问:
AngularJs - Displaying username password in url
I have a AngularJs application with Webapi (c#). I have a login page but some times when I click on Login button, it adds the user credentials in url which causes security issue.

I am using OWIN for auth.

答:
I have been puzzling a similar error in my application for a bit. I was confused because we definitely weren't explicitly adding the username & password to the URL, and it only happened in certain scenarios - not all the time.

Eventually, today, I got down to the bottom of it.

I discovered that it's default HTML behaviour to add form parameters to the URL when you don't specify an action or a method. A form method defaults to GET which explains why the parameters get added to the URL.

I then discovered that the Angular controller method specified in "ng-submit" for the form element was not being called at all.

When I examined the Javascript errors logged in the Console, I realised that the Angular container was not being loaded due to an unhandled exception that was thrown when the login page was being rendered.

Our specific situation was that the frontend (Angular) application was unable to communicate with the backend (Java) API - when we loaded the login page before the backend server container was started up. When that happened, some of the API calls we made during initialisation to load constants from the application's database failed and our application constants were not initialised correctly in the error function. This caused an "Unknown Provider" exception to be thrown which caused the Angular framework to abort initialisation which resulted in the submission of the form being handled by default HTML behaviour!

So I suggest that anyone else facing this issue looks to see if there are any errors being thrown during initialisation of your Angular app.


来源: stackexchange

问:
Where does the Wakanda Enterprise Server license file go, on a Mac OS Sierra system?
Where should the Wakanda Enterprise Server license file be located in a Mac OS Sierra system? I signed up for the 30-day trial, and the instructions said /Document/Wakanda/License, but when I created that path and started the server, it said

"License not found. Server running in Community mode"

I also tried ~/Documents/Wakanda/ and ~/Documents/Wakanda/License/ to no effect.  I can’t seem to find it in the documentation either, can someone point me in the right direction?

答: /Document/Wakanda/License is the correct path, you have to create only the file "License" and put on it the license.key file and restart Wakanda Studio and Server.</p>

ContentLicense: CC BY-SA 3.0


问:
Access div using JQuery
Anobody suggest me how to access DIV in td

```<code><table border="0" cellpadding="0" cellspacing="0" width="95%">
    <tr>
        <td valign="top" style="width:25%">
            <img src="../NewsImages/82010437713162453512.bmp" id="rptAllNewsContent__ctl1_imgNews" width="120" height="120" />
        </td>
        <td valign="top" align="left" style="width:*;padding-left:7px;">
            dsdsdsd
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td align="left" style="width:20%;"><a id="rptAllNewsContent__ctl1_lnkbtnTotalComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl1$lnkbtnTotalComments','')" style="color:#80C355;">2 Comments</a></td>
                    <td align="left"><a id="rptAllNewsContent__ctl1_lnkbtnAddComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl1$lnkbtnAddComments','')" style="color:#80C355;">Add Comments</a></td>
                </tr>
            </table>
        </td>
    </tr>
    <tr><td colspan="2" style="height:13px;"></td></tr>
    <tr>
        <td>
            <div id="rptAllNewsContent__ctl1_divComment">
            sdfasdasda
            sdsa
            d
            asdas
            </div>
        </td>
    </tr>
    <tr>
        <td valign="top" style="width:25%">
            <img src="../NewsImages/8201010976151655912.jpg" id="rptAllNewsContent__ctl2_imgNews" width="120" height="120" />
        </td>
        <td valign="top" align="left" style="width:*;padding-left:7px;">
            dasdasd
        </td>
        </tr>
        <tr>
            <td colspan="2">
                <table border="0" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td align="left" style="width:20%;"><a id="rptAllNewsContent__ctl2_lnkbtnTotalComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl2$lnkbtnTotalComments','')" style="color:#80C355;">3 Comments</a></td>
                        <td align="left"><a id="rptAllNewsContent__ctl2_lnkbtnAddComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl2$lnkbtnAddComments','')" style="color:#80C355;">Add Comments</a></td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr><td colspan="2" style="height:13px;"></td></tr>
        <tr>
            <td>
                <div id="rptAllNewsContent__ctl2_divComment">
                sdfasdasda
                sdsa
                d
                asdas
                </div>
            </td>
        </tr>
    </table>
</code>```

I tried in this way but doesn't work.

```<code>$(document).ready(function(){
    $("a[id$='lnkbtnTotalComments']").click(function(){
        $(this).parent("td").parent("tr").next("tr").next("tr td").find("div").text();
        return false;
    });
    });
</code>```

答:
What about:

```<code>$(document).ready(function() {
    var totalCommentsSel = "a[id$='lnkbtnTotalComments']",
        commentsContSel = "div[id$='divComment']",
        wrapper = "table";

    $(totalComments).click(function(e){
        var commentsDiv = $(this).closest(wrapper).find(commentsContSel);
        // Use commentsDiv below

        // Prevent the click from redirecting, but allow further propagation
        e.preventDefault();
    });
});
</code>```

EDIT:
This one does work (tested), but it's not pretty code. Any way you could change into a nicer markup?

```<code>$(document).ready(function() {
    var totalCommentsSel = "a[id$='lnkbtnTotalComments']",
        commentsContSel = "div[id$='divComment']";

        $(totalCommentsSel).click(function(e){
            var $wrapper = $(this).closest('table').closest('tr').next().next(),
                commentsDiv = $wrapper.find(commentsContSel);
                // Use commentsDiv below

                console.info($wrapper.length, commentsDiv.length, commentsDiv.length);
                // Prevent the click from redirecting, but allow further propagation
                return false;
            });
        });
</code>```

ContentLicense: CC BY-SA 2.5

Title: Access div using JQuery

Body:
Anobody suggest me how to access DIV in td

            dsdsdsd

                    2 Comments
                    Add Comments

            sdfasdasda
            sdsa
            d
            asdas

            dasdasd

                        3 Comments
                        Add Comments

                sdfasdasda
                sdsa
                d
                asdas

I tried in this way but doesn't work.

$(document).ready(function(){
    $("a[id$='lnkbtnTotalComments']").click(function(){
        $(this).parent("td").parent("tr").next("tr").next("tr td").find("div").text();
        return false;
    });
    });

Body:
What about:

$(document).ready(function() {
    var totalCommentsSel = "a[id$='lnkbtnTotalComments']",
        commentsContSel = "div[id$='divComment']",
        wrapper = "table";

    $(totalComments).click(function(e){
        var commentsDiv = $(this).closest(wrapper).find(commentsContSel);
        // Use commentsDiv below

        // Prevent the click from redirecting, but allow further propagation
        e.preventDefault();
    });
});

EDIT:
This one does work (tested), but it's not pretty code. Any way you could change into a nicer markup?

$(document).ready(function() {
    var totalCommentsSel = "a[id$='lnkbtnTotalComments']",
        commentsContSel = "div[id$='divComment']";

        $(totalCommentsSel).click(function(e){
            var $wrapper = $(this).closest('table').closest('tr').next().next(),
                commentsDiv = $wrapper.find(commentsContSel);
                // Use commentsDiv below

                console.info($wrapper.length, commentsDiv.length, commentsDiv.length);
                // Prevent the click from redirecting, but allow further propagation
                return false;
            });
        });


问:
How number of items in IN clause relates to index usage
I'm trying to optimize a query but I'm seeing a weird behavior I don't understand.

I have a table contains almost 2 million records, with an index on column "status_code" which is tinyint.

When I call the query with 10 numbers in In clause, mysql do a full table scan

```<code>select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9,10);
</code>```

When I call it with 9 numbers in the IN clause, the index is used.

```<code>select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9);
</code>```

Note: Number of rows here is '9' although the query returns only 1 row.

I'm using Amazon RDS, I need to understand why is this behavior, and if there is any kind of configuration that controls this.

答:
When you use the IN() predicate, MySQL would have to analyze the index for each value in your list, estimating the benefit of using the index. When you use long lists of values, calculating the optimizer's estimate becomes expensive, even before executing the query.

In MySQL 5.6, they established a threshold so a list of 10 or more items in an IN() predicate skipped the index-dive-per-value work, and just guessed at the value of using the index based on previously collected stats about the index. This is documented here: https://dev.mysql.com/doc/refman/5.6/en/range-optimization.html in the subsection "Equality Range Optimization of Many-Valued Comparisons."

You can tune the threshold with the variable eq_range_index_dive_limit. In MySQL 5.6, the default is 10. In MySQL 5.7, they realized that the default of 10 was too small, so they increased the default value to 200. You could change this variable to 200 to be like the MySQL 5.7 behavior.

I notice you are using RDS. The default on RDS is sometimes different from the default in stock MySQL, so the default might be 10 even if you're using RDS based on MySQL 5.7. Review your db parameter group.

Body:
I'm trying to optimize a query but I'm seeing a weird behavior I don't understand.

I have a table contains almost 2 million records, with an index on column "status_code" which is tinyint.

When I call the query with 10 numbers in In clause, mysql do a full table scan

select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9,10);

When I call it with 9 numbers in the IN clause, the index is used.

select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9);

Note: Number of rows here is '9' although the query returns only 1 row.

I'm using Amazon RDS, I need to understand why is this behavior, and if there is any kind of configuration that controls this.


