问:
VB.Net crystal report connection string
I am using vb.net 2010 to develop my software. Also have crystal reports in my projects and things are working perfectly in my PC.

My problem is that I design the crystal report in my PC with wizard and my PC is not the server, then upload it to the server so it would be accessible to users. But when try to open report a connection problem to the database pops up. I know that is due to the connection property when I designed the reports in my PC.

How can I solve this problem.

答:
I know this post is a few years old, but after struggling with these same problems, I thought I would add a variation of Mahesh ML's routine for MS SQL 2016 server.

A three things to note:

SqlClient.SqlConnectionStringBuilder is used instead of DbConnectionStringBuilder

zSecurity (added) for Window's authentication instead of database user

reportDocument.DataSourceConnections(0).IntegratedSecurity = True is needed when Windows authentication is used

```<code>Public Sub SetReportSQL(ByVal ConnectionString As String,
                   ByRef CrystalReportViewer As CrystalDecisions.Windows.Forms.CrystalReportViewer,
                   ByRef reportDocument As ReportClass)
    'Get SQL Server Details
    Dim builder As New SqlClient.SqlConnectionStringBuilder

    builder.ConnectionString = ConnectionString

    Dim zServer As String = TryCast(builder("Data Source"), String)
    Dim zDatabase As String = TryCast(builder("Initial Catalog"), String)
    Dim zSecurity As Boolean = Boolean.TryParse(builder("Integrated Security"), zSecurity)
    Dim zUsername As String = TryCast(builder("User ID"), String)
    Dim zPassword As String = TryCast(builder("Password"), String)

    Dim ciReportConnection As New ConnectionInfo

    ciReportConnection.ServerName = zServer
    ciReportConnection.DatabaseName = zDatabase
    ciReportConnection.IntegratedSecurity = zSecurity
    If zSecurity = False Then
        ciReportConnection.UserID = zUsername
        ciReportConnection.Password = zPassword
    Else
        reportDocument.DataSourceConnections(0).IntegratedSecurity = True
    End If

    'Assign data source details to tables
    For Each table As Table In reportDocument.Database.Tables
        table.LogOnInfo.ConnectionInfo = ciReportConnection
        table.ApplyLogOnInfo(table.LogOnInfo)
    Next

    For Each subrep As ReportDocument In reportDocument.Subreports
        For Each table As Table In subrep.Database.Tables
            table.LogOnInfo.ConnectionInfo = ciReportConnection
            table.ApplyLogOnInfo(table.LogOnInfo)
        Next
    Next

    'Assign data source details to the report viewer
    If CrystalReportViewer.LogOnInfo IsNot Nothing Then
        Dim tlInfo As TableLogOnInfos = CrystalReportViewer.LogOnInfo
        For Each tbloginfo As TableLogOnInfo In tlInfo
            tbloginfo.ConnectionInfo = ciReportConnection
        Next
    End If
    reportDocument.VerifyDatabase()
    reportDocument.Refresh()
    CrystalReportViewer.ReportSource = reportDocument
    CrystalReportViewer.Refresh()
End Sub
</code>```

Title: VB.Net crystal report connection string

Body:
I know this post is a few years old, but after struggling with these same problems, I thought I would add a variation of Mahesh ML's routine for MS SQL 2016 server.

A three things to note:

SqlClient.SqlConnectionStringBuilder is used instead of DbConnectionStringBuilder

zSecurity (added) for Window's authentication instead of database user

reportDocument.DataSourceConnections(0).IntegratedSecurity = True is needed when Windows authentication is used

Public Sub SetReportSQL(ByVal ConnectionString As String,
                   ByRef CrystalReportViewer As CrystalDecisions.Windows.Forms.CrystalReportViewer,
                   ByRef reportDocument As ReportClass)
    'Get SQL Server Details
    Dim builder As New SqlClient.SqlConnectionStringBuilder

    builder.ConnectionString = ConnectionString

    Dim zServer As String = TryCast(builder("Data Source"), String)
    Dim zDatabase As String = TryCast(builder("Initial Catalog"), String)
    Dim zSecurity As Boolean = Boolean.TryParse(builder("Integrated Security"), zSecurity)
    Dim zUsername As String = TryCast(builder("User ID"), String)
    Dim zPassword As String = TryCast(builder("Password"), String)

    Dim ciReportConnection As New ConnectionInfo

    ciReportConnection.ServerName = zServer
    ciReportConnection.DatabaseName = zDatabase
    ciReportConnection.IntegratedSecurity = zSecurity
    If zSecurity = False Then
        ciReportConnection.UserID = zUsername
        ciReportConnection.Password = zPassword
    Else
        reportDocument.DataSourceConnections(0).IntegratedSecurity = True
    End If

    'Assign data source details to tables
    For Each table As Table In reportDocument.Database.Tables
        table.LogOnInfo.ConnectionInfo = ciReportConnection
        table.ApplyLogOnInfo(table.LogOnInfo)
    Next

    For Each subrep As ReportDocument In reportDocument.Subreports
        For Each table As Table In subrep.Database.Tables
            table.LogOnInfo.ConnectionInfo = ciReportConnection
            table.ApplyLogOnInfo(table.LogOnInfo)
        Next
    Next

    'Assign data source details to the report viewer
    If CrystalReportViewer.LogOnInfo IsNot Nothing Then
        Dim tlInfo As TableLogOnInfos = CrystalReportViewer.LogOnInfo
        For Each tbloginfo As TableLogOnInfo In tlInfo
            tbloginfo.ConnectionInfo = ciReportConnection
        Next
    End If
    reportDocument.VerifyDatabase()
    reportDocument.Refresh()
    CrystalReportViewer.ReportSource = reportDocument
    CrystalReportViewer.Refresh()
End Sub


来源: stackexchange

问:
I can't install JDK7 on Ubuntu 16.04 Download Failed
I'm trying to install jdk7 on a my Ubuntu 16.04 machine, here are the commands that I executed:

```<code>sudo apt-get update
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
</code>```

The last one returned Download Failed error and was not able to install the package.

Error Screenshot

When I did some digging I found that Oracle no longer provide JDK7 download link on their official site.

If someone has figured out a way to install it please help !

答:
Ok, since the binaries are not longer available you will have to download
it manually

1) download jdk-7u80-linux-i586.tar.gz or jdk-7u80-linux-x64.tar.gz based on the architecture of your operative system from here (you will have to create an oracle account if you dont have one)

2) Move the file that you just downloaded to this directory
 /var/cache/oracle-jdk7-installer/

3) Finally run the below commands

```<code>sudo echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee /etc/apt/sources.list.d/webupd8team-java.list
sudo echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
sudo apt-get update
sudo echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections
sudo apt-get -y install oracle-java7-installer
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to install jdk7 on a my Ubuntu 16.04 machine, here are the commands that I executed:

sudo apt-get update
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

The last one returned Download Failed error and was not able to install the package.

Error Screenshot

When I did some digging I found that Oracle no longer provide JDK7 download link on their official site.

If someone has figured out a way to install it please help !

Body:
Ok, since the binaries are not longer available you will have to download
it manually

1) download jdk-7u80-linux-i586.tar.gz or jdk-7u80-linux-x64.tar.gz based on the architecture of your operative system from here (you will have to create an oracle account if you dont have one)

2) Move the file that you just downloaded to this directory
 /var/cache/oracle-jdk7-installer/

3) Finally run the below commands

sudo echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee /etc/apt/sources.list.d/webupd8team-java.list
sudo echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
sudo apt-get update
sudo echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections
sudo apt-get -y install oracle-java7-installer


问:
Strange Feature? of Ruby Arrays
I came around this strange feature(?) of arrays in Ruby and it would be very helpful if someone could explain to me why they work the way they do.

First lets give an example of how things usually work.

```<code>a = "Hello" #=> "Hello"
b = a #=> "Hello"
b += " Goodbye" #=> "Hello Goodbye"
b #=> "Hello Goodbye"
a #=> "Hello"
</code>```

Ok cool, when you use = it creats a copy of the object (this time a string).

But when you use arrays this happens:

```<code>a = [1,2,3] #=> [1,2,3]
b = a #=> [1,2,3]
b[1] = 5 #=> [1,5,3]
b #=> [1,5,3]
a #=> [1,5,3]
</code>```

Now thats just strange.  Its the only object I've found that doesn't get copied when using = but instead just creates a refrance to the original object.

Can someone also explain (there must be a method) for copying an array without having it point back to the original object?

答:
What happends there is that ruby is treating the Array object by reference and not by value.

So you can see it as this:

```<code> b= [1,2,3]
 a= b

              --'b' Points to---> [1,2,3] <--'a' points t---