问:
Sendemail on Linux Debian Wheezy gives errors on gmail and gmx accounts
I am using the SendEmail SMTP client (http://caspian.dotconf.net/menu/Software/SendEmail/) on a Beaglebone black running the Debian Wheezy Linux distro.

This tool is exactly what I need but I am having a few problems with it. Bear in mind that I am a Linux Newbie.

Firstly, the latest SendEmail package for Debian Wheezy is 1.56-2 (https://packages.debian.org/source/wheezy/sendemail).  A later package (1.56-5) is available for other Debian distros (e.g. Sid/Jessie) but not for Wheezy.  Anyone know why this is?

I have also using libio-socket-ssl-perl 1.76-2,  libnet-ssleay-per 1.48-1+b1, perl 5.14.2-21+deb7u2.

Secondly, I am testing using GMAIL and GMX accounts on ports 465 and 587.  Note that I have tested these using a different OS (not Linux) with my own SMTP client with PolarSLL and the accounts all work OK.

However, they do not seem to work when using SendEmail on Linux Debian Wheezy.  The problems I am having are:

```<code>GMAIL port 587 (STARTTLS)  FAILS:
Jun 12 10:39:55 beaglebone sendEmail[3686]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:39:55 beaglebone sendEmail[3686]: SUCCESS => Received:        220 mx.google.com ESMTP ha4sm2142303wib.0 - gsmtp
Jun 12 10:39:55 beaglebone sendEmail[3686]: INFO => Sending:    EHLO beaglebone
Jun 12 10:39:55 beaglebone sendEmail[3686]: SUCCESS => Received:        250-mx.google.com at your service, [92.19.250.250], 250-SIZE 35882577, 250-8BITMIME, 250-STARTTLS, 250-ENHANCEDSTATUSCODES, 250-PIPELINING, 250-CHUNKING, 250 SMTPUTF8
Jun 12 10:39:55 beaglebone sendEmail[3686]: INFO => Sending:    STARTTLS
Jun 12 10:39:55 beaglebone sendEmail[3686]: SUCCESS => Received:        220 2.0.0 Ready to start TLS
invalid SSL_version specified at /usr/share/perl5/IO/Socket/SSL.pm line 332
</code>```

Various forums mention that the fix/workaround for this is to change line 1490 in "SSL.pm"

from

```<code>m{^(!?)(?:(SSL(?:v2|v3|v23|v2/3))|(TLSv1[12]?))$}i
</code>```

to

```<code>m{^(!?)(?:(SSL(?:v2|v3|v23|v2/3))|(TLSv1[12]?))}i
</code>```

This does fix the problem. Perhaps this fix is not required if 1.56-5 was available for Wheezy?

The following accounts give the same results regardless of whether the above fix is implemented or not.

```<code>GMAIL port 465 (SSL) FAILS:
Jun 12 10:32:43 beaglebone sendEmail[3537]: DEBUG => Connecting to smtp.gmail.com:465
Jun 12 10:32:43 beaglebone sendEmail[3537]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:33:43 beaglebone sendEmail[3537]: ERROR => Timeout while reading from smtp.gmail.com:465 There was no response after 60 seconds.

GMX port 587 (STARTTLS)  FAILS:
Jun 12 10:35:12 beaglebone sendEmail[3586]: DEBUG => Connecting to mail.gmx.com:587
Jun 12 10:35:13 beaglebone sendEmail[3586]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:35:13 beaglebone sendEmail[3586]: SUCCESS => Received:        220 gmx.com (mrgmx103) Nemesis ESMTP Service ready
Jun 12 10:35:13 beaglebone sendEmail[3586]: INFO => Sending:    EHLO beaglebone
Jun 12 10:35:13 beaglebone sendEmail[3586]: SUCCESS => Received:        250-gmx.com Hello beaglebone [92.19.250.250], 250-SIZE 69920427, 250-AUTH LOGIN PLAIN, 250 STARTTLS
Jun 12 10:35:13 beaglebone sendEmail[3586]: INFO => Sending:    STARTTLS
Jun 12 10:35:13 beaglebone sendEmail[3586]: SUCCESS => Received:        220 OK
Jun 12 10:35:13 beaglebone sendEmail[3586]: ERROR => TLS setup failed: SSL connect attempt failed with unknown error error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

GMX port 465 (SSL) FAILS:
Jun 12 10:36:23 beaglebone sendEmail[3619]: DEBUG => Connecting to mail.gmx.com:465
Jun 12 10:36:23 beaglebone sendEmail[3619]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:36:33 beaglebone sendEmail[3619]: ERROR => mail.gmx.com:465 returned a zero byte response to our query.
</code>```

Can anyone help?

Thanks

答:
I have same error (in debian jessie), and I solved installing package ca-certificates

```<code>apt-get install ca-certificates
</code>```

Body:
I am using the SendEmail SMTP client (http://caspian.dotconf.net/menu/Software/SendEmail/) on a Beaglebone black running the Debian Wheezy Linux distro.

This tool is exactly what I need but I am having a few problems with it. Bear in mind that I am a Linux Newbie.

Firstly, the latest SendEmail package for Debian Wheezy is 1.56-2 (https://packages.debian.org/source/wheezy/sendemail).  A later package (1.56-5) is available for other Debian distros (e.g. Sid/Jessie) but not for Wheezy.  Anyone know why this is?

I have also using libio-socket-ssl-perl 1.76-2,  libnet-ssleay-per 1.48-1+b1, perl 5.14.2-21+deb7u2.

Secondly, I am testing using GMAIL and GMX accounts on ports 465 and 587.  Note that I have tested these using a different OS (not Linux) with my own SMTP client with PolarSLL and the accounts all work OK.

However, they do not seem to work when using SendEmail on Linux Debian Wheezy.  The problems I am having are:

GMAIL port 587 (STARTTLS)  FAILS:
Jun 12 10:39:55 beaglebone sendEmail[3686]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:39:55 beaglebone sendEmail[3686]: SUCCESS => Received:        220 mx.google.com ESMTP ha4sm2142303wib.0 - gsmtp
Jun 12 10:39:55 beaglebone sendEmail[3686]: INFO => Sending:    EHLO beaglebone
Jun 12 10:39:55 beaglebone sendEmail[3686]: SUCCESS => Received:        250-mx.google.com at your service, [92.19.250.250], 250-SIZE 35882577, 250-8BITMIME, 250-STARTTLS, 250-ENHANCEDSTATUSCODES, 250-PIPELINING, 250-CHUNKING, 250 SMTPUTF8
Jun 12 10:39:55 beaglebone sendEmail[3686]: INFO => Sending:    STARTTLS
Jun 12 10:39:55 beaglebone sendEmail[3686]: SUCCESS => Received:        220 2.0.0 Ready to start TLS
invalid SSL_version specified at /usr/share/perl5/IO/Socket/SSL.pm line 332

Various forums mention that the fix/workaround for this is to change line 1490 in "SSL.pm"

from

m{^(!?)(?:(SSL(?:v2|v3|v23|v2/3))|(TLSv1[12]?))$}i

to

m{^(!?)(?:(SSL(?:v2|v3|v23|v2/3))|(TLSv1[12]?))}i

This does fix the problem. Perhaps this fix is not required if 1.56-5 was available for Wheezy?

The following accounts give the same results regardless of whether the above fix is implemented or not.

GMAIL port 465 (SSL) FAILS:
Jun 12 10:32:43 beaglebone sendEmail[3537]: DEBUG => Connecting to smtp.gmail.com:465
Jun 12 10:32:43 beaglebone sendEmail[3537]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:33:43 beaglebone sendEmail[3537]: ERROR => Timeout while reading from smtp.gmail.com:465 There was no response after 60 seconds.

GMX port 587 (STARTTLS)  FAILS:
Jun 12 10:35:12 beaglebone sendEmail[3586]: DEBUG => Connecting to mail.gmx.com:587
Jun 12 10:35:13 beaglebone sendEmail[3586]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:35:13 beaglebone sendEmail[3586]: SUCCESS => Received:        220 gmx.com (mrgmx103) Nemesis ESMTP Service ready
Jun 12 10:35:13 beaglebone sendEmail[3586]: INFO => Sending:    EHLO beaglebone
Jun 12 10:35:13 beaglebone sendEmail[3586]: SUCCESS => Received:        250-gmx.com Hello beaglebone [92.19.250.250], 250-SIZE 69920427, 250-AUTH LOGIN PLAIN, 250 STARTTLS
Jun 12 10:35:13 beaglebone sendEmail[3586]: INFO => Sending:    STARTTLS
Jun 12 10:35:13 beaglebone sendEmail[3586]: SUCCESS => Received:        220 OK
Jun 12 10:35:13 beaglebone sendEmail[3586]: ERROR => TLS setup failed: SSL connect attempt failed with unknown error error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

GMX port 465 (SSL) FAILS:
Jun 12 10:36:23 beaglebone sendEmail[3619]: DEBUG => Connecting to mail.gmx.com:465
Jun 12 10:36:23 beaglebone sendEmail[3619]: DEBUG => My IP address is: 192.168.1.224
Jun 12 10:36:33 beaglebone sendEmail[3619]: ERROR => mail.gmx.com:465 returned a zero byte response to our query.

Can anyone help?

Thanks

Body:
I have same error (in debian jessie), and I solved installing package ca-certificates

apt-get install ca-certificates


问:
Open more than 15 Files by Context Menu without MultipleInvokePromptMinimum
I have already added a right click option to open files with my c++ program:

```<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\Open With MyProgram]
"Icon"="\"C:\\Program Files (x86)\\myProgram.exe\""

[HKEY_CLASSES_ROOT\*\shell\Open With MyProgram\command]
@="\"C:\\Program Files (x86)\\myProgram.exe\" \"%1\""
</code>```

This is working just fine. When I select more than 15 files the right click option disappears.
I already read about the following method with MultipleInvokePromptMinimum:

```<code>[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer]
"MultipleInvokePromptMinimum"=dword:00001388
</code>```

This would do the job, the only problem is that I dont want to enable other "open" or "print" right click options for more than 15 files, just my custom one.

(The "Edit with Notepad++" right click option for example is enabled for more than 15 files without changing the MultipleInvokePromptMinimum)

Whats the best way to achieve this? Thanks in advance.

答:
As you have already figured out from the comments, a plain static verb has a limit that can be bumped up to 100 by setting MultiSelectModel to player. Explorer only allows COM based shell extensions to go beyond this limit.

There are multiple types of shell extensions you could implement depending on your minimum supported Windows version:

IExecuteCommand is the least amount of work but it is only usable on Windows 7 and later. Tutorial/example can be found here.

IDropTarget needs a full COM server but works on Windows XP and later. Tutorial/example can be found here.

IContextMenu registered under ShellEx\ContextMenuHandlers works on every Windows version but the selection limit does not exist on these old systems so there is no need to implement this in your case.

It is recommended that you write your extension in C/C++ or Delphi and not in a .NET language like C# (this is a recommendation or requirement depending on the Windows and .NET version).

Body:
I have already added a right click option to open files with my c++ program:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\Open With MyProgram]
"Icon"="\"C:\\Program Files (x86)\\myProgram.exe\""

[HKEY_CLASSES_ROOT\*\shell\Open With MyProgram\command]
@="\"C:\\Program Files (x86)\\myProgram.exe\" \"%1\""

This is working just fine. When I select more than 15 files the right click option disappears.
I already read about the following method with MultipleInvokePromptMinimum:

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer]
"MultipleInvokePromptMinimum"=dword:00001388

This would do the job, the only problem is that I dont want to enable other "open" or "print" right click options for more than 15 files, just my custom one.

(The "Edit with Notepad++" right click option for example is enabled for more than 15 files without changing the MultipleInvokePromptMinimum)

Whats the best way to achieve this? Thanks in advance.


问:
How do you dynamically allocate a matrix?
How do you dynamically allocate a 2D matrix in C++?
I have tried based on what I already know:

```<code>#include <iostream>

int main(){
    int rows;
    int cols;
    int * arr;
    arr = new int[rows][cols];
 }
</code>```

It works for one parameter, but now for two. What should I do?

答:
```<code>const int nRows = 20;
const int nCols = 10;
int (*name)[nCols] = new int[nRows][nCols];
std::memset(name, 0, sizeof(int) * nRows * nCols); //row major contiguous memory
name[0][0] = 1; //first element
name[nRows-1][nCols-1] = 1; //last element
delete[] name;
</code>```

Body:
How do you dynamically allocate a 2D matrix in C++?
I have tried based on what I already know:

#include <iostream>

int main(){
    int rows;
    int cols;
    int * arr;
    arr = new int[rows][cols];
 }

It works for one parameter, but now for two. What should I do?


问:
Back button from activity 2 closes down the app instead of going to activity 1 in Android 7
Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.

Then the whole app closed when pressing back button from the second activity.

I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.

I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.

It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).

Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:

Activity 1:

```<code>Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
</code>```

答:
The below code should be used in 2nd activity so that   when u press back button it terminates the current activity(2nd activity) and goes back to previous activity</p>

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}
</code>```

Body:
Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.

Then the whole app closed when pressing back button from the second activity.

I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.

I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.

It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).

Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:

Activity 1:

Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

Body:
The below code should be used in 2nd activity so that   when u press back button it terminates the current activity(2nd activity) and goes back to previous activity

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}


问:
Unable to use RadioButton with JQuery - Alert doesn't pop up
I have two radio buttons and I want to display an alert when one of them is checked, it seems that the problem is that it doesn't recognize the element because the alert doesn't pop up!

This code used to work but it doesn't anymore (I think I changed the Id of one of the elements and that's what caused the issue)

JS:

```<code>/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});
</code>```

HTML

```<code>    <form method='post' id='prechatForm' autocomplete="on">
        <div id="bankEmployeeYesNoRadioButtonDiv">
          <label>{!$Label.Bank_Employee}</label><br/>
          <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
          <label for="radio-2" class="radioLabel">{!$Label.No}</label>
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>
        </div>
</form>
</code>```

Result: When I click on a radio button nothing happens, no alert.
No Console Errors
Notes: Please note that I'm using Salesforce (Visualforce) syntax.

答:
your jquery selector is wrong, so change this:

```<code><div id="bankEmployeeYesNoRadioButtonDiv">
  <label>{!$Label.Bank_Employee}</label><br/>
  <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
  <label for="radio-2" class="radioLabel">{!$Label.No}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>
</div>
</code>```

to:

```<code><form id="bankEmployeeYesNoRadioButtonDiv">
  <label>{!$Label.Bank_Employee}</label><br/>
  <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
  <label for="radio-2" class="radioLabel">{!$Label.No}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>
</form>
</code>```

Body:
I have two radio buttons and I want to display an alert when one of them is checked, it seems that the problem is that it doesn't recognize the element because the alert doesn't pop up!

This code used to work but it doesn't anymore (I think I changed the Id of one of the elements and that's what caused the issue)

JS:

/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});

HTML

    <form method='post' id='prechatForm' autocomplete="on">

          {!$Label.Bank_Employee}

          {!$Label.Yes}
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
          {!$Label.No}
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>

</form>

Result: When I click on a radio button nothing happens, no alert.
No Console Errors
Notes: Please note that I'm using Salesforce (Visualforce) syntax.

Body:
your jquery selector is wrong, so change this:

<div id="bankEmployeeYesNoRadioButtonDiv">
  <label>{!$Label.Bank_Employee}</label><br/>
  <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
  <label for="radio-2" class="radioLabel">{!$Label.No}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>
</div>

to:

<form id="bankEmployeeYesNoRadioButtonDiv">
  <label>{!$Label.Bank_Employee}</label><br/>
  <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
  <label for="radio-2" class="radioLabel">{!$Label.No}</label>
  <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>
</form>


问:
How to set image as hyperlink in windows form at design time
I want to set image as hyperlink in windows form at design time. May I know which class should I use, and property I need to set to enable this requirement?</p>

答:
if you want to open an other window (e.g. Form2) you can write your code in Click event:

```<code>private void PictureBox1_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    frm.Show();
}
</code>```

And if you want to open a folder in windows explorer, you should do it like so:

```<code>private void PictureBox1_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process.Start("explorer.exe", @"d:\");
}
</code>```

Body:
if you want to open an other window (e.g. Form2) you can write your code in Click event:

private void PictureBox1_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    frm.Show();
}

And if you want to open a folder in windows explorer, you should do it like so:

private void PictureBox1_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process.Start("explorer.exe", @"d:\");
}


问:
Why is my query performing a Clustered Index Scan
I have a query that tries to find all records within a certain bounding box [geocode lookup].

After running the query plan through the RedGate profiler it spends an awfully large amount of time inside a Clustered Index Scan (below) (offending query at the bottom of question).  This is my slowest running query and I guess there is something wrong with it because of this final step taking so long?

After having looked around SO and Google I decided to include all columns of the table inside my index. Here are what indexes I have

PK on the Id.

Index on [UTC_UPDATED Desc, North, East, South, West] [includes all other columns to try avoid scan]

Index on [UTC_UPDATED Desc, Source Desc]

Query:

```<code>SET ANSI_NULLS ON; SET ANSI_PADDING ON; SET ANSI_WARNINGS ON; SET ARITHABORT OFF; SET CONCAT_NULL_YIELDS_NULL ON; SET NUMERIC_ROUNDABORT OFF; SET QUOTED_IDENTIFIER ON

(@p__linq__0 datetime2(7),@p__linq__1 float,@p__linq__2 float,@p__linq__3 float,@p__linq__4 float)SELECT
    [Project1].[ID] AS [ID],
    [Project1].[CENTER] AS [CENTER],
    [Project1].[BOUNDS] AS [BOUNDS],
    [Project1].[UTC_UPDATED] AS [UTC_UPDATED],
    [Project1].[PLACE_ID] AS [PLACE_ID],
    [Project1].[FORMATTED_ADDRESS] AS [FORMATTED_ADDRESS],
    [Project1].[POST_CODE] AS [POST_CODE],
    [Project1].[SOURCE] AS [SOURCE],
    [Project1].[North] AS [North],
    [Project1].[East] AS [East],
    [Project1].[South] AS [South],
    [Project1].[West] AS [West]
    FROM ( SELECT
        [Extent1].[ID] AS [ID],
        [Extent1].[CENTER] AS [CENTER],
        [Extent1].[BOUNDS] AS [BOUNDS],
        [Extent1].[UTC_UPDATED] AS [UTC_UPDATED],
        [Extent1].[PLACE_ID] AS [PLACE_ID],
        [Extent1].[FORMATTED_ADDRESS] AS [FORMATTED_ADDRESS],
        [Extent1].[POST_CODE] AS [POST_CODE],
        [Extent1].[SOURCE] AS [SOURCE],
        [Extent1].[North] AS [North],
        [Extent1].[East] AS [East],
        [Extent1].[South] AS [South],
        [Extent1].[West] AS [West]
        FROM [dbo].[HST_GEOCODE_POINTS] AS [Extent1]
        WHERE ([Extent1].[UTC_UPDATED] > @p__linq__0)
            AND ([Extent1].[North] >= @p__linq__1)
            AND ([Extent1].[East] >= @p__linq__2)
            AND ([Extent1].[South] <= @p__linq__3)
            AND ([Extent1].[West] <= @p__linq__4)
    )  AS [Project1]
    ORDER BY [Project1].[UTC_UPDATED] DESC, [Project1].[SOURCE] DESC
</code>```

Note Bounds and Center are Geography types.  I initially used Intersects to find the correct Geocoded address but it was so slow I opted to find the rough NESW bounding box using SQL [they are simply doubles] and then intersect in code [.NET].

答: Whether SQL Server decides to do a scan or a seek depends on the selectivity of your query. In your case a scan is simply less expensive than a seek. Whether the index covers the query or not is not an issue. Please read about the tipping point.</p>

Body:
I have a query that tries to find all records within a certain bounding box [geocode lookup].

After running the query plan through the RedGate profiler it spends an awfully large amount of time inside a Clustered Index Scan (below) (offending query at the bottom of question).  This is my slowest running query and I guess there is something wrong with it because of this final step taking so long?

After having looked around SO and Google I decided to include all columns of the table inside my index. Here are what indexes I have

PK on the Id.

Index on [UTC_UPDATED Desc, North, East, South, West] [includes all other columns to try avoid scan]

Index on [UTC_UPDATED Desc, Source Desc]

Query:

SET ANSI_NULLS ON; SET ANSI_PADDING ON; SET ANSI_WARNINGS ON; SET ARITHABORT OFF; SET CONCAT_NULL_YIELDS_NULL ON; SET NUMERIC_ROUNDABORT OFF; SET QUOTED_IDENTIFIER ON

(@p__linq__0 datetime2(7),@p__linq__1 float,@p__linq__2 float,@p__linq__3 float,@p__linq__4 float)SELECT
    [Project1].[ID] AS [ID],
    [Project1].[CENTER] AS [CENTER],
    [Project1].[BOUNDS] AS [BOUNDS],
    [Project1].[UTC_UPDATED] AS [UTC_UPDATED],
    [Project1].[PLACE_ID] AS [PLACE_ID],
    [Project1].[FORMATTED_ADDRESS] AS [FORMATTED_ADDRESS],
    [Project1].[POST_CODE] AS [POST_CODE],
    [Project1].[SOURCE] AS [SOURCE],
    [Project1].[North] AS [North],
    [Project1].[East] AS [East],
    [Project1].[South] AS [South],
    [Project1].[West] AS [West]
    FROM ( SELECT
        [Extent1].[ID] AS [ID],
        [Extent1].[CENTER] AS [CENTER],
        [Extent1].[BOUNDS] AS [BOUNDS],
        [Extent1].[UTC_UPDATED] AS [UTC_UPDATED],
        [Extent1].[PLACE_ID] AS [PLACE_ID],
        [Extent1].[FORMATTED_ADDRESS] AS [FORMATTED_ADDRESS],
        [Extent1].[POST_CODE] AS [POST_CODE],
        [Extent1].[SOURCE] AS [SOURCE],
        [Extent1].[North] AS [North],
        [Extent1].[East] AS [East],
        [Extent1].[South] AS [South],
        [Extent1].[West] AS [West]
        FROM [dbo].[HST_GEOCODE_POINTS] AS [Extent1]
        WHERE ([Extent1].[UTC_UPDATED] > @p__linq__0)
            AND ([Extent1].[North] >= @p__linq__1)
            AND ([Extent1].[East] >= @p__linq__2)
            AND ([Extent1].[South] <= @p__linq__3)
            AND ([Extent1].[West] <= @p__linq__4)
    )  AS [Project1]
    ORDER BY [Project1].[UTC_UPDATED] DESC, [Project1].[SOURCE] DESC

Note Bounds and Center are Geography types.  I initially used Intersects to find the correct Geocoded address but it was so slow I opted to find the rough NESW bounding box using SQL [they are simply doubles] and then intersect in code [.NET].


问:
Passing arguments to a Scala udf
I am calling a udf on a specific column of my dataframe, in which I check if all values are valid as per a specified date format.

```<code>sourcefile = sourcefile.withColumn(column, DateConversion(col(column)))
</code>```

Here DateConversion is my udf. My question here is that, is there a way  by which I can pass the valid date format "yyyy/MM/dd" as a string to this udf which can be used internally in the udf for validation purposes.

I was trying

```<code>sourcefile = sourcefile.withColumn(column, DateConversion(col(column),"yyyy/MM/dd"))
</code>```

But this gives and error.

答:
You can just curry the udf, passing in the date format - or really any other argument you want - when the udf is created.

```<code>def getUdf(format: String) = udf{date: String =>
  /*some logic that uses format*/}