</code>```

So as you can see both point to the same reference, that means that if you change anything in a it will be reflected on b.

As for your question on the copying the object you could use the Object#clone method to do so.

ContentLicense: CC BY-SA 2.5

Title: Strange Feature? of Ruby Arrays

Body:
I came around this strange feature(?) of arrays in Ruby and it would be very helpful if someone could explain to me why they work the way they do.

First lets give an example of how things usually work.

a = "Hello" #=> "Hello"
b = a #=> "Hello"
b += " Goodbye" #=> "Hello Goodbye"
b #=> "Hello Goodbye"
a #=> "Hello"

Ok cool, when you use = it creats a copy of the object (this time a string).

But when you use arrays this happens:

a = [1,2,3] #=> [1,2,3]
b = a #=> [1,2,3]
b[1] = 5 #=> [1,5,3]
b #=> [1,5,3]
a #=> [1,5,3]

Now thats just strange.  Its the only object I've found that doesn't get copied when using = but instead just creates a refrance to the original object.

Can someone also explain (there must be a method) for copying an array without having it point back to the original object?

Body:
What happends there is that ruby is treating the Array object by reference and not by value.

So you can see it as this:

 b= [1,2,3]
 a= b

              --'b' Points to---> [1,2,3] <--'a' points t---

So as you can see both point to the same reference, that means that if you change anything in a it will be reflected on b.

As for your question on the copying the object you could use the Object#clone method to do so.


问:
Why does this write outfile not work on different SPSS versions?
I have a data set consisting of variables id, condition, response. I have the following syntax to generate an Excel file, say, for data cleaning:

```<code>compute tab=9.
formats tab (pib).
write outfile='Directory\outfile.xls' / " if id = " tab id tab " and condition = " tab condition tab " response = ".
execute.
</code>```

The variable tab is created to separate the outputs (text, variables) in the write outfile command into different cells in Excel file.
I run the syntax on one computer (SPSS 23, 64-bit) and it works as expected, like this:

```<code>|if id = | 1 | and condition = | 2 |response =|
</code>```

Each | represent a cell.

However, I run on another computer (SPSS 23, 32-bit) and it doesn't work. It particular, it dumps all fields from the write outfile into one single cell. It looks like this

```<code>|if id = 1 and condition = 2 response =|
</code>```

Can you tell what may go wrong? I suspect it has something to do with variable tab. And what does pib format mean?

UPDATE: I try to write outfile in text format and the tab works OK.

```<code>write outfile='Directory\outfile.txt' / " if id = " tab id tab " and condition = " tab condition tab " response = ".
</code>```

答:
The WRITE command is always creating a text file regardless of the file extension. (SAVE TRANSLATE could create Excel files directly.). So the difference may be on the Excel side.  Looking at the WRITE output as a hex dump would show for sure what is being written.

PIB format stands for Positive Integer Binary.  It is used here to say to treat 9 as a character code rather than the numeric value 9.  9 is the character code for a tab.

Body:
I have a data set consisting of variables id, condition, response. I have the following syntax to generate an Excel file, say, for data cleaning:

compute tab=9.
formats tab (pib).
write outfile='Directory\outfile.xls' / " if id = " tab id tab " and condition = " tab condition tab " response = ".
execute.

The variable tab is created to separate the outputs (text, variables) in the write outfile command into different cells in Excel file.
I run the syntax on one computer (SPSS 23, 64-bit) and it works as expected, like this:

|if id = | 1 | and condition = | 2 |response =|

Each | represent a cell.

However, I run on another computer (SPSS 23, 32-bit) and it doesn't work. It particular, it dumps all fields from the write outfile into one single cell. It looks like this

|if id = 1 and condition = 2 response =|

Can you tell what may go wrong? I suspect it has something to do with variable tab. And what does pib format mean?

UPDATE: I try to write outfile in text format and the tab works OK.

write outfile='Directory\outfile.txt' / " if id = " tab id tab " and condition = " tab condition tab " response = ".


问:
Retaining n most recent directories in a backup script
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017
</code>```

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
</code>```

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

```<code>find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;
</code>```

Do you guys have another idea to do that?

答:
Since your directories have well-defined and integer names, I'd just use bash to calculate the appropriate targets:

```<code>mkdir -p backup/201{2..7} # just for testing

cd backup
rm -fr $(seq 2012 $(( $(date +"%Y") - 3)))
</code>```

seq generates a list of numbers from 2012 through the current year minus 3, which are then passed to rm to blast them.

Body:
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

/home/backup/2012
/home/backup/2013
/home/backup/2014

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;

Do you guys have another idea to do that?

Body:
Since your directories have well-defined and integer names, I'd just use bash to calculate the appropriate targets:

mkdir -p backup/201{2..7} # just for testing

cd backup
rm -fr $(seq 2012 $(( $(date +"%Y") - 3)))

seq generates a list of numbers from 2012 through the current year minus 3, which are then passed to rm to blast them.


问:
CodeIgniter / Ajax . Posting parameters through ajax to CodeIgniter controller
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

```<code>$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

        });
      });
</code>```

Here is my controller function.

```<code>    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}
</code>```

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

答:
```<code>$.ajax({
   url:"<?php echo base_url(); ?>products/add_product_to_cart",
   type:"POST",
   data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
   success:function(data)
   {
      alert('success');
   }
);
</code>```

in your method : "POST" change it to type: "POST", ajax doesnt using the same way like html.

Body:
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

        });
      });

Here is my controller function.

    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

Body:
$.ajax({
   url:"<?php echo base_url(); ?>products/add_product_to_cart",
   type:"POST",
   data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
   success:function(data)
   {
      alert('success');
   }
);

in your method : "POST" change it to type: "POST", ajax doesnt using the same way like html.


问:
Using CASE WHEN
I have the following table:

```<code>Email | value | group
 a    |   1   |   x
 a    |   2   |   y
 a    |   3   |   y
 b    |   3   |   z
</code>```

I previously wrote code to pull the sum of values by distinct email in each group, to get this:

```<code>Email | value | group
 a    |   1   |   x
 a    |   5   |   y
 b    |   3   |   z
</code>```

The code looked like this:

```<code> SELECT distinct email,
        group,
        sum (value)
  from t
 group by email, group
</code>```

Now, I want to sum by groups of groups using CASE, to get this output:

```<code> Email | value | super_group
 a     |   6    |   x_y
 b     |   3    |   z
</code>```

But this code doesn't work:

```<code> SELECT distinct email,
        CASE when group in (x,y)
             then 'x_y'
             else 'z'
        end as super_group,
        sum (value)
   from t
  group by email, super_group
</code>```

答:
You can use ARRAY_AGG

Also, if you are using a GROUP BY you don't need the DISTINCT. Try this way:

First you will have to define an ARRAY Type like this:

```<code>-- note the varchar with size 20 is a sample you should pick yours
-- and the size of the array is also an example
CREATE TYPE group_array AS VARCHAR(20) ARRAY[100];
</code>```

Then you can make your query return the array type with the group value aggregated.

```<code>SELECT email,
       sum (value) as value,
       ARRAY_AGG(group, NEW group_array()) as super_group
 FROM t
GROUP BY email
</code>```

That should give you as result:

```<code> email   | value  | super_group
   a     |   6    |   ( x, y )
   b     |   3    |   ( z )
</code>```

Reference to ARRAY_AGG

Title: Using CASE WHEN

Body:
I have the following table:

Email | value | group
 a    |   1   |   x
 a    |   2   |   y
 a    |   3   |   y
 b    |   3   |   z

I previously wrote code to pull the sum of values by distinct email in each group, to get this:

Email | value | group
 a    |   1   |   x
 a    |   5   |   y
 b    |   3   |   z

The code looked like this:

 SELECT distinct email,
        group,
        sum (value)
  from t
 group by email, group

Now, I want to sum by groups of groups using CASE, to get this output:

 Email | value | super_group
 a     |   6    |   x_y
 b     |   3    |   z

But this code doesn't work:

 SELECT distinct email,
        CASE when group in (x,y)
             then 'x_y'
             else 'z'
        end as super_group,
        sum (value)
   from t
  group by email, super_group

Body:
You can use ARRAY_AGG

Also, if you are using a GROUP BY you don't need the DISTINCT. Try this way:

First you will have to define an ARRAY Type like this:

-- note the varchar with size 20 is a sample you should pick yours
-- and the size of the array is also an example
CREATE TYPE group_array AS VARCHAR(20) ARRAY[100];

Then you can make your query return the array type with the group value aggregated.

SELECT email,
       sum (value) as value,
       ARRAY_AGG(group, NEW group_array()) as super_group
 FROM t
GROUP BY email

That should give you as result:

 email   | value  | super_group
   a     |   6    |   ( x, y )
   b     |   3    |   ( z )

Reference to ARRAY_AGG


问:
Easier way to center a label in Xul
Is there an easier way to center a label in Xul then with the following?</p>

```<code><xul:hbox>
    <xul:spacer flex="1" />
    <xul:label id="myLabel" value="LABEL"/>
    <xul:spacer flex="1" />
</xul:hbox>
</code>```

答:
Yes.  Use box packing via the pack attribute.</p>

```<code><hbox pack="center"><label id="myLabel" value="LABEL"/></hbox.
</code>```

Title: Easier way to center a label in Xul

Body:
Is there an easier way to center a label in Xul then with the following?

<xul:hbox>
    <xul:spacer flex="1" />
    <xul:label id="myLabel" value="LABEL"/>
    <xul:spacer flex="1" />
</xul:hbox>

Body:
Yes.  Use box packing via the pack attribute.

<hbox pack="center"><label id="myLabel" value="LABEL"/></hbox.


问:
iOS best practices - Custom back action, popToViewController: vs manually removing the controller from navigation stack
Overview:

I've 3 controllers A,B & C and pushing the view controllers as shown in the picture below.

Scenario

I always want to pop the view controller to 'A' no matter what. Assume the below flow.

```<code>NC > A > B > C
</code>```

There are two ways to handle the Back action.

• popToViewController: - pop to specific view controller, in this case 'A'.

• Remove view controller 'B' from navigation stack. In this way the view controller 'C' always pop back to view controller 'A'.

Question:

Since iOS back button (navigationBar.backButtonItem) doesn't have any action to be customized except pop, we have to add a custom left bar button as back button and add the button action to handle popViewController: manually.

In other scenario if we remove the view controller B from the navigation stack and leave the default navigation bar back button as it is. And when tapped on back button it will pop to view controller 'A'.

Which is the best option to proceed and kindly brief why is it better?

Note

View controller 'A' is not root view controller and not looking for code solutions.

Thanks.

答:
Best way would be to use popToViewController:animated API call to pop to desired viewController, you can use

```<code>if let viewControllerA = self.navigationController?.viewControllers[1] as? ViewControllerA { //replace index
   self.navigationController?.popToViewController(viewController, animated: true)
}
</code>```

to go back to 'ViewController-A' from 'ViewController-C' using custom leftbarButton and adding action to it.

From VC-B you can go normally using

self.navigationController?.popViewController(animated: true)

Edit:

• popToViewController: - pop to specific view controller: this would be better approach as it uses UINavigationController API without overhead of removing any view controllers from the navigation stack, which will give clarity when reading the code plus extra advantage of going back to VC-B if some use case required in future to show VC-B so you can easily plug that in backAction of leftBarbuttonItem or call it from the code anywhere in VC-C.

Body:
Overview:

I've 3 controllers A,B & C and pushing the view controllers as shown in the picture below.

Scenario

I always want to pop the view controller to 'A' no matter what. Assume the below flow.

NC > A > B > C

There are two ways to handle the Back action.

• popToViewController: - pop to specific view controller, in this case 'A'.

• Remove view controller 'B' from navigation stack. In this way the view controller 'C' always pop back to view controller 'A'.

Question:

Since iOS back button (navigationBar.backButtonItem) doesn't have any action to be customized except pop, we have to add a custom left bar button as back button and add the button action to handle popViewController: manually.

In other scenario if we remove the view controller B from the navigation stack and leave the default navigation bar back button as it is. And when tapped on back button it will pop to view controller 'A'.

Which is the best option to proceed and kindly brief why is it better?

Note

View controller 'A' is not root view controller and not looking for code solutions.

Thanks.

Body:
Best way would be to use popToViewController:animated API call to pop to desired viewController, you can use

if let viewControllerA = self.navigationController?.viewControllers[1] as? ViewControllerA { //replace index
   self.navigationController?.popToViewController(viewController, animated: true)
}

to go back to 'ViewController-A' from 'ViewController-C' using custom leftbarButton and adding action to it.

From VC-B you can go normally using

self.navigationController?.popViewController(animated: true)

Edit:

• popToViewController: - pop to specific view controller: this would be better approach as it uses UINavigationController API without overhead of removing any view controllers from the navigation stack, which will give clarity when reading the code plus extra advantage of going back to VC-B if some use case required in future to show VC-B so you can easily plug that in backAction of leftBarbuttonItem or call it from the code anywhere in VC-C.


问:
The range for a relaxed state/normal state/stressful state using a Galvanic Skin Response (skin conductance )
I want to measure Skin conductance using Galvanic Skin sensor. I use Arduino software.

So I want to know the actual value range for a relaxed person and for a stressed person.
Also I want to know What is the actual unit for this measurement.

This is my ardiuno source code .

```<code>const int LED=13;
const int GSR=A2;
int threshold=0;
int sensorValue;

void setup(){
  long sum=0;
  Serial.begin(9600);
  pinMode(LED,OUTPUT);
  digitalWrite(LED,LOW);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.print("sensorValue=");
  Serial.println(sensorValue);
  temp = threshold - sensorValue;

 }
}
</code>```

答:
```<code>analogRead(GSR);
</code>```

This gives you value from 0~1023, you need to map it to a certain range, or do some calculations.

Check datasheet, or provide us, the sensor's name.

Body:
I want to measure Skin conductance using Galvanic Skin sensor. I use Arduino software.

So I want to know the actual value range for a relaxed person and for a stressed person.
Also I want to know What is the actual unit for this measurement.

This is my ardiuno source code .

const int LED=13;
const int GSR=A2;
int threshold=0;
int sensorValue;

void setup(){
  long sum=0;
  Serial.begin(9600);
  pinMode(LED,OUTPUT);
  digitalWrite(LED,LOW);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.print("sensorValue=");
  Serial.println(sensorValue);
  temp = threshold - sensorValue;

 }
}

Body:
analogRead(GSR);

This gives you value from 0~1023, you need to map it to a certain range, or do some calculations.

Check datasheet, or provide us, the sensor's name.


问:
CSS style priority
Before this question, I already search 'CSS priority' and I found following

The priority of inline style like
 is higher than class blue which define color:blue; And this rule is still work between tag and inline, i.e., inline has higher priority than tag.

Now I encounter a obstacle that I don't know. Here, simple example of my case.

First there are
s

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

and they have CSS

```<code>div { backgorund:url('path') no-repeat; }
div:nth-child(2n+1) { background-position: 'position A'; }
</code>```

Now first and third
 has same background image at position A.
Then I tried change third
's background like

```<code><div></div>
<div></div>
<div style="background-position: 'position B';"></div>
</code>```

But the inline style of third
 is not applied, still the :nth-child's style occupy it. (third
 still has background-position with 'position A')

I want to change third
's background image that only has different
background position. How can I do this?

(I know the priority of inline style is always higher than any others. But
 in this case, it does not work)

for specification here my code

```<code>#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li>
        <div style='background-position:-551px -438px;'></div>
    </li>