</code>```

And then call that method like so

```<code>val dateConversion = getUdf("yyyy/MM/dd")
sourcefile = sourcefile.withColumn(column, dateConversion(col(column)))
</code>```

This will also allow you to easily swap out the date conversion format, by changing the argument passed to getUdf, rather than the difficulty if the format is hardcoded inside the udf

ContentLicense: CC BY-SA 4.0

Title: Passing arguments to a Scala udf

Body:
I am calling a udf on a specific column of my dataframe, in which I check if all values are valid as per a specified date format.

sourcefile = sourcefile.withColumn(column, DateConversion(col(column)))

Here DateConversion is my udf. My question here is that, is there a way  by which I can pass the valid date format "yyyy/MM/dd" as a string to this udf which can be used internally in the udf for validation purposes.

I was trying

sourcefile = sourcefile.withColumn(column, DateConversion(col(column),"yyyy/MM/dd"))

But this gives and error.

Body:
You can just curry the udf, passing in the date format - or really any other argument you want - when the udf is created.

def getUdf(format: String) = udf{date: String =>
  /*some logic that uses format*/}

And then call that method like so

val dateConversion = getUdf("yyyy/MM/dd")
sourcefile = sourcefile.withColumn(column, dateConversion(col(column)))

This will also allow you to easily swap out the date conversion format, by changing the argument passed to getUdf, rather than the difficulty if the format is hardcoded inside the udf


问:
Sas process sql
I am trying to select from a SQL server table that both has dashes in the name and is greater than 32 characters.

I have tried pass through and quotes but no joy.

It's very unlikely that I could get a view produced and only have read access.

```<code>proc sql;
    drop table poss_gw1;
    create table poss_gw1 as ( select * from cdb.'''form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71'''n as agg);
quit;

proc sql;
    connect to odbc(dsn=FirmstepReporting user=myname pwd=mypwd);
    Create table work.tmp_gw as select * from connection to odbc (select * from "'form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71'"n);
    disconnect from odbc;
quit;
</code>```

Any one have any ideas?

答:
You need to use SQL Server syntax in the pass thru code.

```<code>create table work.tmp_gw as
select * from connection to odbc
(select *
 from "form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71"
);
</code>```

If your variable names are also not valid for SAS then you will need to change the name in the pass thru code also.

```<code>create table work.tmp_gw as
select * from connection to odbc
(select id
      , "invalid-name" as valid_name
 from "form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71"
);
</code>```

Title: Sas process sql

Body:
I am trying to select from a SQL server table that both has dashes in the name and is greater than 32 characters.

I have tried pass through and quotes but no joy.

It's very unlikely that I could get a view produced and only have read access.

proc sql;
    drop table poss_gw1;
    create table poss_gw1 as ( select * from cdb.'''form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71'''n as agg);
quit;

proc sql;
    connect to odbc(dsn=FirmstepReporting user=myname pwd=mypwd);
    Create table work.tmp_gw as select * from connection to odbc (select * from "'form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71'"n);
    disconnect from odbc;
quit;

Any one have any ideas?

Body:
You need to use SQL Server syntax in the pass thru code.

create table work.tmp_gw as
select * from connection to odbc
(select *
 from "form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71"
);

If your variable names are also not valid for SAS then you will need to change the name in the pass thru code also.

create table work.tmp_gw as
select * from connection to odbc
(select id
      , "invalid-name" as valid_name
 from "form_Garden_waste_service_AF-Form-59fb9946-0f6e-4cd9-9b30-82fc5d96ec71"
);


问:
Unspecified error while executing sql query vba on Oracle database
I want to import data from Oracle database to Excel using VBA. I've tried several options I found in here or in the official manual but none of them seem to work for me - I always get the same unspecified runtime error on line with

```<code>rs.Open strSQL1, con
</code>```

or

```<code>Set rs = con.Execute(strSQL1)
</code>```

depending on which one of these two methods I use obviously. Here is the whole code:

```<code>Sub data_distribution()

'Setting up the database connection
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL1, strInput, strCon As String

Set con = New ADODB.Connection
Set rs = New ADODB.Recordset

strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=XXX)(PORT=XXX))" & _
"(CONNECT_DATA=(SERVICE_NAME=XXX))); uid=XXX; pwd=XXX;"

'---  Open the above connection string.
con.ConnectionString = strCon
con.Open
'con.Open strCon

'---  Now connection is open and you can use queries to execute them.
'---  It will be open till you close the connection

'Definition of parameter
strInput = InputBox("Insert car_id")

strSQL1 = "select * from car where car_id = " & strInput & ""

'Executing the query
'rs.activeconnection = con
'rs.Open strSQL1, con

Set rs = con.Execute(strSQL1)
rs.Open strSQL1, con

Worksheets("Data").Range("A2").CopyFromRecordset rs

'Closing connection
rs.Close
con.Close
Set con = Nothing
Set rs = Nothing
</code>```

I was thinking it might be an issue of connecting to the database but if I import/query data manual, it works just fine. For example using this manual

http://blog.mclaughlinsoftware.com/microsoft-excel/how-to-query-oracle-from-excel-2007/

I had to download and configure ODAC for Windows from Oracle site to make it work. I use tsnames.ora to set the path. Wasn't sure if I configured it right but it works so I guess there isn't a problem with the connection in vba either, or is it? (The variables are, of course, set to real values, not "XXX")

The query itself is correct and returns valid results from the database. Libraries necessary to use ADOBD are linked as well. (Microsoft ActiveX Data Objects 2.0 Library)

There is an existing question with the same error but it's unresolved:

Unspecified run time error while executing vba script

I'm guessing it's station/interface specific (I use Excel 2010, SQL developer).

答:
Even though it's been some time I asked the question, here, it's still unresolved so I will answer myself.

The problem was in the car table where one of the attributes was type CLOB (CHARACTER LARGE OBJECT) with lenght over 2000 characters. Excel was unable to cope with that type and the query caused the unspecified error. If I listed all attributes but this one, it all went well.

Body:
I want to import data from Oracle database to Excel using VBA. I've tried several options I found in here or in the official manual but none of them seem to work for me - I always get the same unspecified runtime error on line with

rs.Open strSQL1, con

or

Set rs = con.Execute(strSQL1)

depending on which one of these two methods I use obviously. Here is the whole code:

Sub data_distribution()

'Setting up the database connection
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL1, strInput, strCon As String

Set con = New ADODB.Connection
Set rs = New ADODB.Recordset

strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=XXX)(PORT=XXX))" & _
"(CONNECT_DATA=(SERVICE_NAME=XXX))); uid=XXX; pwd=XXX;"

'---  Open the above connection string.
con.ConnectionString = strCon
con.Open
'con.Open strCon

'---  Now connection is open and you can use queries to execute them.
'---  It will be open till you close the connection

'Definition of parameter
strInput = InputBox("Insert car_id")

strSQL1 = "select * from car where car_id = " & strInput & ""

'Executing the query
'rs.activeconnection = con
'rs.Open strSQL1, con

Set rs = con.Execute(strSQL1)
rs.Open strSQL1, con

Worksheets("Data").Range("A2").CopyFromRecordset rs

'Closing connection
rs.Close
con.Close
Set con = Nothing
Set rs = Nothing

I was thinking it might be an issue of connecting to the database but if I import/query data manual, it works just fine. For example using this manual

http://blog.mclaughlinsoftware.com/microsoft-excel/how-to-query-oracle-from-excel-2007/

I had to download and configure ODAC for Windows from Oracle site to make it work. I use tsnames.ora to set the path. Wasn't sure if I configured it right but it works so I guess there isn't a problem with the connection in vba either, or is it? (The variables are, of course, set to real values, not "XXX")

The query itself is correct and returns valid results from the database. Libraries necessary to use ADOBD are linked as well. (Microsoft ActiveX Data Objects 2.0 Library)

There is an existing question with the same error but it's unresolved:

Unspecified run time error while executing vba script

I'm guessing it's station/interface specific (I use Excel 2010, SQL developer).


问:
How to redirect to other views after file download using backbone js?
I am using backbone js and atmosphere js in my application.
I have two tabs on my view as Delete and Download. I am able to download file using following code:

```<code>var link = "/myEndPointURL?download?id=1234";
$downloadButton.off("click").on("click", function(e){
    window.location.href = link;

});
</code>```

This code downloads file but after downloads the file but after download, when I clicks on delete tab,  I am not able to push that view . It gives me error as "No suspended connection available .....".

Am I using correct approach or do I use any other way.
I do not want to reload page.

Can someone help me to solve above issue?

答:
Download links in single-page apps could simply be a link that opens in another tab or window using target="_blank".

Download
```

That way, you let the browser handle clicking on a link rather than doing it with window.location.href. It also lets the app at the state it was without reloading.

Body:
I am using backbone js and atmosphere js in my application.
I have two tabs on my view as Delete and Download. I am able to download file using following code:

var link = "/myEndPointURL?download?id=1234";
$downloadButton.off("click").on("click", function(e){
    window.location.href = link;

});

This code downloads file but after downloads the file but after download, when I clicks on delete tab,  I am not able to push that view . It gives me error as "No suspended connection available .....".

Am I using correct approach or do I use any other way.
I do not want to reload page.

Can someone help me to solve above issue?

Body:
Download links in single-page apps could simply be a link that opens in another tab or window using target="_blank".

<a href="/myEndPointURL?download?id=1234" target="_blank">Download</a>

That way, you let the browser handle clicking on a link rather than doing it with window.location.href. It also lets the app at the state it was without reloading.


问:
LocalDateTime - deserialization with LocalDateTime.parse
I have the field initiationDate which serialises by ToStringSerializer class to ISO-8601 format.

```<code>@JsonSerialize(using = ToStringSerializer.class)
private LocalDateTime initiationDate;
</code>```

When I receive the following JSON,

```<code>...
"initiationDate": "2016-05-11T17:32:20.897",
...
</code>```

I want to deserialize it by LocalDateTime.parse(CharSequence text) factory method. All my attempts ended with com.fasterxml.jackson.databind.JsonMappingException:

Can not instantiate value of type [simple type, class java.time.LocalDateTime] from String value ('2016-05-11T17:32:20.897'); no single-String constructor/factory method

How do I achieve that? How can I specify factory method?

EDIT:

The problem has been solved by including  jackson-datatype-jsr310 module to the project and using @JsonDeserialize with LocalDateTimeDeserializer.

```<code>@JsonSerialize(using = ToStringSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime initiationDate;
</code>```

答:
For those who want to parse custom date-time format.

1) Add dependency

```<code>compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.8"
</code>```

2) Json annotation with date-time format

```<code>public class ClientRestObject {

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime timestamp;

}
</code>```

3) Register Java8 module in ObjectMapper

```<code>private static ObjectMapper buildObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    //To parse LocalDateTime
    objectMapper.registerModule(new JavaTimeModule());
    return objectMapper;
}
</code>```

Body:
I have the field initiationDate which serialises by ToStringSerializer class to ISO-8601 format.

@JsonSerialize(using = ToStringSerializer.class)
private LocalDateTime initiationDate;

When I receive the following JSON,

...
"initiationDate": "2016-05-11T17:32:20.897",
...

I want to deserialize it by LocalDateTime.parse(CharSequence text) factory method. All my attempts ended with com.fasterxml.jackson.databind.JsonMappingException:

Can not instantiate value of type [simple type, class java.time.LocalDateTime] from String value ('2016-05-11T17:32:20.897'); no single-String constructor/factory method

How do I achieve that? How can I specify factory method?

EDIT:

The problem has been solved by including  jackson-datatype-jsr310 module to the project and using @JsonDeserialize with LocalDateTimeDeserializer.

@JsonSerialize(using = ToStringSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime initiationDate;

Body:
For those who want to parse custom date-time format.

1) Add dependency

compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.8"

2) Json annotation with date-time format

public class ClientRestObject {

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime timestamp;

}

3) Register Java8 module in ObjectMapper

private static ObjectMapper buildObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    //To parse LocalDateTime
    objectMapper.registerModule(new JavaTimeModule());
    return objectMapper;
}


问:
How to submit semantic-ui-react Search value?
I'm trying to add submit functionality to my semantic-ui-react Search component but it's not behaving the way i want it to.

The submit should make a ajax call to an api and log out the data.

Does anyone know how to make it work? I'm either getting errors or my ajax request search query ends up empty even if i write something in the input field.

import React, {Component} from 'react'
import { Container, Header, Search } from 'semantic-ui-react'

import './jumbotron.css'

class Jumbotron extends Component {
constructor(props) {
    super(props)

    this.state = {value: ''}

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  }

  handleChange(event) {
    this.setState({value: event.target.value})
  }

  handleSubmit(event) {
    const food = this.state.value;
    const url = `https://api.edamam.com/search?q=${food}&app_id=${appId}&app_key=${apiKey}`

    fetch(url).then( response => response.json())
    .then( data => console.log(data))

    event.preventDefault();
  }

    render() {
        return (
            <Container text>

                    Nutrion

                <form onSubmit={this.handleSubmit}>
                <Search
                onChange={this.handleChange}
                type='text'
                value={this.state.value}
                size='big'
                placeholder=' ...'/>
                <input type="submit" value="Submit" />
                </form>
            </Container>
        )
    }
}

export default Jumbotron```

答:
The change required here is:-

Instead of

```<code><Search
    onChange={this.handleChange}
    type='text'
    value={this.state.value} // THIS CAUSING CONFICT WITH INTERNAL STATE?
    size='big'
    placeholder='What would you like to eat today? ...'/>
</code>```

Should be

```<code><Search
    onSearchChange={this.handleChange}
    type='text'
    value={this.state.value} // THIS CAUSING CONFICT WITH INTERNAL STATE?
    size='big'
    placeholder='What would you like to eat today? ...'/>
</code>```

Basically onChange should be replaced with onSearchChange

Body:
The change required here is:-

Instead of

<Search
    onChange={this.handleChange}
    type='text'
    value={this.state.value} // THIS CAUSING CONFICT WITH INTERNAL STATE?
    size='big'
    placeholder='What would you like to eat today? ...'/>

Should be

<Search
    onSearchChange={this.handleChange}
    type='text'
    value={this.state.value} // THIS CAUSING CONFICT WITH INTERNAL STATE?
    size='big'
    placeholder='What would you like to eat today? ...'/>

Basically onChange should be replaced with onSearchChange


问:
3DES/DES encryption using the JCE - generating an acceptable key
I'm working on a project that requires 3DES encryption in Java. The issue is that I've been (and will continue to be) supplied with a 128-bit hex key like "0123456789ABCDEF0123456789ABCDEF". Conversion to bytes is no issue. What is the issue, however, is that the Java Cryptographic Extensions API will choke on this key, saying it is invalid. I gather that the MSB of each byte is merely a parity bit, so the JCE expects me to remove those (or so I think). In .NET, however, I can specify the key as supplied, and it quietly handles the encryption/decryption with no complaints.

Is there any way I can generate the kind of key the JCE expects from the kind of key I'm supplied?

I've found that the JCE allows you specify an 8-byte key for DES encryption, so I tried implementing 3DES as DES EDE using half of the supplied key. However, I'm still getting inconsistent results with .NET.

Here's the Java code:

```<code>import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Main{
    public static void main(String[] args) throws Exception {
        byte [] plain = "I eat fish every day".getBytes("utf-8");

        byte [] keyBytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
            };

        byte [] key2Bytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0  }; // actual keys replaced with dummies.

        SecretKey keySpec = new SecretKeySpec(keyBytes, "DES");
        SecretKey keySpec2 = new SecretKeySpec(key2Bytes, "DES");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e_cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");

        e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        cipher.init(Cipher.DECRYPT_MODE, keySpec2, iv);

        byte [] cipherText = e_cipher.doFinal(plain);
        cipherText = cipher.doFinal(cipherText);
        cipherText = e_cipher.doFinal(cipherText);

        System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
    }
}
</code>```

and here's the .NET code:

```<code>using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace EncryptionDemo
{
    class Program
    {
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        // TODO: Implement Functionality Here
        var plainBytes = Encoding.UTF8.GetBytes("I eat fish every day");
        var keyBytes = new byte [] { 0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00,  0x00, 0x00, 0x00  };

        var tripleDES = TripleDESCryptoServiceProvider.Create();
        var transform = tripleDES.CreateEncryptor(keyBytes, new byte [8]);

        var memStream = new MemoryStream();
        var cStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);

        cStream.Write(plainBytes, 0, plainBytes.Length);
        cStream.FlushFinalBlock();

        //memStream.Position = 0;
        var cipherBytes = memStream.ToArray();

        Console.WriteLine("Ciphertext: " + Convert.ToBase64String(cipherBytes));

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}
</code>```

Both produce different outputs (some characters in the Base64 string are the same)

答:
the Sun provider doesn't accept 16-byte 3DES keys, but the BouncyCastle provider does. I just tried it out and it works like a charm - it produces the same output as the .NET code!</p>

```<code>import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Main{
    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        byte [] plain = "I eat fish every day".getBytes("utf-8");

        byte [] keyBytes = new byte [] { (byte) 0xC1, (byte) 0x57, (byte) 0x45, (byte) 0x08,
            (byte) 0x85, (byte) 0x02, (byte) 0xB0, (byte) 0xD3,
            (byte) 0xA2, (byte) 0xEF, (byte) 0x68, (byte) 0x43,
            (byte) 0x5E, (byte) 0xE6, (byte) 0xD0, (byte) 0x75 };

        SecretKey keySpec = new SecretKeySpec(keyBytes, "DESede");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e_cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "BC");

        e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

        byte [] cipherText = e_cipher.doFinal(plain);

        System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
    }
}
</code>```

Body:
I'm working on a project that requires 3DES encryption in Java. The issue is that I've been (and will continue to be) supplied with a 128-bit hex key like "0123456789ABCDEF0123456789ABCDEF". Conversion to bytes is no issue. What is the issue, however, is that the Java Cryptographic Extensions API will choke on this key, saying it is invalid. I gather that the MSB of each byte is merely a parity bit, so the JCE expects me to remove those (or so I think). In .NET, however, I can specify the key as supplied, and it quietly handles the encryption/decryption with no complaints.

Is there any way I can generate the kind of key the JCE expects from the kind of key I'm supplied?

I've found that the JCE allows you specify an 8-byte key for DES encryption, so I tried implementing 3DES as DES EDE using half of the supplied key. However, I'm still getting inconsistent results with .NET.

Here's the Java code:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Main{
    public static void main(String[] args) throws Exception {
        byte [] plain = "I eat fish every day".getBytes("utf-8");

        byte [] keyBytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
            };

        byte [] key2Bytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0  }; // actual keys replaced with dummies.

        SecretKey keySpec = new SecretKeySpec(keyBytes, "DES");
        SecretKey keySpec2 = new SecretKeySpec(key2Bytes, "DES");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e_cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");

        e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        cipher.init(Cipher.DECRYPT_MODE, keySpec2, iv);

        byte [] cipherText = e_cipher.doFinal(plain);
        cipherText = cipher.doFinal(cipherText);
        cipherText = e_cipher.doFinal(cipherText);

        System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
    }
}

and here's the .NET code:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace EncryptionDemo
{
    class Program
    {
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        // TODO: Implement Functionality Here
        var plainBytes = Encoding.UTF8.GetBytes("I eat fish every day");
        var keyBytes = new byte [] { 0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00,  0x00, 0x00, 0x00  };

        var tripleDES = TripleDESCryptoServiceProvider.Create();
        var transform = tripleDES.CreateEncryptor(keyBytes, new byte [8]);

        var memStream = new MemoryStream();
        var cStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);

        cStream.Write(plainBytes, 0, plainBytes.Length);
        cStream.FlushFinalBlock();

        //memStream.Position = 0;
        var cipherBytes = memStream.ToArray();

        Console.WriteLine("Ciphertext: " + Convert.ToBase64String(cipherBytes));

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

Both produce different outputs (some characters in the Base64 string are the same)

Body:
the Sun provider doesn't accept 16-byte 3DES keys, but the BouncyCastle provider does. I just tried it out and it works like a charm - it produces the same output as the .NET code!

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Main{
    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        byte [] plain = "I eat fish every day".getBytes("utf-8");

        byte [] keyBytes = new byte [] { (byte) 0xC1, (byte) 0x57, (byte) 0x45, (byte) 0x08,
            (byte) 0x85, (byte) 0x02, (byte) 0xB0, (byte) 0xD3,
            (byte) 0xA2, (byte) 0xEF, (byte) 0x68, (byte) 0x43,
            (byte) 0x5E, (byte) 0xE6, (byte) 0xD0, (byte) 0x75 };

        SecretKey keySpec = new SecretKeySpec(keyBytes, "DESede");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e_cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "BC");

        e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

        byte [] cipherText = e_cipher.doFinal(plain);

        System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
    }
}


问:
Clicking on link within Google search results using Selenium webdriver
I am trying to use selenium web driver to open up Google search for Youtube and then click on the Youtube link.  (I know I could go straight there but this is a proof of concept)  I have played around with different solutions, but I keep having problems locating the Youtube link for me to click on.

Here is what I have:

```<code>driver = webdriver.Chrome()
driver.get("https://google.com")
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("youtube")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
link = driver.find_element_by_link_text('YouTube')
link.click()
</code>```

I can't get the HTML to recognize so just inspect it on google to see the HTML for Youtube.

Also answers in python would be appreciated.

答:
To open up Google search for Youtube and then click on the Youtube link, here is your own working code with some simple tweaks:

```<code>from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