</ul>
</code>```

答:
EDITED to your scenario (used background color for better illustration, you can simply replace them for position):

#courseList>li:nth-child(2n+1) {
  background: red;
}

#courseList>li:nth-child(2n+2) {
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="courseList">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li style='background: blue;'>
    <div></div>
  </li>
</ul></code>```

Here's a generic example:

div {
  background: red;
  height: 50px;
  width: 50px;
}

div:nth-child(2n+1) {
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div>
<div></div>
<div style="background: green;"></div></code>```

Title: CSS style priority

Body:
Before this question, I already search 'CSS priority' and I found following

The priority of inline style like
 is higher than class blue which define color:blue; And this rule is still work between tag and inline, i.e., inline has higher priority than tag.

Now I encounter a obstacle that I don't know. Here, simple example of my case.

First there are
s

and they have CSS

div { backgorund:url('path') no-repeat; }
div:nth-child(2n+1) { background-position: 'position A'; }

Now first and third
 has same background image at position A.
Then I tried change third
's background like

But the inline style of third
 is not applied, still the :nth-child's style occupy it. (third
 still has background-position with 'position A')

I want to change third
's background image that only has different
background position. How can I do this?

(I know the priority of inline style is always higher than any others. But
 in this case, it does not work)

for specification here my code

#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

Body:
EDITED to your scenario (used background color for better illustration, you can simply replace them for position):

#courseList>li:nth-child(2n+1) {
  background: red;
}

#courseList>li:nth-child(2n+2) {
  background: green;
}

<ul id="courseList">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li style='background: blue;'>
    <div></div>
  </li>
</ul>

Here's a generic example:

div {
  background: red;
  height: 50px;
  width: 50px;
}

div:nth-child(2n+1) {
  background: blue;
}

<div></div>
<div></div>
<div style="background: green;"></div>


问:
Finding pattern in string using indexof
Can someone tell me why this is an infinte loop?    </p>

```<code>private void splitBody()    {
        bodyparts=new Vector();
        String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("<br />",previousIndex)!=-1) {
            int index=body.indexOf("<br />",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }
</code>```

答:
Because you don't change your body string, so indexOf always returns an index different that -1 since the substring is contained in body.

Add body = body.substring(index); at the end of the loop to fix that.

Title: Finding pattern in string using indexof

Body:
Can someone tell me why this is an infinte loop?

private void splitBody()    {
        bodyparts=new Vector();
        String body = "
testtestest
fefefefefefefefefef
qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("
",previousIndex)!=-1) {
            int index=body.indexOf("
",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }


问:
Django Tutorial: name 'HttpResponse' is not defined
I am learning Django via their tutorial for getting started. I have looked at other Django Tutorial errors and did not see this one (although I did not search every listing).

I have made the changes to mysite/urls.py and polls/urls.py exactly as they demonstrate and I have run the server command:

```<code>python manage.py runserver
</code>```

I get the following error:

Since I am new to Django, I do not know what is going on. Please help.

答:
from django.http import HttpResponse
add this line on the top of polls/views.py file. I am new too, and had the same error. good Luck and i see u around.

Body:
I am learning Django via their tutorial for getting started. I have looked at other Django Tutorial errors and did not see this one (although I did not search every listing).

I have made the changes to mysite/urls.py and polls/urls.py exactly as they demonstrate and I have run the server command:

python manage.py runserver

I get the following error:

Since I am new to Django, I do not know what is going on. Please help.


答:
Try this(this will install oracle JDK),

First update the apt-get repos

```<code>$ sudo apt-get update
</code>```

Add the java(7 and 8) repo to apt-get

```<code>$ sudo add-apt-repository ppa:webupd8team/java
</code>```

Again update the apt-get repo

```<code>$ sudo apt-get update
</code>```

Finally install java 7

```<code>$ sudo apt-get install oracle-java7-installer
</code>```

Title: I can't install JDK7 on Ubuntu 16.04 Download Failed

Body:
I'm trying to install jdk7 on a my Ubuntu 16.04 machine, here are the commands that I executed:

sudo apt-get update
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

The last one returned Download Failed error and was not able to install the package.

Error Screenshot

When I did some digging I found that Oracle no longer provide JDK7 download link on their official site.

If someone has figured out a way to install it please help !

Body:
Try this(this will install oracle JDK),

First update the apt-get repos

$ sudo apt-get update

Add the java(7 and 8) repo to apt-get

$ sudo add-apt-repository ppa:webupd8team/java

Again update the apt-get repo

$ sudo apt-get update

Finally install java 7

$ sudo apt-get install oracle-java7-installer


问:
Is there a way to list all resources in AWS
Is there a way to list all resources in AWS? For all regions, all resources.. Such as list all EC2 instances, all VPCs, all APIs in API Gateway, etc...  I would like to list all resources for my account, since it's hard for me to find which resources I can relinquish now.</p>

答:
Edit: This answer is deprecated and is incorrect. There are several ways to list AWS resources (the AWS Tag Editor, etc.). Check
  the other answers for more details.

No.

Each AWS Service (eg Amazon EC2, Amazon S3) have their own set of API calls. Also, each Region is independent.

To obtain a list of all resources, you would have to make API calls to every service in every region.

You might want to activate AWS Config:

AWS Config provides a detailed view of the configuration of AWS resources in your AWS account. This includes how the resources are related to one another and how they were configured in the past so that you can see how the configurations and relationships change over time.

However, AWS Config only collects information about EC2/VPC-related resources, not everything in your AWS account.

ContentLicense: CC BY-SA 4.0


问:
How can I use regex to parse an OCC Option Symbol?
The OCC option symbol consists of 4 parts:

Root symbol of the underlying stock or ETF, padded with spaces to 6 characters

Expiration date, 6 digits in the format yymmdd

Option type, either P or C, for put or call

Strike price, as the price x 1000, front padded with 0s to 8 digits

As an example SPX   141122P00019500 means a put on SPX, expiring on 11/22/2014, with a strike price of $19.50.

Is it possible to use regex to parse this out automatically? I'm using JavaScript

答:
Here is the regex (I highly recommend http://regexr.com)

```<code>([\w ]{6})((\d{2})(\d{2})(\d{2}))([PC])(\d{8})
</code>```

Group1: ETF

Group2: Year

Group3:Month

Group4: Day

Group5: put/call

Group6: strike price

Your js would look something like this (somewhat psuedo-code. Not tested)

```<code>var myString = "SPX   141122P00019500";
var myRegexp = /([\w ]{6})((\d{2})(\d{2})(\d{2}))([PC])(\d{8})/g;
var match = myRegexp.exec(myString);

console.log("a " + match[5] + " on " + match[1].trim() + ", expiring on " + match[3] + "/" + match[4] + "/20" + match[2] + " with a strike price of $" + match[6]);
</code>```

Body:
Here is the regex (I highly recommend http://regexr.com)

([\w ]{6})((\d{2})(\d{2})(\d{2}))([PC])(\d{8})

Group1: ETF

Group2: Year

Group3:Month

Group4: Day

Group5: put/call

Group6: strike price

Your js would look something like this (somewhat psuedo-code. Not tested)

var myString = "SPX   141122P00019500";
var myRegexp = /([\w ]{6})((\d{2})(\d{2})(\d{2}))([PC])(\d{8})/g;
var match = myRegexp.exec(myString);

console.log("a " + match[5] + " on " + match[1].trim() + ", expiring on " + match[3] + "/" + match[4] + "/20" + match[2] + " with a strike price of $" + match[6]);


问:
why no whole width of screen is covered?
I use css and JavaScript to lock screen, but I am not sure why the lock panel is not the same width as screen, do you have any idea?
Here is HTML source and you find javascript code as below, does anyone help me?

JavaScript:

```<code>function FreezeScreen(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}
</code>```

HTML:

```<code><body>
<div align="center" id="FreezePane" class="FreezePaneOff">
   <div id="InnerFreezePane" class="InnerFreezePane"> </div>
</div>
</code>```

CSS:

```<code>.FreezePaneOff {
  visibility: hidden;
  display: none;
  position: absolute;
  top: -100px;
  left: -100px;
}

.FreezePaneOn {
  position: absolute;
  top: 0px;
  left: 0px;
  visibility: visible;
  display: block;
  width: 100%;
  height: 100%;
  background-color: #666;
  z-index: 999;
  filter:alpha(opacity=85);
  -moz-opacity:0.85;
  padding-top: 20%;
}

.InnerFreezePane {
  text-align: center;
  width: 66%;
  background-color: #171;
  color: White;
  font-size: large;
  border: dashed 2px #111;
  padding: 9px;
}
</code>```

答:
If you want it to cover the screen you could change position:absolute to position:fixed

Position property :

absolute - The element is positioned relative to its first positioned
  (not static) ancestor element.

fixed - The element is positioned relative to the browser window.

Body:
I use css and JavaScript to lock screen, but I am not sure why the lock panel is not the same width as screen, do you have any idea?
Here is HTML source and you find javascript code as below, does anyone help me?

JavaScript:

function FreezeScreen(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}

HTML:

CSS:

.FreezePaneOff {
  visibility: hidden;
  display: none;
  position: absolute;
  top: -100px;
  left: -100px;
}

.FreezePaneOn {
  position: absolute;
  top: 0px;
  left: 0px;
  visibility: visible;
  display: block;
  width: 100%;
  height: 100%;
  background-color: #666;
  z-index: 999;
  filter:alpha(opacity=85);
  -moz-opacity:0.85;
  padding-top: 20%;
}

.InnerFreezePane {
  text-align: center;
  width: 66%;
  background-color: #171;
  color: White;
  font-size: large;
  border: dashed 2px #111;
  padding: 9px;
}


问:
translate CGContext generating image method from ios to mac
Is anyone able to help me translate this method in ios to mac version? Code is written in C# in Xamarin</p>

```<code>public static UIImage GetImageFromColor(UIColor color, float borderWidth = 1.0f)
    {
        var rect = new CGRect(0.0f, 0.0f, borderWidth, borderWidth);
        UIGraphics.BeginImageContext(rect.Size);
        var context = UIGraphics.GetCurrentContext();
        context.SetFillColor(color.CGColor);
        context.FillRect(rect);

        var image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return image.CreateResizableImage(new UIEdgeInsets(1.0f, 1.0f, 1.0f, 1.0f));
    }
</code>```

答:
This is not a translation from the code you posted but it does exactly the same job:

```<code>public static NSImage GetImageFromColor (NSColor color, float borderWidth = 1.0f)
{
    var image = new NSImage (new CGSize (borderWidth, borderWidth));
    image.LockFocus ();
    color.DrawSwatchInRect (new CGRect (new CGPoint (0, 0), image.Size));
    image.UnlockFocus ();

    return image;
}
</code>```

Hope this helps.-

Body:
Is anyone able to help me translate this method in ios to mac version? Code is written in C# in Xamarin

public static UIImage GetImageFromColor(UIColor color, float borderWidth = 1.0f)
    {
        var rect = new CGRect(0.0f, 0.0f, borderWidth, borderWidth);
        UIGraphics.BeginImageContext(rect.Size);
        var context = UIGraphics.GetCurrentContext();
        context.SetFillColor(color.CGColor);
        context.FillRect(rect);

        var image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return image.CreateResizableImage(new UIEdgeInsets(1.0f, 1.0f, 1.0f, 1.0f));
    }

Body:
This is not a translation from the code you posted but it does exactly the same job:

public static NSImage GetImageFromColor (NSColor color, float borderWidth = 1.0f)
{
    var image = new NSImage (new CGSize (borderWidth, borderWidth));
    image.LockFocus ();
    color.DrawSwatchInRect (new CGRect (new CGPoint (0, 0), image.Size));
    image.UnlockFocus ();

    return image;
}

Hope this helps.-


问:
AJAX error Response for preflight has invalid HTTP status code 403 to Spring
I want run POST AJAX but I found an error > Response for preflight has invalid HTTP status code 403. I created POST method in Spring and I want consume with AJAX (I use SAPUI5 frontend based on javascript).

Error and Invalid CORS Request

Headers

Log when run spring (maven project):

```<code>org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$793b4734]
> is not eligible for getting processed by all BeanPostProcessors (for
> example: not eligible for auto-proxying) [INFO] Loaded JDBC driver:
> com.mysql.jdbc.Driver [INFO] HCANN000001: Hibernate Commons
> Annotations {4.0.5.Final} [INFO] HHH000412: Hibernate Core
> {4.3.11.Final} [INFO] HHH000206: hibernate.properties not found [INFO]
> HHH000021: Bytecode provider name : javassist [INFO] HHH000400: Using
> dialect: org.hibernate.dialect.MySQLDialect [INFO] HHH000423:
> Disabling contextual LOB creation as JDBC driver reported JDBC version
> 2 less than 4 [INFO] HHH000399: Using default transaction strategy
> (direct JDBC transactions) [INFO] HHH000397: Using
> ASTQueryTranslatorFactory [INFO] Mapped
> "{[/tesupdate],methods=[PUT],consumes=[application/json]}" onto public
> org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.update(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped
> "{[/tesinsert],methods=[POST],consumes=[application/json]}" onto
> public org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.insert(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped "{[/**],methods=[OPTIONS]}"
> onto public void
> com.project.maven.controller.UserController.corsHeaders(javax.servlet.http.HttpServletResponse)
> [INFO] Mapped "{[/tesget],methods=[GET]}" onto public java.util.List
> com.project.maven.controller.UserController.getTes2() throws
> java.lang.Exception [INFO] Mapped
> "{[/v2/api-docs],methods=[GET],produces=[application/json ||
> application/hal+json]}" onto public
> org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json>
> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
> [INFO] Mapped "{[/swagger-resources/configuration/security]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
> [INFO] Mapped "{[/swagger-resources/configuration/ui]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
> [INFO] Mapped "{[/swagger-resources]}" onto
> org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>>
> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
> [INFO] Mapped URL path [/static/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Mapped URL path [/**/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Looking for @ControllerAdvice: Root WebApplicationContext:
> startup date [Tue Jun 06 10:22:39 ICT 2017]; root of context hierarchy
> [INFO] Using DataSource
> [org.springframework.jdbc.datasource.DriverManagerDataSource@1dafa047]
> of Hibernate SessionFactory for HibernateTransactionManager [INFO]
> Starting beans in phase 2147483647 [INFO] Context refreshed [INFO]
> Found 1 custom documentation plugin(s) [INFO] Scanning for api listing
> references [INFO] Root WebApplicationContext: initialization completed
> in 7923 ms Jun 06, 2017 10:22:47 AM
> org.apache.catalina.core.ApplicationContext log INFO: Initializing
> Spring FrameworkServlet 'appServlet' [INFO] FrameworkServlet
> 'appServlet': initialization started [INFO] Refreshing
> WebApplicationContext for namespace 'appServlet-servlet': startup date
> [Tue Jun 06 10:22:47 ICT 2017]; parent: Root WebApplicationContext
> [INFO] Loading XML bean definitions from ServletContext resource
> [/WEB-INF/config/servlet-context.xml] [INFO] FrameworkServlet
> 'appServlet': initialization completed in 50 ms Jun 06, 2017 10:22:47
> AM org.apache.catalina.core.ApplicationContext log INFO: Initializing
> Spring FrameworkServlet 'dispatcher' [INFO] FrameworkServlet
> 'dispatcher': initialization started [INFO] Refreshing
> WebApplicationContext for namespace 'dispatcher-servlet': startup date
> [Tue Jun 06 10:22:47 ICT 2017]; parent: Root WebApplicationContext
> [INFO] Registering annotated classes: [class
> com.project.maven.config.AppConfig] [INFO] JSR-330
> 'javax.inject.Inject' annotation found and supported for autowiring
> [INFO] Bean
> 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration'
> of type [class
> org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$793b4734]
> is not eligible for getting processed by all BeanPostProcessors (for
> example: not eligible for auto-proxying) [INFO] Loaded JDBC driver:
> com.mysql.jdbc.Driver [INFO] HHH000400: Using dialect:
> org.hibernate.dialect.MySQLDialect [INFO] HHH000423: Disabling
> contextual LOB creation as JDBC driver reported JDBC version 2 less
> than 4 [INFO] HHH000399: Using default transaction strategy (direct
> JDBC transactions) [INFO] HHH000397: Using ASTQueryTranslatorFactory
> [INFO] Mapped
> "{[/tesupdate],methods=[PUT],consumes=[application/json]}" onto public
> org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.update(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped
> "{[/tesinsert],methods=[POST],consumes=[application/json]}" onto
> public org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.insert(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped "{[/**],methods=[OPTIONS]}"
> onto public void
> com.project.maven.controller.UserController.corsHeaders(javax.servlet.http.HttpServletResponse)
> [INFO] Mapped "{[/tesget],methods=[GET]}" onto public java.util.List
> com.project.maven.controller.UserController.getTes2() throws
> java.lang.Exception [INFO] Mapped
> "{[/v2/api-docs],methods=[GET],produces=[application/json ||
> application/hal+json]}" onto public
> org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json>
> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
> [INFO] Mapped "{[/swagger-resources/configuration/security]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
> [INFO] Mapped "{[/swagger-resources/configuration/ui]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
> [INFO] Mapped "{[/swagger-resources]}" onto
> org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>>
> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
> [INFO] Using DataSource
> [org.springframework.jdbc.datasource.DriverManagerDataSource@3afb8a87]
> of Hibernate SessionFactory for HibernateTransactionManager [INFO]
> Mapped URL path [/static/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Mapped URL path [/**/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Looking for @ControllerAdvice: WebApplicationContext for
> namespace 'dispatcher-servlet': startup date [Tue Jun 06 10:22:47 ICT
> 2017]; parent: Root WebApplicationContext [INFO] Starting beans in
> phase 2147483647 [INFO] Context refreshed [INFO] Found 1 custom
> documentation plugin(s) [INFO] Scanning for api listing references
> [INFO] FrameworkServlet 'dispatcher': initialization completed in 1351
> ms Jun 06, 2017 10:22:48 AM org.apache.coyote.AbstractProtocol start
> INFO: Starting ProtocolHandler ["http-bio-8089"]
</code>```

Controller in Spring:

```<code>@PostMapping(value={"/tesinsert"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(@RequestBody KasusEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabel(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}
</code>```

in javascript:

```<code>    var data = {
            "kodekasus":5,
            "nama":"baru",
            "isdelete":1,
            "createdby":"hahaa",
            "createddate":null,
            "updatedby":"hihii",
            "updateddate":null
    };

    var url = "http://localhost:8089/SpringNew/tesinsert";

    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: JSON.stringify(data),
        success: function(data) {
            console.log('sukses: '+data);
        },
        error: function(error){
            console.log('gagal: '+error);
            console.log(data);
        }
        ,
        headers: {
            Accept : "application/json",
            "Content-type": "application/json;charset=UTF-8"
            }
    });
</code>```

How to solve this problem? Where code is wrong? in javascript or spring? I already try run insert method in spring with Swagger and I can insert data. I already try ajax GET and no problem. Before this, I also found a problem with AJAX GET but I solved this problem with clear "contentType" in ajax. but in AJAX POST cannot.

Thanks.

Bobby

答:
this my code in KasusEntity:

```<code>package com.project.maven.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="KASUS")
public class KasusEntity implements Serializable {

    @Id
    @Column(name="KODE_KASUS")
    private int kodekasus;

    @Column(name="NAMA")
    private String nama;

    @Column(name="IS_DELETE")
    private int isdelete;

    @Column(name="CREATED_BY")
    private String createdby;

    @Column(name="CREATED_DATE")
    private Date createddate;

    @Column(name="UPDATED_BY")
    private String updatedby;

    @Column(name="UPDATED_DATE")
    private Date updateddate;

    public int getKodekasus() {
        return kodekasus;
    }

    public void setKodekasus(int kodekasus) {
        this.kodekasus = kodekasus;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    public int getIsdelete() {
        return isdelete;
    }

    public void setIsdelete(int isdelete) {
        this.isdelete = isdelete;
    }

    public String getCreatedby() {
        return createdby;
    }

    public void setCreatedby(String createdby) {
        this.createdby = createdby;
    }

    public Date getCreateddate() {
        return createddate;
    }

    public void setCreateddate(Date createddate) {
        this.createddate = createddate;
    }

    public String getUpdatedby() {
        return updatedby;
    }

    public void setUpdatedby(String updatedby) {
        this.updatedby = updatedby;
    }

    public Date getUpdateddate() {
        return updateddate;
    }

    public void setUpdateddate(Date updateddate) {
        this.updateddate = updateddate;
    }

}
</code>```

Thanks.
Bobby

Body:
I want run POST AJAX but I found an error > Response for preflight has invalid HTTP status code 403. I created POST method in Spring and I want consume with AJAX (I use SAPUI5 frontend based on javascript).

Error and Invalid CORS Request

Headers

Log when run spring (maven project):

org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$793b4734]
> is not eligible for getting processed by all BeanPostProcessors (for
> example: not eligible for auto-proxying) [INFO] Loaded JDBC driver:
> com.mysql.jdbc.Driver [INFO] HCANN000001: Hibernate Commons
> Annotations {4.0.5.Final} [INFO] HHH000412: Hibernate Core
> {4.3.11.Final} [INFO] HHH000206: hibernate.properties not found [INFO]
> HHH000021: Bytecode provider name : javassist [INFO] HHH000400: Using
> dialect: org.hibernate.dialect.MySQLDialect [INFO] HHH000423:
> Disabling contextual LOB creation as JDBC driver reported JDBC version
> 2 less than 4 [INFO] HHH000399: Using default transaction strategy
> (direct JDBC transactions) [INFO] HHH000397: Using
> ASTQueryTranslatorFactory [INFO] Mapped
> "{[/tesupdate],methods=[PUT],consumes=[application/json]}" onto public
> org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.update(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped
> "{[/tesinsert],methods=[POST],consumes=[application/json]}" onto
> public org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.insert(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped "{[/**],methods=[OPTIONS]}"
> onto public void
> com.project.maven.controller.UserController.corsHeaders(javax.servlet.http.HttpServletResponse)
> [INFO] Mapped "{[/tesget],methods=[GET]}" onto public java.util.List
> com.project.maven.controller.UserController.getTes2() throws
> java.lang.Exception [INFO] Mapped
> "{[/v2/api-docs],methods=[GET],produces=[application/json ||
> application/hal+json]}" onto public
> org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json>
> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
> [INFO] Mapped "{[/swagger-resources/configuration/security]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
> [INFO] Mapped "{[/swagger-resources/configuration/ui]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
> [INFO] Mapped "{[/swagger-resources]}" onto
> org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>>
> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
> [INFO] Mapped URL path [/static/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Mapped URL path [/**/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Looking for @ControllerAdvice: Root WebApplicationContext:
> startup date [Tue Jun 06 10:22:39 ICT 2017]; root of context hierarchy
> [INFO] Using DataSource
> [org.springframework.jdbc.datasource.DriverManagerDataSource@1dafa047]
> of Hibernate SessionFactory for HibernateTransactionManager [INFO]
> Starting beans in phase 2147483647 [INFO] Context refreshed [INFO]
> Found 1 custom documentation plugin(s) [INFO] Scanning for api listing
> references [INFO] Root WebApplicationContext: initialization completed
> in 7923 ms Jun 06, 2017 10:22:47 AM
> org.apache.catalina.core.ApplicationContext log INFO: Initializing
> Spring FrameworkServlet 'appServlet' [INFO] FrameworkServlet
> 'appServlet': initialization started [INFO] Refreshing
> WebApplicationContext for namespace 'appServlet-servlet': startup date
> [Tue Jun 06 10:22:47 ICT 2017]; parent: Root WebApplicationContext
> [INFO] Loading XML bean definitions from ServletContext resource
> [/WEB-INF/config/servlet-context.xml] [INFO] FrameworkServlet
> 'appServlet': initialization completed in 50 ms Jun 06, 2017 10:22:47
> AM org.apache.catalina.core.ApplicationContext log INFO: Initializing
> Spring FrameworkServlet 'dispatcher' [INFO] FrameworkServlet
> 'dispatcher': initialization started [INFO] Refreshing
> WebApplicationContext for namespace 'dispatcher-servlet': startup date
> [Tue Jun 06 10:22:47 ICT 2017]; parent: Root WebApplicationContext
> [INFO] Registering annotated classes: [class
> com.project.maven.config.AppConfig] [INFO] JSR-330
> 'javax.inject.Inject' annotation found and supported for autowiring
> [INFO] Bean
> 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration'
> of type [class
> org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$793b4734]
> is not eligible for getting processed by all BeanPostProcessors (for
> example: not eligible for auto-proxying) [INFO] Loaded JDBC driver:
> com.mysql.jdbc.Driver [INFO] HHH000400: Using dialect:
> org.hibernate.dialect.MySQLDialect [INFO] HHH000423: Disabling
> contextual LOB creation as JDBC driver reported JDBC version 2 less
> than 4 [INFO] HHH000399: Using default transaction strategy (direct
> JDBC transactions) [INFO] HHH000397: Using ASTQueryTranslatorFactory
> [INFO] Mapped
> "{[/tesupdate],methods=[PUT],consumes=[application/json]}" onto public
> org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.update(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped
> "{[/tesinsert],methods=[POST],consumes=[application/json]}" onto
> public org.springframework.http.ResponseEntity<?>
> com.project.maven.controller.UserController.insert(com.project.maven.entity.KasusEntity)
> throws java.lang.Exception [INFO] Mapped "{[/**],methods=[OPTIONS]}"
> onto public void
> com.project.maven.controller.UserController.corsHeaders(javax.servlet.http.HttpServletResponse)
> [INFO] Mapped "{[/tesget],methods=[GET]}" onto public java.util.List
> com.project.maven.controller.UserController.getTes2() throws
> java.lang.Exception [INFO] Mapped
> "{[/v2/api-docs],methods=[GET],produces=[application/json ||
> application/hal+json]}" onto public
> org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json>
> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
> [INFO] Mapped "{[/swagger-resources/configuration/security]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
> [INFO] Mapped "{[/swagger-resources/configuration/ui]}" onto
> org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration>
> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
> [INFO] Mapped "{[/swagger-resources]}" onto
> org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>>
> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
> [INFO] Using DataSource
> [org.springframework.jdbc.datasource.DriverManagerDataSource@3afb8a87]
> of Hibernate SessionFactory for HibernateTransactionManager [INFO]
> Mapped URL path [/static/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Mapped URL path [/**/**] onto handler of type [class
> org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
> [INFO] Looking for @ControllerAdvice: WebApplicationContext for
> namespace 'dispatcher-servlet': startup date [Tue Jun 06 10:22:47 ICT
> 2017]; parent: Root WebApplicationContext [INFO] Starting beans in
> phase 2147483647 [INFO] Context refreshed [INFO] Found 1 custom
> documentation plugin(s) [INFO] Scanning for api listing references
> [INFO] FrameworkServlet 'dispatcher': initialization completed in 1351
> ms Jun 06, 2017 10:22:48 AM org.apache.coyote.AbstractProtocol start
> INFO: Starting ProtocolHandler ["http-bio-8089"]

Controller in Spring:

@PostMapping(value={"/tesinsert"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(@RequestBody KasusEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabel(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}

in javascript:

    var data = {
            "kodekasus":5,
            "nama":"baru",
            "isdelete":1,
            "createdby":"hahaa",
            "createddate":null,
            "updatedby":"hihii",
            "updateddate":null
    };

    var url = "http://localhost:8089/SpringNew/tesinsert";

    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: JSON.stringify(data),
        success: function(data) {
            console.log('sukses: '+data);
        },
        error: function(error){
            console.log('gagal: '+error);
            console.log(data);
        }
        ,
        headers: {
            Accept : "application/json",
            "Content-type": "application/json;charset=UTF-8"
            }
    });

How to solve this problem? Where code is wrong? in javascript or spring? I already try run insert method in spring with Swagger and I can insert data. I already try ajax GET and no problem. Before this, I also found a problem with AJAX GET but I solved this problem with clear "contentType" in ajax. but in AJAX POST cannot.

Thanks.

Bobby

Body:
this my code in KasusEntity:

package com.project.maven.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="KASUS")
public class KasusEntity implements Serializable {

    @Id
    @Column(name="KODE_KASUS")
    private int kodekasus;

    @Column(name="NAMA")
    private String nama;

    @Column(name="IS_DELETE")
    private int isdelete;

    @Column(name="CREATED_BY")
    private String createdby;

    @Column(name="CREATED_DATE")
    private Date createddate;

    @Column(name="UPDATED_BY")
    private String updatedby;

    @Column(name="UPDATED_DATE")
    private Date updateddate;

    public int getKodekasus() {
        return kodekasus;
    }

    public void setKodekasus(int kodekasus) {
        this.kodekasus = kodekasus;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    public int getIsdelete() {
        return isdelete;
    }

    public void setIsdelete(int isdelete) {
        this.isdelete = isdelete;
    }

    public String getCreatedby() {
        return createdby;
    }

    public void setCreatedby(String createdby) {
        this.createdby = createdby;
    }

    public Date getCreateddate() {
        return createddate;
    }

    public void setCreateddate(Date createddate) {
        this.createddate = createddate;
    }

    public String getUpdatedby() {
        return updatedby;
    }

    public void setUpdatedby(String updatedby) {
        this.updatedby = updatedby;
    }

    public Date getUpdateddate() {
        return updateddate;
    }

    public void setUpdateddate(Date updateddate) {
        this.updateddate = updateddate;
    }

}

Thanks.
Bobby


问:
Forwarding socket.io/engine.io connection to another server
We are trying to find the best approach to our load balancing issue with websockets.

Websocket can initially connect to any server, that server will run some logic and then if needed it will "redirect" the client to appropriate server.

Is there a way in socket.io/engine.io to redirect/forward connections?

Something like:

```<code>io.use(function(socket){
    // ... logic
    if(logic === true){
        socket.redirect("172.10.10.2:3000");
    }
});
</code>```

I am aware of that socket.redirect is not valid function but is there something like that?

答:
socket.io not support something like socket.redirect

But you can use Nginx to make proxy for load balance and use socket.io-redis to make adapter for socket.io and handle if(logic === true){} in multiple nodes.

Body:
We are trying to find the best approach to our load balancing issue with websockets.

Websocket can initially connect to any server, that server will run some logic and then if needed it will "redirect" the client to appropriate server.

Is there a way in socket.io/engine.io to redirect/forward connections?

Something like:

io.use(function(socket){
    // ... logic
    if(logic === true){
        socket.redirect("172.10.10.2:3000");
    }
});

I am aware of that socket.redirect is not valid function but is there something like that?


问:
Save encoded data to another workbook
I have a macro code here in which saves the encoded data to another sheet within the same workbook. But I want to make some modification in this macro, I want the encoded data saves to another workbook, here is my code:  </p>

```<code>Sub RoundedRectangle1_Click()
Dim i, lastrow As Long
If ActiveSheet.Range("d6") = "" Or ActiveSheet.Range("g6") = "" Or ActiveSheet.Range("c9") = "" Then
MsgBox "Please complete all fields!"
Exit Sub
End If

lastrow = Sheets("database").Cells(Cells.Rows.Count, 2).End(xlUp).Row + 1
i = 9
Do While Cells(i, 3) <> "" And i < 29
Sheets("Database").Cells(lastrow, 2) = ActiveSheet.Range("g6") ' Date
Sheets("Database").Cells(lastrow, 3) = ActiveSheet.Range("d6") ' Ref
Sheets("Database").Cells(lastrow, 4) = ActiveSheet.Cells(i, 3) ' Code
Sheets("Database").Cells(lastrow, 5) = ActiveSheet.Cells(i, 4) ' Description
Sheets("Database").Cells(lastrow, 6) = ActiveSheet.Cells(i, 5) ' U/M
Sheets("Database").Cells(lastrow, 7) = ActiveSheet.Cells(i, 6) ' Qty
Sheets("Database").Cells(lastrow, 8) = ActiveSheet.Cells(i, 7) ' Price
Sheets("Database").Cells(lastrow, 9) = "IN" ' Transaction
i = i + 1
lastrow = lastrow + 1
Loop
MsgBox "Saved Succesfully!"
ThisWorkbook.Save
Call RoundedRectangle2_Click
End Sub
</code>```

答:
Maybe, code would be like this..</p>

```<code>Sub RoundedRectangle1_Click()
Dim i As Long, lastrow As Long, n As Long
Dim vResult()
Dim myWs As Worksheet

Set myWs = ThisWorkbook.Sheets("Database")

If ActiveSheet.Range("d6") = "" Or ActiveSheet.Range("g6") = "" Or ActiveSheet.Range("c9") = "" Then
MsgBox "Please complete all fields!"
Exit Sub
End If

'lastrow = Sheets("database").Cells(Cells.Rows.Count, 2).End(xlUp).Row + 1
i = 9
Do While Cells(i, 3) <> "" And i < 29
    n = n + 1
    ReDim Preserve vResult(1 To 8, 1 To n)
    vResult(1, n) = ActiveSheet.Range("g6") ' Date
    vResult(2, n) = ActiveSheet.Range("d6") ' Ref
    vResult(3, n) = ActiveSheet.Cells(i, 3) ' Code
    vResult(4, n) = ActiveSheet.Cells(i, 4) ' Description
    vResult(5, n) = ActiveSheet.Cells(i, 5) ' U/M
    vResult(6, n) = ActiveSheet.Cells(i, 6) ' Qty
    vResult(7, n) = ActiveSheet.Cells(i, 7) ' Price
    vResult(8, n) = "IN" ' Transaction
    i = i + 1

Loop

Dim wb As Workbook
'chage workbook name as  your workbook.name
Set wb = Workbooks("another.xlsx")
With wb.Sheets("Database")
    .Range("b" & Rows.Count).End(xlUp)(2).Resize(n, 8) = WorksheetFunction.Transpose(vResult)
End With
myWs.Range("b" & Rows.Count).End(xlUp)(2).Resize(n, 8) = WorksheetFunction.Transpose(vResult)

MsgBox "Saved Succesfully!"
ThisWorkbook.Save
Call RoundedRectangle2_Click
End Sub
</code>```

Title: Save encoded data to another workbook

Body:
I have a macro code here in which saves the encoded data to another sheet within the same workbook. But I want to make some modification in this macro, I want the encoded data saves to another workbook, here is my code:

Sub RoundedRectangle1_Click()
Dim i, lastrow As Long
If ActiveSheet.Range("d6") = "" Or ActiveSheet.Range("g6") = "" Or ActiveSheet.Range("c9") = "" Then
MsgBox "Please complete all fields!"
Exit Sub
End If

lastrow = Sheets("database").Cells(Cells.Rows.Count, 2).End(xlUp).Row + 1
i = 9
Do While Cells(i, 3) <> "" And i < 29
Sheets("Database").Cells(lastrow, 2) = ActiveSheet.Range("g6") ' Date
Sheets("Database").Cells(lastrow, 3) = ActiveSheet.Range("d6") ' Ref
Sheets("Database").Cells(lastrow, 4) = ActiveSheet.Cells(i, 3) ' Code
Sheets("Database").Cells(lastrow, 5) = ActiveSheet.Cells(i, 4) ' Description
Sheets("Database").Cells(lastrow, 6) = ActiveSheet.Cells(i, 5) ' U/M
Sheets("Database").Cells(lastrow, 7) = ActiveSheet.Cells(i, 6) ' Qty
Sheets("Database").Cells(lastrow, 8) = ActiveSheet.Cells(i, 7) ' Price
Sheets("Database").Cells(lastrow, 9) = "IN" ' Transaction
i = i + 1
lastrow = lastrow + 1
Loop
MsgBox "Saved Succesfully!"
ThisWorkbook.Save
Call RoundedRectangle2_Click
End Sub

Body:
Maybe, code would be like this..

Sub RoundedRectangle1_Click()
Dim i As Long, lastrow As Long, n As Long
Dim vResult()
Dim myWs As Worksheet

Set myWs = ThisWorkbook.Sheets("Database")

If ActiveSheet.Range("d6") = "" Or ActiveSheet.Range("g6") = "" Or ActiveSheet.Range("c9") = "" Then
MsgBox "Please complete all fields!"
Exit Sub
End If

'lastrow = Sheets("database").Cells(Cells.Rows.Count, 2).End(xlUp).Row + 1
i = 9
Do While Cells(i, 3) <> "" And i < 29
    n = n + 1
    ReDim Preserve vResult(1 To 8, 1 To n)
    vResult(1, n) = ActiveSheet.Range("g6") ' Date
    vResult(2, n) = ActiveSheet.Range("d6") ' Ref
    vResult(3, n) = ActiveSheet.Cells(i, 3) ' Code
    vResult(4, n) = ActiveSheet.Cells(i, 4) ' Description
    vResult(5, n) = ActiveSheet.Cells(i, 5) ' U/M
    vResult(6, n) = ActiveSheet.Cells(i, 6) ' Qty
    vResult(7, n) = ActiveSheet.Cells(i, 7) ' Price
    vResult(8, n) = "IN" ' Transaction
    i = i + 1

Loop

Dim wb As Workbook
'chage workbook name as  your workbook.name
Set wb = Workbooks("another.xlsx")
With wb.Sheets("Database")
    .Range("b" & Rows.Count).End(xlUp)(2).Resize(n, 8) = WorksheetFunction.Transpose(vResult)
End With
myWs.Range("b" & Rows.Count).End(xlUp)(2).Resize(n, 8) = WorksheetFunction.Transpose(vResult)

MsgBox "Saved Succesfully!"
ThisWorkbook.Save
Call RoundedRectangle2_Click
End Sub


问:
Implement async method synchronously
I have an interface which forces me to implement an (async) Task:

```<code>namespace Microsoft.Owin.Security.Infrastructure
{
    public interface IAuthenticationTokenProvider
    {
        ..
        Task CreateAsync(AuthenticationTokenCreateContext context);
        ..
    }
}
</code>```

I want to implement this method, but I'm not awaiting anything. Although I have to await something or return some task, otherwise my code does not compile.:

```<code>public class MyImplementation: IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        /// do something synchronously.

        await something here? ??
    }
}
</code>```

My question is: How would I implement this method without doing something asynchronously? I've have found a couple of solutions (await task.Yield(), or await Task.Run(() => {})), yet I can't fully understand what would be the correct implementation and why.

答:
My solution is to return a Task that represents the result of an already executed synchronous method. That way you maintain the semantics an async method with regard to when the exception gets surfaced, without the overhead of the async state machine. Funny enough, I actually did this for the same reason on this same interface

I have an extension method:

```<code>    public static Task AsCompletedTask<T>(this Action<T> func, T arg)
    {
        var tcs = new TaskCompletionSource<VoidResult>();
        try
        {
            func(arg);
            tcs.SetResult(voidResult);
        }
        catch (Exception e)
        {
            tcs.SetException(e);
        };

        return tcs.Task;
    }
</code>```

Which then I invoke via:

```<code>    public Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        return ((Action<AuthenticationTokenCreateContext>)Create).AsCompletedTask(context);
    }
</code>```

BTW, I hate that name. If anyone has a better suggestion, I'm all ears.

Title: Implement async method synchronously

Body:
I have an interface which forces me to implement an (async) Task:

namespace Microsoft.Owin.Security.Infrastructure
{
    public interface IAuthenticationTokenProvider
    {
        ..
        Task CreateAsync(AuthenticationTokenCreateContext context);
        ..
    }
}

I want to implement this method, but I'm not awaiting anything. Although I have to await something or return some task, otherwise my code does not compile.:

public class MyImplementation: IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        /// do something synchronously.

        await something here? ??
    }
}

My question is: How would I implement this method without doing something asynchronously? I've have found a couple of solutions (await task.Yield(), or await Task.Run(() => {})), yet I can't fully understand what would be the correct implementation and why.

Body:
My solution is to return a Task that represents the result of an already executed synchronous method. That way you maintain the semantics an async method with regard to when the exception gets surfaced, without the overhead of the async state machine. Funny enough, I actually did this for the same reason on this same interface

I have an extension method:

    public static Task AsCompletedTask<T>(this Action<T> func, T arg)
    {
        var tcs = new TaskCompletionSource<VoidResult>();
        try
        {
            func(arg);
            tcs.SetResult(voidResult);
        }
        catch (Exception e)
        {
            tcs.SetException(e);
        };

        return tcs.Task;
    }

Which then I invoke via:

    public Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        return ((Action<AuthenticationTokenCreateContext>)Create).AsCompletedTask(context);
    }

BTW, I hate that name. If anyone has a better suggestion, I'm all ears.


问:
complex orderby that links to another table
I have the following query to start with:

```<code>var query = from p in db.Products
                        from pc in p.NpProductCategories
                        where pc.CategoryId == categoryId
                        select p;
</code>```

I'm applying some more filtering on it and in the end I want to sort the results:

```<code>if (orderBy == ProductSortingEnum.Name)
                    query = query.OrderBy(x => x.Name);
                else
                    query = query.OrderBy(............);
</code>```

My big problem (coming from not knowing linq too good) is the ELSE here. How can I sort results by a column that is not in the current result set? I would like to somehow link to another linq query in the orderby. The sorting I'm trying to achive is to link to NpProductVariants query using the ProductId to match between NpProductVariant and Products
 and sort by the Price of the NpProductVariant

答:
I think you can hook your Join to your query as long as it is returning the same thing. So maybe something like (I'm not 100 % sure since I haven't tried it):

```<code>            query = from i1 in query
                 join i2 in query2 on i1.PropertyToJoin equals i2.PropertyToJoin
                 orderby i1.OrderProp1, i2.OrderProp2
                 select i1;
</code>```

But I think it might be a good idea to check the generated sql so it is still effective.

Body:
I have the following query to start with:

var query = from p in db.Products
                        from pc in p.NpProductCategories
                        where pc.CategoryId == categoryId
                        select p;

I'm applying some more filtering on it and in the end I want to sort the results:

if (orderBy == ProductSortingEnum.Name)
                    query = query.OrderBy(x => x.Name);
                else
                    query = query.OrderBy(............);

My big problem (coming from not knowing linq too good) is the ELSE here. How can I sort results by a column that is not in the current result set? I would like to somehow link to another linq query in the orderby. The sorting I'm trying to achive is to link to NpProductVariants query using the ProductId to match between NpProductVariant and Products
 and sort by the Price of the NpProductVariant

Body:
I think you can hook your Join to your query as long as it is returning the same thing. So maybe something like (I'm not 100 % sure since I haven't tried it):

            query = from i1 in query
                 join i2 in query2 on i1.PropertyToJoin equals i2.PropertyToJoin
                 orderby i1.OrderProp1, i2.OrderProp2
                 select i1;

But I think it might be a good idea to check the generated sql so it is still effective.


问:
boto3 says table is non-existent but I can query it in the AWS CLI
I'm trying to get a table description using boto3 and python using the following snippet:

```<code>import boto3

dynamodb = boto3.client('dynamodb', region_name='us-east-2', endpoint_url="http://localhost:8000")

response = dynamodb.describe_table(
    TableName='bars'
)

print(response)
</code>```

but I keep getting this error:

botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the DescribeTable operation: Cannot do operations on a non-existent table

But I'm able to query it in the AWS CLI when I run this command:

```<code>aws dynamodb describe-table --table-name bars
</code>```

Is something borked with my boto3 setup? Obviously my aws config file is fine because I can access the table using the cli.

答:
Remove the endpoint_url().

This is useful when connecting to DynamoDB Local but is not necessary when connecting to the 'live' Amazon DynamoDB service.

The AWS Command-Line Interface (CLI) will use the live service by default.

Body:
I'm trying to get a table description using boto3 and python using the following snippet:

import boto3

dynamodb = boto3.client('dynamodb', region_name='us-east-2', endpoint_url="http://localhost:8000")

response = dynamodb.describe_table(
    TableName='bars'
)

print(response)

but I keep getting this error:

botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the DescribeTable operation: Cannot do operations on a non-existent table

But I'm able to query it in the AWS CLI when I run this command:

aws dynamodb describe-table --table-name bars

Is something borked with my boto3 setup? Obviously my aws config file is fine because I can access the table using the cli.


问:
How to program Pascal's Triangle in Javascript - confusion re Arrays
I'm having a little trouble with my attempt at this problem. Code Below:

```<code>function pasc(n){
var result = [[1]];
for (var row = 1; row < n; row++){
    for (var col = 1; col <= row; col++){
        result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
    }
}
return result;
}
pasc(10)
for (var i = 0; i < result.length; i++){
    document.write(result[i]+"<br>");
}
</code>```

It seems the problem hinges on assigning values to an array using an expression like myArray[1][1] = "foo"

I'm confused about this because I can do this: var myArray = []; myArray[4] = "foo" which seems to suggest that an element can be created at an arbitrary position in a 1 dimensional array, but not with 2 dimensions.

Any help with clearing up my misconceptions appreciated.

答:
The Pascal's Triangle can be printed using recursion

Below is the code snippet that works recursively.

We have a recursive function pascalRecursive(n, a) that works up till the number of rows are printed. Each row is a element of the 2-D array ('a' in this case)

    var numRows = 10,
        triangle,
        start,
        stop;

    // N is the no. of rows/tiers
    // a is the 2-D array consisting of the row content

    function pascalRecursive(n, a) {

      if (n < 2) return a;

      var prevRow = a[a.length-1];
      var curRow = [1];

      for (var i = 1; i < prevRow.length; i++) {
        curRow[i] = prevRow[i] + prevRow[i-1];
      }
      curRow.push(1);
      a.push(curRow);

      return pascalRecursive(n-1, a); // Call the function recursively
    }

    var triangle = pascalRecursive(numRows, [[1]]);

    for(var i = 0; i < triangle.length; i++)
      console.log(triangle[i]+"\n");```

Body:
I'm having a little trouble with my attempt at this problem. Code Below:

function pasc(n){
var result = [[1]];
for (var row = 1; row < n; row++){
    for (var col = 1; col <= row; col++){
        result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
    }
}
return result;
}
pasc(10)
for (var i = 0; i < result.length; i++){
    document.write(result[i]+"
");
}

It seems the problem hinges on assigning values to an array using an expression like myArray[1][1] = "foo"

I'm confused about this because I can do this: var myArray = []; myArray[4] = "foo" which seems to suggest that an element can be created at an arbitrary position in a 1 dimensional array, but not with 2 dimensions.

Any help with clearing up my misconceptions appreciated.


问:
selinium and excel poi program
i have tried an automation program using selinium and java excel.  Unfortunately formulas to excel is not populating.  I tried using various methods but the intial selinium program is itself terminating with giving only one line in the excel output.  Can some one help. </p>

答:
Try this one</p>

```<code>    FileInputStream fis = new FileInputStream("/test/tes123.xls");
        Workbook wb = new HSSFWorkbook(fis);
        Sheet sheet = wb.getSheetAt(0);
        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

        // suppose your formula is in B2
        CellReference cellReference = new CellReference("B2");
        Row row = sheet.getRow(cellReference.getRow());
        Cell cell = row.getCell(cellReference.getCol());

        if (cell!=null) {
            switch (evaluator.evaluateFormulaCell(cell)) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.println(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.println(cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.println(cell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_BLANK:
                    break;
                case Cell.CELL_TYPE_ERROR:
                    System.out.println(cell.getErrorCellValue());
                    break;

                // CELL_TYPE_FORMULA will never occur
                case Cell.CELL_TYPE_FORMULA:
                    break;
            }
        }
</code>```

Title: selinium and excel poi program

Body:
Try this one

    FileInputStream fis = new FileInputStream("/test/tes123.xls");
        Workbook wb = new HSSFWorkbook(fis);
        Sheet sheet = wb.getSheetAt(0);
        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

        // suppose your formula is in B2
        CellReference cellReference = new CellReference("B2");
        Row row = sheet.getRow(cellReference.getRow());
        Cell cell = row.getCell(cellReference.getCol());

        if (cell!=null) {
            switch (evaluator.evaluateFormulaCell(cell)) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.println(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.println(cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.println(cell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_BLANK:
                    break;
                case Cell.CELL_TYPE_ERROR:
                    System.out.println(cell.getErrorCellValue());
                    break;

                // CELL_TYPE_FORMULA will never occur
                case Cell.CELL_TYPE_FORMULA:
                    break;
            }
        }


问:
Xamarin, Android BottomNavigationBar 3rd-party library goes down in special situation
I used this link to implement BottomNavigationBar in xamarin forms, I need to have the BottomNavigationBar in all of my pages, in this case I have a problem:

If I define MainPage in App as a non-NavigationPage, and all inner pages as NavigationPage, the bottomNavigation goes down and only it’s icons are visible!
(image1, image2)

If I define MainPage in App as a NavigationPage, and all inner pages as non-NavigationPage I'll not be able to see bottomNavigation in inner pages!
(image1, image2)

If I define both MainPage and inner pages as NavigationPage, I will have two toolbars in inner pages.

I prefer the first option if it's possible, but I cannot handle that!

答:
Since you want your tabs to be visible all the time I would put your MainPage as a Tabbed page and then use NavigationPages as the tabs. This will allow you to have navigation in the tabs. You then place all your content in ContentPages, don't place your xaml in NavigationPages.

Navigation Pages, TabbedPages and MasterDetailsPages should contain only ContentPages.

You can find a sample in the Xamarin website: https://developer.xamarin.com/samples/xamarin-forms/Navigation/TabbedPageWithNavigationPage/


问:
How do I download artifacts from GitHub during build?
I need as a part of the build process to download contents from external github repository. I set up repository under "services" but I can not find a task which will download artifacts from that repo.

I use TFS 2017 on prem. My repository is already set to Git repo and I need to have one of build steps to pull data from yet another Git repo. How do i do that?

答:
Build for the same github repo

If you want to download artifacts to your local path, you only need to use copy files task in your build definition.

Get source: select Github and use github token to authoize. If you want CI build, set in Triggers Tab.

Copy Files: set $(Build.SourcesDirectory) as Source Folder, specify the file you want to download in Contents, set a local path as Target Folder.

If you want to download/publish artifacts to VSTS server or share folder, you can use copy files task and publish build artifacts task in you build defnition.

Get source: select from github.

Copy Files: set $(Build.SourcesDirectory) as Source Folder, specify the file you want to download in Contents, set $(build.artifactstagingdirectory) as Target Folder.

Publish Build Artifacts: set $(build.artifactstagingdirectory) as Path to Publish, select the type you want to publish.

The way to connect github repo for TFS build:

In TFS build definition -> Repository Tab -> select External Git -> click Manage to add an External Git Service Endpoint -> input your github repo URL, username and password -> OK -> Then select the endpoint as connection.

Build for a git repo, and also need to download code from another github repo

You can use Command Line task to clone the github repo to your $(Build.SourcesDirectory) folder.

Settings of command Line task:

Tool: git

Arguments: clone https://github.com/username/repo

Now the code of the github repo is cloned in $(Build.SourcesDirectory)\repo.


答:
I don't think you even need a regex, assuming the OCC option string has a fixed format.  Instead, you can try just using substring() to extract the various components.

var occ = 'SPX   141122P00019500';
var symbol = occ.substring(0, 3);
var year = parseInt(occ.substring(6, 8)) + 2000;
var month = occ.substring(8, 10);
var day = occ.substring(10, 12);
var date = month + '/' + day + '/' + year;
var type = occ.substring(12, 13) == 'P' ? 'put' : 'call';
var price = parseFloat(occ.substring(13, 21)) / 1000.0;

var output = 'a ' + type + ' on ' + symbol + ', expiring on ' + date +
             ', with a strike price of $' + price.toFixed(2); + '.';
console.log(output);```

I would expect using substring to build your output string would generally perform better than using a regex.

Title: How can I use regex to parse an OCC Option Symbol?

Body:
The OCC option symbol consists of 4 parts:

Root symbol of the underlying stock or ETF, padded with spaces to 6 characters

Expiration date, 6 digits in the format yymmdd

Option type, either P or C, for put or call

Strike price, as the price x 1000, front padded with 0s to 8 digits

As an example SPX   141122P00019500 means a put on SPX, expiring on 11/22/2014, with a strike price of $19.50.

Is it possible to use regex to parse this out automatically? I'm using JavaScript

Body:
I don't think you even need a regex, assuming the OCC option string has a fixed format.  Instead, you can try just using substring() to extract the various components.

var occ = 'SPX   141122P00019500';
var symbol = occ.substring(0, 3);
var year = parseInt(occ.substring(6, 8)) + 2000;
var month = occ.substring(8, 10);
var day = occ.substring(10, 12);
var date = month + '/' + day + '/' + year;
var type = occ.substring(12, 13) == 'P' ? 'put' : 'call';
var price = parseFloat(occ.substring(13, 21)) / 1000.0;

var output = 'a ' + type + ' on ' + symbol + ', expiring on ' + date +
             ', with a strike price of $' + price.toFixed(2); + '.';
console.log(output);

I would expect using substring to build your output string would generally perform better than using a regex.