driver=webdriver.Chrome("C:\\Utility\\BrowserDrivers\\chromedriver.exe")
driver.maximize_window()
driver.implicitly_wait(20)
driver.get("https://google.com")
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("youtube")
elem.send_keys(Keys.RETURN)
time.sleep(3)
assert "No results found." not in driver.page_source
driver.find_element_by_xpath('.//*[@id="rso"]/div[1]/div/div/div/div/h3/a').click()
</code>```

Body:
I am trying to use selenium web driver to open up Google search for Youtube and then click on the Youtube link.  (I know I could go straight there but this is a proof of concept)  I have played around with different solutions, but I keep having problems locating the Youtube link for me to click on.

Here is what I have:

driver = webdriver.Chrome()
driver.get("https://google.com")
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("youtube")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
link = driver.find_element_by_link_text('YouTube')
link.click()

I can't get the HTML to recognize so just inspect it on google to see the HTML for Youtube.

Also answers in python would be appreciated.

Body:
To open up Google search for Youtube and then click on the Youtube link, here is your own working code with some simple tweaks:

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

driver=webdriver.Chrome("C:\\Utility\\BrowserDrivers\\chromedriver.exe")
driver.maximize_window()
driver.implicitly_wait(20)
driver.get("https://google.com")
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("youtube")
elem.send_keys(Keys.RETURN)
time.sleep(3)
assert "No results found." not in driver.page_source
driver.find_element_by_xpath('.//*[@id="rso"]/div[1]/div/div/div/div/h3/a').click()


问:
Import Apple Development Teams into Xamarin Studio on Mac without fastlane?
Is it possible to import Apple Development Teams into Xamarin Studio on Mac without installing fastlane?

I'm comfortable with letting Xcode manage my Apple ID, passwords, certificates, provisioning profiles. I would like to avoid bringing in a third-party tool like fastlane into this process (seems to me quite insecure to enter my AppleID & password in any tools outside Apple's ecosystem)

UPDATE:

Adding a screenshot to explain where are the Development Teams missing in Xamarin Studio.

答:
So I have never actually tried use Xamarin Studio to do all of that stuff for me, I did not even know it was able to do all of that. I guess I did it the manual way which might work better for you.

If you are trying to enable push notifications I would highly suggest following Xamarin's Guide which walks you through manually creating an APNS certificate (which I think it what Xamarin Studio is trying to do for you by using fastlane).

As far as the Entitlements.plist file, my app uses remote Push Notifications and does not specify anything special in its Entitlements.plist file, so that part may not even be necessary for you unless there is a specific reason to do it.

My app adds the following to it's Info.plist file though:

```<code><key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
</code>```

That along with enabling Push Notifications in the app's App Id on the Apple Developer site, associating the App Id with an APNS certificate, and then regenerating your Provisioning Profiles should be more or less all you need to do (other than adding actual code).

Body:
So I have never actually tried use Xamarin Studio to do all of that stuff for me, I did not even know it was able to do all of that. I guess I did it the manual way which might work better for you.

If you are trying to enable push notifications I would highly suggest following Xamarin's Guide which walks you through manually creating an APNS certificate (which I think it what Xamarin Studio is trying to do for you by using fastlane).

As far as the Entitlements.plist file, my app uses remote Push Notifications and does not specify anything special in its Entitlements.plist file, so that part may not even be necessary for you unless there is a specific reason to do it.

My app adds the following to it's Info.plist file though:

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

That along with enabling Push Notifications in the app's App Id on the Apple Developer site, associating the App Id with an APNS certificate, and then regenerating your Provisioning Profiles should be more or less all you need to do (other than adding actual code).


问:
how to send json data to server and get Json response in android?
how to send json data to server and get json response in android using HttpURLConnection (get, post, put, delete)?
the url like = http://maxxapi.webname.com/oauth/token_access</p>

答: in order to send http requests,i suggest you to try OkHttpClient or Retrofit </p>


问:
Base R library not loading in VS
Situation: I have installed R 3.3 and set up R for Visual Studio extension.

Code snippet:

```<code> log.ir <- log(iris[, 1:4])
 ir.species <- iris[, 5]
 ir.pca <- stats:::prcomp(log.ir, center = TRUE, scale = TRUE)
</code>```

This works in R interactive window in Visual Studio, it also work in RGui but when I run it using C# the code fails on 3rd line:

```<code>engine.Evaluate("log.ir <- log(iris[, 1:4])");
engine.Evaluate("ir.species <- iris[, 5]");
engine.Evaluate("ir.pca <- stats:::prcomp(log.ir, center = TRUE, scale = TRUE)");
</code>```

Exception:

Error in inDL(x, as.logical(local), as.logical(now), ...) :
  unable to load shared object 'C:/Program Files/R/R-3.3.3/library/stats/libs/x64/stats.dll':
  LoadLibrary failure:  The specified module could not be found.

I have tried reinstalling all R components but it hasn't helped. And obviously I have checked and the stats.dll file exists in the path specified in the error.

RTVS version:

Any help is much appreciated,
Thanks

答:
I encountered this recently and the solution to this seems to be relatively straightforward. All you need to do is add the path to the R.dll from the relevant architecture (i386/x64)to the System Path statement. So, on my system I added "C:\Program Files\R\R-3.4.0\bin\i386" to the System Path Environment Variable. I also forced the architecture to x86, but that could just be overkill.

This information was gleaned from ASP.NET with R.NET

Title: Base R library not loading in VS

Body:
Situation: I have installed R 3.3 and set up R for Visual Studio extension.

Code snippet:

 log.ir <- log(iris[, 1:4])
 ir.species <- iris[, 5]
 ir.pca <- stats:::prcomp(log.ir, center = TRUE, scale = TRUE)

This works in R interactive window in Visual Studio, it also work in RGui but when I run it using C# the code fails on 3rd line:

engine.Evaluate("log.ir <- log(iris[, 1:4])");
engine.Evaluate("ir.species <- iris[, 5]");
engine.Evaluate("ir.pca <- stats:::prcomp(log.ir, center = TRUE, scale = TRUE)");

Exception:

Error in inDL(x, as.logical(local), as.logical(now), ...) :
  unable to load shared object 'C:/Program Files/R/R-3.3.3/library/stats/libs/x64/stats.dll':
  LoadLibrary failure:  The specified module could not be found.

I have tried reinstalling all R components but it hasn't helped. And obviously I have checked and the stats.dll file exists in the path specified in the error.

RTVS version:

Any help is much appreciated,
Thanks


问:
How to use Camel Apache Timer Component
So currently, the only thing that we can work out is to simply transfer one file to another folder.
Like so:

```<code>from("file://C:/Users/Me/Desktop/FolderA?noop=true")
    .to("file://C:/Users/Me/Desktop/FolderB");
</code>```

However, when I try to add the complexity of the timer component, it just does not make sense to me. I keep getting "Cannot write null body to file" exception.

The code I try to write for the timer Component is like so:

```<code>from("timer://file://C:/Users/Me/Desktop/FolderA?period=30000")
    .to("file://C:/Users/Me/Desktop/FolderB");
</code>```

答:
Use timer with pollEnrich</p>

```<code>from("timer://foo?period=30000")
   .pollEnrich("file://C:/Users/Me/Desktop/FolderA?noop=true")
   .to("file://C:/Users/Me/Desktop/FolderB");
</code>```

Title: How to use Camel Apache Timer Component

Body:
So currently, the only thing that we can work out is to simply transfer one file to another folder.
Like so:

from("file://C:/Users/Me/Desktop/FolderA?noop=true")
    .to("file://C:/Users/Me/Desktop/FolderB");

However, when I try to add the complexity of the timer component, it just does not make sense to me. I keep getting "Cannot write null body to file" exception.

The code I try to write for the timer Component is like so:

from("timer://file://C:/Users/Me/Desktop/FolderA?period=30000")
    .to("file://C:/Users/Me/Desktop/FolderB");

Body:
Use timer with pollEnrich

from("timer://foo?period=30000")
   .pollEnrich("file://C:/Users/Me/Desktop/FolderA?noop=true")
   .to("file://C:/Users/Me/Desktop/FolderB");


问:
IBM.Data.DB2.iSeries SQL0180 error
I'm attempting to connect to IBM.Data.DB2.iSeries database via a .NET application and am receiving the following error when executing a DB2 stored procedure: "SQL0180 Syntax of date, time, or timestamp value not valid."

However, when i run the same stored procedure in the IBM Data Studio i get no error and it successfully returns a from the execution of the stored procedure. This leads me to believe it may be a driver issue and i'll need to update it.  Has anyone ran into this issue before and was it a driver update that fixed it?

答: The default path for the tool will include your username in it.  It then takes that username and looks for data inside a library of the same name.  If there are no libraries with the name being the username then it will fail. Two solutions: modify the default path to not include the username, or to add a library of the username.</p>

Title: IBM.Data.DB2.iSeries SQL0180 error


问:
Angular 2 Kendo Grid from array of string
I'm developing app with Angular 2 + Kendo UI.

So, I have array of paths to images and I want to show it in table form.
I want instead of 1 column in a table row show 5 columns in a table row.

Can I do that? If yes, then how would look kendo grid html template and data for it?

答:
So, the result is the following:

HTML template (table header is hidden):

```<code><kendo-grid [data]="gridData">
    <ng-template ngFor [ngForOf]="columns" let-column>
        <kendo-grid-column field="{{column}}" [headerClass]="'hidden'">
            <ng-template kendoGridCellTemplate let-dataItem>
                <img *ngIf="dataItem[column].avatarUri != null" [src]="dataItem[column].avatarUri" [alt]="dataItem[column].keywords" />
             </ng-template>
        </kendo-grid-column>
    </ng-template>
</kendo-grid>
</code>```

TypeScript component:

```<code>gridData: any[];
columns: string[] = ["column0", "column1", "column2", "column3", "column4"];

ngOnInit() {
    this.avatarService.getAvatars()
        .subscribe((avatars: Array<Avatar>) => {
            this.gridData = [];
            let i = 0;
            while (i < avatars.length) {
                let obj = {};
                for (let column of this.columns) {
                    obj[column] = {
                        avatarUri: i >= avatars.length ? null : avatars[i].avatarUri,
                        keywords: i >= avatars.length ? null : avatars[i].keywords
                    };
                    i++;
                }
                this.gridData.push(obj);
            }
        });
}
</code>```

Also helped that link with dynamic columns.

Body:
So, the result is the following:

HTML template (table header is hidden):

<kendo-grid [data]="gridData">
    <ng-template ngFor [ngForOf]="columns" let-column>
        <kendo-grid-column field="{{column}}" [headerClass]="'hidden'">
            <ng-template kendoGridCellTemplate let-dataItem>
                <img *ngIf="dataItem[column].avatarUri != null" [src]="dataItem[column].avatarUri" [alt]="dataItem[column].keywords" />
             </ng-template>
        </kendo-grid-column>
    </ng-template>
</kendo-grid>

TypeScript component:

gridData: any[];
columns: string[] = ["column0", "column1", "column2", "column3", "column4"];

ngOnInit() {
    this.avatarService.getAvatars()
        .subscribe((avatars: Array<Avatar>) => {
            this.gridData = [];
            let i = 0;
            while (i < avatars.length) {
                let obj = {};
                for (let column of this.columns) {
                    obj[column] = {
                        avatarUri: i >= avatars.length ? null : avatars[i].avatarUri,
                        keywords: i >= avatars.length ? null : avatars[i].keywords
                    };
                    i++;
                }
                this.gridData.push(obj);
            }
        });
}

Also helped that link with dynamic columns.


问:
How to swap keys and values in a Map elegantly
I already know how to do it the hard way and got it working - iterating over entries and swapping "manually". But i wonder if, like so many tasks,  this one can be solved in a more elegant way.

I have read this post, unfortunately it does not feature elegant solutions. I also have no possibility to use any fancy Guava BiMaps or anything outside the jdk (project stack is already defined).

I can assume that my map is bijective, btw :)

答:
If you don't have a choice to use a third party library, I don't consider the following code so ugly (though some scripting languages do have elegant ways of doing it):</p>

```<code>//map must be a bijection in order for this to work properly
public static <K,V> HashMap<V,K> reverse(Map<K,V> map) {
    HashMap<V,K> rev = new HashMap<V, K>();
    for(Map.Entry<K,V> entry : map.entrySet())
        rev.put(entry.getValue(), entry.getKey());
    return rev;
}
</code>```

Body:
If you don't have a choice to use a third party library, I don't consider the following code so ugly (though some scripting languages do have elegant ways of doing it):

//map must be a bijection in order for this to work properly
public static <K,V> HashMap<V,K> reverse(Map<K,V> map) {
    HashMap<V,K> rev = new HashMap<V, K>();
    for(Map.Entry<K,V> entry : map.entrySet())
        rev.put(entry.getValue(), entry.getKey());
    return rev;
}


问:
Count the number of sheets in a separate workbook and return to a cell in original workbook
I have written a query that opens a separate file, counts all the unique 13 digit values, and copies all of the data related to that no. into separate sheets in a new workbook. What I now need to do is, from the original workbook where the macro lives, count all of the the sheets in the new workbook and return the count to a cell in the original workbook. For some reason, this baffling me so any assistance would be greatly appreciated. </p>

```<code>Option Explicit

Sub MPANSeparation()

Dim X As Integer               'Holds Count of rows
Dim Y As Integer            'Holds the count of copied cells
Dim MyLimit As Long         'Holds the count of matches
Dim MyTemp As String          'Holds the MPAN #
Dim MyNewBook As String     'Holds the name of the new workbook
Dim FullFileName As String  'Holds the full file name
Dim FileLocation As String  'Holds the file location
Dim FileName As String      'Holds the file name
Dim MPANSeparate As Excel.Workbook
Dim NumberOfSheets As Double

'Turn Off Screen Updates
Application.ScreenUpdating = False
'Turn off calculations
Application.Calculation = xlCalculationManual

'Identifies cell references for upload file
FullFileName = Sheet1.Cells(7, 2)
FileLocation = Sheet1.Cells(8, 2)
FileName = Sheet1.Cells(9, 2)

'Identifies workbook where data is being extracted from.
 Application.EnableEvents = False
Application.DisplayAlerts = False
Set MPANSeparate = Workbooks.Open(FullFileName, ReadOnly:=False)

'Ensure we're on the data sheet
Sheets("Sheet1").Select

'Get the count of the rows in the current region
X = Range("A1").CurrentRegion.Rows.Count

'Add a new "Scratch" Sheet after first sheet
Sheets.Add After:=Sheets(1)
'Rename newly added sheet
ActiveSheet.Name = "Scratch"

'Copy all of column A of the first sheet to scratch
Sheets(1).Range("A1:A" & X).Copy Sheets("Scratch").Range("A1")

'Copy all of column B of the first sheet to scratch
Sheets(1).Range("B1:B" & X).Copy
Sheets("Scratch").Range("A1048575").End(xlUp).Offset(1, 0)

'Copy all of column C of the first sheet to scratch
Sheets(1).Range("C1:C" & X).Copy
Sheets("Scratch").Range("A1048575").End(xlUp).Offset(1, 0)

'Remove all duplicates
ActiveSheet.Range("$A:$A").RemoveDuplicates Columns:=1, Header:= _
    xlYes

'Select start of range
Range("A1").Select

'Loop to test for len of 13 characters
Do While ActiveCell.Value <> ""
    'Logical test (is this cell 13 characters long)
    If Len(ActiveCell.Value) <> 13 Then
        'Delete the whole row
        ActiveCell.EntireRow.Delete
    Else
        'Move down a cell
        ActiveCell.Offset(1, 0).Select
    End If
Loop

'Add CountIf formulas to column B (checking A,B & C)
Range("B1:B" & Range("A1048575").End(xlUp).Row) _
    .Formula = "=COUNTIF(Sheet1!C[-1]:C[1],Scratch!RC[-1])"

'Add a new workbook
Workbooks.Add
'Get the name of the new workbook
MyNewBook = ActiveWorkbook.Name

'Go back to this workbook
MPANSeparate.Activate

'Select start of range
Range("A1").Select

'Loop to add sheets (one for each MPAN)
Do While ActiveCell.Value <> ""
    'Get MPAN #
    MyTemp = ActiveCell.Value
    'Add new sheet to "MyNewBook"
    Workbooks(MyNewBook).Sheets.Add _

After:=Workbooks(MyNewBook).Sheets(Workbooks(MyNewBook).Sheets.Count)
    'Rename newly added sheet to MPAN #
    Workbooks(MyNewBook).Sheets(Workbooks(MyNewBook).Sheets.Count).Name =
MyTemp
    'Move down a cell
    ActiveCell.Offset(1, 0).Select
Loop

'Select start of range
Range("A1").Select

'The outer copy and paste loop
Do While ActiveCell.Value <> ""

    'Select start of range
    Range("A1").Select

    'Get the first value we're looking for
    MyTemp = ActiveCell.Value
    'Get the actual count of matches
    MyLimit = ActiveCell.Offset(0, 1).Value

    'Go to the data sheet
    Sheets("Sheet1").Select

    'The A loop
    'Select start of range
    Range("A1").Select

        Do While ActiveCell.Value <> ""
            If ActiveCell.Value <> MyTemp Then
                'Move down a cell
                ActiveCell.Offset(1, 0).Select
            Else
                'Copy the entire row to the appropriate sheet in the new
Workbook
                ActiveCell.EntireRow.Copy _

Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)

                'Move down a cell
                ActiveCell.Offset(1, 0).Select

                'Increase Y by 1
                Y = Y + 1

                'If we have all the matches, add headings and go to
NextOuterLoop
                If Y = MyLimit Then
                    Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
                    GoTo NextOuterLoop
                End If
            End If
        Loop

    'The B loop
    'Select start of range
    Range("B1").Select

        Do While ActiveCell.Value <> ""
            If ActiveCell.Value <> MyTemp Then
                'Move down a cell
                ActiveCell.Offset(1, 0).Select
            Else
                'Copy the entire row to the appropriate sheet in the new
Workbook
                ActiveCell.EntireRow.Copy _

Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)

                'Move down a cell
                ActiveCell.Offset(1, 0).Select

                'Increase Y by 1
                Y = Y + 1

                'If we have all the matches, add headings and go to
NextOuterLoop
                If Y = MyLimit Then
                    Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
                    GoTo NextOuterLoop
                End If
            End If
        Loop

    'The C loop
    'Select start of range
    Range("C1").Select

        Do While ActiveCell.Value <> ""
            If ActiveCell.Value <> MyTemp Then
                'Move down a cell
                ActiveCell.Offset(1, 0).Select
            Else
                'Copy the entire row to the appropriate sheet in the new
Workbook
                ActiveCell.EntireRow.Copy _

Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)

                'Move down a cell
                ActiveCell.Offset(1, 0).Select

                'Increase Y by 1
                Y = Y + 1

                'If we have all the matches, add headings and go to
NextOuterLoop
                If Y = MyLimit Then
                    Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
                    GoTo NextOuterLoop
                End If
            End If
        Loop

NextOuterLoop:

    'Reset Y
    Y = 0
    'Go to the scratch sheet
    Sheets("Scratch").Select
    'Delete the entire row
    Range("A1").EntireRow.Delete

Loop

'Turn off display alerts
Application.DisplayAlerts = False
'Delete the scratch sheet
Sheets("Scratch").Delete
'Turn on display alerts
Application.DisplayAlerts = True

Workbooks(MyNewBook).SaveAs ("C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1" & ".xlsx")

'Ensure we're back on the data sheet
Sheets("Sheet1").Select
'Select start of range
Range("A1").Select

Call forEachWs
'Turn On Calculations
Application.Calculation = xlCalculationAutomatic
'Turn on screen updates
Application.ScreenUpdating = True

End Sub

Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next
End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
End With

NumberOfSheets = Workbooks(FileName).Worksheets.Count

End Sub
</code>```

答:
The following script opens a workbook and returns the count of sheets in Range A1 in the first sheet of the workbook the macro resides in:</p>

```<code>Sub Test()
Dim fullPath As String
Dim wb As Workbook

fullPath = "Somepath\someworkbook.xlsx"

Set wb = Workbooks.Open(fullPath)

ThisWorkbook.Worksheets(1).Range("A1").Value = wb.Worksheets.Count

wb.Close

Set wb = Nothing
End Sub
</code>```

Body:
I have written a query that opens a separate file, counts all the unique 13 digit values, and copies all of the data related to that no. into separate sheets in a new workbook. What I now need to do is, from the original workbook where the macro lives, count all of the the sheets in the new workbook and return the count to a cell in the original workbook. For some reason, this baffling me so any assistance would be greatly appreciated.

Option Explicit

Sub MPANSeparation()

Dim X As Integer               'Holds Count of rows
Dim Y As Integer            'Holds the count of copied cells
Dim MyLimit As Long         'Holds the count of matches
Dim MyTemp As String          'Holds the MPAN #
Dim MyNewBook As String     'Holds the name of the new workbook
Dim FullFileName As String  'Holds the full file name
Dim FileLocation As String  'Holds the file location
Dim FileName As String      'Holds the file name
Dim MPANSeparate As Excel.Workbook
Dim NumberOfSheets As Double

'Turn Off Screen Updates
Application.ScreenUpdating = False
'Turn off calculations
Application.Calculation = xlCalculationManual

'Identifies cell references for upload file
FullFileName = Sheet1.Cells(7, 2)
FileLocation = Sheet1.Cells(8, 2)
FileName = Sheet1.Cells(9, 2)

'Identifies workbook where data is being extracted from.
 Application.EnableEvents = False
Application.DisplayAlerts = False
Set MPANSeparate = Workbooks.Open(FullFileName, ReadOnly:=False)

'Ensure we're on the data sheet
Sheets("Sheet1").Select

'Get the count of the rows in the current region
X = Range("A1").CurrentRegion.Rows.Count

'Add a new "Scratch" Sheet after first sheet
Sheets.Add After:=Sheets(1)
'Rename newly added sheet
ActiveSheet.Name = "Scratch"

'Copy all of column A of the first sheet to scratch
Sheets(1).Range("A1:A" & X).Copy Sheets("Scratch").Range("A1")

'Copy all of column B of the first sheet to scratch
Sheets(1).Range("B1:B" & X).Copy
Sheets("Scratch").Range("A1048575").End(xlUp).Offset(1, 0)

'Copy all of column C of the first sheet to scratch
Sheets(1).Range("C1:C" & X).Copy
Sheets("Scratch").Range("A1048575").End(xlUp).Offset(1, 0)

'Remove all duplicates
ActiveSheet.Range("$A:$A").RemoveDuplicates Columns:=1, Header:= _
    xlYes

'Select start of range
Range("A1").Select

'Loop to test for len of 13 characters
Do While ActiveCell.Value <> ""
    'Logical test (is this cell 13 characters long)
    If Len(ActiveCell.Value) <> 13 Then
        'Delete the whole row
        ActiveCell.EntireRow.Delete
    Else
        'Move down a cell
        ActiveCell.Offset(1, 0).Select
    End If
Loop

'Add CountIf formulas to column B (checking A,B & C)
Range("B1:B" & Range("A1048575").End(xlUp).Row) _
    .Formula = "=COUNTIF(Sheet1!C[-1]:C[1],Scratch!RC[-1])"

'Add a new workbook
Workbooks.Add
'Get the name of the new workbook
MyNewBook = ActiveWorkbook.Name

'Go back to this workbook
MPANSeparate.Activate

'Select start of range
Range("A1").Select

'Loop to add sheets (one for each MPAN)
Do While ActiveCell.Value <> ""
    'Get MPAN #
    MyTemp = ActiveCell.Value
    'Add new sheet to "MyNewBook"
    Workbooks(MyNewBook).Sheets.Add _

After:=Workbooks(MyNewBook).Sheets(Workbooks(MyNewBook).Sheets.Count)
    'Rename newly added sheet to MPAN #
    Workbooks(MyNewBook).Sheets(Workbooks(MyNewBook).Sheets.Count).Name =
MyTemp
    'Move down a cell
    ActiveCell.Offset(1, 0).Select
Loop

'Select start of range
Range("A1").Select

'The outer copy and paste loop
Do While ActiveCell.Value <> ""

    'Select start of range
    Range("A1").Select

    'Get the first value we're looking for
    MyTemp = ActiveCell.Value
    'Get the actual count of matches
    MyLimit = ActiveCell.Offset(0, 1).Value

    'Go to the data sheet
    Sheets("Sheet1").Select

    'The A loop
    'Select start of range
    Range("A1").Select

        Do While ActiveCell.Value <> ""
            If ActiveCell.Value <> MyTemp Then
                'Move down a cell
                ActiveCell.Offset(1, 0).Select
            Else
                'Copy the entire row to the appropriate sheet in the new
Workbook
                ActiveCell.EntireRow.Copy _

Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)

                'Move down a cell
                ActiveCell.Offset(1, 0).Select

                'Increase Y by 1
                Y = Y + 1

                'If we have all the matches, add headings and go to
NextOuterLoop
                If Y = MyLimit Then
                    Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
                    GoTo NextOuterLoop
                End If
            End If
        Loop

    'The B loop
    'Select start of range
    Range("B1").Select

        Do While ActiveCell.Value <> ""
            If ActiveCell.Value <> MyTemp Then
                'Move down a cell
                ActiveCell.Offset(1, 0).Select
            Else
                'Copy the entire row to the appropriate sheet in the new
Workbook
                ActiveCell.EntireRow.Copy _

Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)

                'Move down a cell
                ActiveCell.Offset(1, 0).Select

                'Increase Y by 1
                Y = Y + 1

                'If we have all the matches, add headings and go to
NextOuterLoop
                If Y = MyLimit Then
                    Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
                    GoTo NextOuterLoop
                End If
            End If
        Loop

    'The C loop
    'Select start of range
    Range("C1").Select

        Do While ActiveCell.Value <> ""
            If ActiveCell.Value <> MyTemp Then
                'Move down a cell
                ActiveCell.Offset(1, 0).Select
            Else
                'Copy the entire row to the appropriate sheet in the new
Workbook
                ActiveCell.EntireRow.Copy _

Workbooks(MyNewBook).Sheets(MyTemp).Range("A1048575").End(xlUp).Offset(1, 0)

                'Move down a cell
                ActiveCell.Offset(1, 0).Select

                'Increase Y by 1
                Y = Y + 1

                'If we have all the matches, add headings and go to
NextOuterLoop
                If Y = MyLimit Then
                    Range("A1").EntireRow.Copy
Workbooks(MyNewBook).Sheets(MyTemp).Range("A1")
                    GoTo NextOuterLoop
                End If
            End If
        Loop

NextOuterLoop:

    'Reset Y
    Y = 0
    'Go to the scratch sheet
    Sheets("Scratch").Select
    'Delete the entire row
    Range("A1").EntireRow.Delete

Loop

'Turn off display alerts
Application.DisplayAlerts = False
'Delete the scratch sheet
Sheets("Scratch").Delete
'Turn on display alerts
Application.DisplayAlerts = True

Workbooks(MyNewBook).SaveAs ("C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1" & ".xlsx")

'Ensure we're back on the data sheet
Sheets("Sheet1").Select
'Select start of range
Range("A1").Select

Call forEachWs
'Turn On Calculations
Application.Calculation = xlCalculationAutomatic
'Turn on screen updates
Application.ScreenUpdating = True

End Sub

Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next
End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
End With

NumberOfSheets = Workbooks(FileName).Worksheets.Count

End Sub

Body:
The following script opens a workbook and returns the count of sheets in Range A1 in the first sheet of the workbook the macro resides in:

Sub Test()
Dim fullPath As String
Dim wb As Workbook

fullPath = "Somepath\someworkbook.xlsx"

Set wb = Workbooks.Open(fullPath)

ThisWorkbook.Worksheets(1).Range("A1").Value = wb.Worksheets.Count

wb.Close

Set wb = Nothing
End Sub