问:
Error while trying to send mail
Getting error:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

The code I used is given below:

```<code>using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(email);
                mail.To.Add(email);
                mail.Subject = "Test";
                mail.Body = html;
                mail.IsBodyHtml = true;

                using (SmtpClient smtp = new SmtpClient(host, int.Parse(port)))
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential(email, password);
                    smtp.EnableSsl = true;
                    smtp.Send(mail);
                }
            }
</code>```

答: Got it worked.....Issue was with the port number. Tried port number 25 and it worked....</p>

Title: Error while trying to send mail

Body:
Getting error:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

The code I used is given below:

using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(email);
                mail.To.Add(email);
                mail.Subject = "Test";
                mail.Body = html;
                mail.IsBodyHtml = true;

                using (SmtpClient smtp = new SmtpClient(host, int.Parse(port)))
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential(email, password);
                    smtp.EnableSsl = true;
                    smtp.Send(mail);
                }
            }


来源: stackexchange

问:
How to restrict user to entering only "Y" or "N" in a single column
I want to restrict user entry in column A and column D.

In column A, the user should enter the values as R00yyyyyy where yyyyyy is a number between 000000 and 999999.

In column D they should only enter y or n.

My code below doesn't seem to work properly. The column A part works fine, just having issues with column D.

Can anyone suggest a way to enable restricting the entry in column D?

```<code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim rngCell As Range

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell In Target.Cells
    rngCell = UCase(rngCell)
    If rngCell.Characters.Count > 9 Then
    MsgBox ("Student number too long")
    rngCell.Clear
    End If
   If Not IsEmpty(rngCell.Value) Then
    Dim s As String
    Dim s1 As String
    Dim y As String
    Dim y1 As String
    s = CStr(rngCell.Value)
    s1 = Left(s, 3)
    y = CStr(rngCell.Value)
    y1 = Right(y, 6)
    If s1 <> "R00" Or Not IsNumeric(y1) Then
    MsgBox ("Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999")
    rngCell.Clear
    End If
   Else
   End If
Next
Application.EnableEvents = True

Dim rngCell2 As Range

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell2 In Target.Cells
    rngCell2 = UCase(rngCell2)
    Dim b As String
    b = CStr(rngCell2.Value)
    If b <> "y" Or b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
    End If
Next
Application.EnableEvents = True

End Sub
</code>```

答:
Assuming the rest of your code is correct, you need to change your logical test from Or to And</p>

```<code>If b <> "y" And b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
End If
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to restrict user entry in column A and column D.

In column A, the user should enter the values as R00yyyyyy where yyyyyy is a number between 000000 and 999999.

In column D they should only enter y or n.

My code below doesn't seem to work properly. The column A part works fine, just having issues with column D.

Can anyone suggest a way to enable restricting the entry in column D?

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim rngCell As Range

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell In Target.Cells
    rngCell = UCase(rngCell)
    If rngCell.Characters.Count > 9 Then
    MsgBox ("Student number too long")
    rngCell.Clear
    End If
   If Not IsEmpty(rngCell.Value) Then
    Dim s As String
    Dim s1 As String
    Dim y As String
    Dim y1 As String
    s = CStr(rngCell.Value)
    s1 = Left(s, 3)
    y = CStr(rngCell.Value)
    y1 = Right(y, 6)
    If s1 <> "R00" Or Not IsNumeric(y1) Then
    MsgBox ("Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999")
    rngCell.Clear
    End If
   Else
   End If
Next
Application.EnableEvents = True

Dim rngCell2 As Range

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell2 In Target.Cells
    rngCell2 = UCase(rngCell2)
    Dim b As String
    b = CStr(rngCell2.Value)
    If b <> "y" Or b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
    End If
Next
Application.EnableEvents = True

End Sub

Body:
Assuming the rest of your code is correct, you need to change your logical test from Or to And

If b <> "y" And b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
End If


问:
Is installing NodeJS packages locally equivalent to Python's virtualenv?
I've been using Python for a while and I've learned we should always use a virtual env for each project where we pip install <name> the packages as needed, etc

I'm new to JS but would downloading packages using npm install <name> without the -g option mean it will only download it in the specific project directory, similarly to how Python's virtual env is keeping the pip packages separate? or is there also some sort of virtual env that needs to be created?

Sorry if I'm misunderstanding anything here... just want to make sure that installing packages using npm install isn't going to mess w/ anything globally or something!

答:
Node installs

local: npm install <pkg>

global: npm install -g <pkg>

Python installs

local: . <envName>/bin/activate then pip install <pkg>

global: pip install <pkg>

Node usage

local: npm start (w/ path to binary specified in package.json e.g. "start":"./node_modules/.bin/<pkg>")

global: <pkg> <cmd>

Python usage

local: . <envName>/bin/activate then <pkg> <cmd>

global: <pkg> <cmd>

main takeaway: once you activate virtualenv you don't have to worry about package commands slipping into global scope

NVM: way to specifiy Node version using .nvmrc file in project root


问:
How to set a variable as a class method and not as a static method
I'm trying to grasp some comments that were made to me by my professor on a programming assignment.  The assignment was to write a program that calls upon another class.  This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period.
Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments.  I received a 90% on my program for my grade.

The following comments were made about my assignment:

"Your setInterest method was to be a class method not an instance
method. Also, your call should have been

```<code>IWUnit4Ch13Investor.setInterest(rate);"
</code>```

I'm not exactly following what I did wrong or how I can fix it.  Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?

```<code>// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;

// main class
public class IWUnit4Ch13 {

    public static void main(String[] args) {

        // Declares local variables
        double rate, INTEREST_RATE;

        // Instantiate investor1 & investor2 objects using a two parameter constructor
        IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
        IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
        Scanner input = new Scanner(System.in);

        // Receives the APR by the user
        System.out.print("Please enter the APR in the form of .05 for 5%: ");
        rate = input.nextDouble();

        // Moves the decimal 2 places to the left (used later)
        INTEREST_RATE = rate * 100;

        // Sets the interest rate using a class variable
        investor1.setInterestRate(rate);
        investor2.setInterestRate(rate);

        // Prints the header for the table
        System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
        System.out.println("Month Account #   Balance Account #   Balance");
        System.out.println("----- ---------   ------- ---------   -------");

        // Loop that prints each month on the table
        // Uses class variables to add interest and get balance for display
        for (int i = 1; i <= 15; i++) {
            investor1.addInterest();
            investor2.addInterest();
            System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
            }

        // Prints the calculated interest earned by both investors
        System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n");
        System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n\n");

    } // end of internal main
} // end of main class
</code>```

```<code>// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {

    // All variables are declared private
    private static double interestRate; // class variable
    private final int ACCOUNT_NUMBER;   // declare constant ACCOUNT_NUMBER
    private double balance;             // instance variable called balance
    private double initialBalance;      // to hold the initial balance
    private double interest;            // to count how much interest was made
    private double INTEREST_RATE;       // used to convert the float interestRate to int

    // Two parameter constructor to initialize account number and balance
    public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
        this.initialBalance = initialBalance;
        this.ACCOUNT_NUMBER = acctNum;
        balance = initialBalance;
    }

    // To return the balance to parent
    public double getBalance() {
        return balance;
    }

    // Class method to set the annual interest rate
    public void setInterestRate(double rate) {
        interestRate = rate;
    }

    // Method to add interest based on balance * interestRate / 12
    public void addInterest() {
        balance += balance * interestRate/12.0;
    }

    // To get account number in parent
    public int getACCOUNT_NUMBER() {
        return ACCOUNT_NUMBER;
    }

    // Used to get the amount of interested earned during 15 months
    public double getInterest() {
        interest = balance - initialBalance;
        return interest;
    }
} // end of class
</code>```

Thank you all in advance for your help.

答:
Terms

First of, please don't confuse terms. A variable is different to a method:

```<code>// A class
public class Dog {
    // Member variable
    private String name;

    // Method
    public void bark() {
        // Variable
        String textToBark = "Wuff";
        // Call to a method
        System.out.println(textToBark);
    }
}
</code>```

Elsewhere:

```<code>// Creating a new instance of class "Dog"
// and saving a reference to it inside a variable
Dog bello = new Dog("Bello");
</code>```

Explanation

Your teacher said he wants the setInterest to be a class method instead of an instance method. What he wants to say with that is that it should be declared static and thus not belonging to instances of the class but to the class itself. Here is more on what static means for methods: Java: when to use static methods

Solution

So the method should look like this:

```<code>// Method to set the annual interest rate
public static void setInterestRate(double rate) {
    IWUnit4Ch13Investor.interestRate = rate;
}
</code>```

Where interestRate then also needs to be declared static (which you already did):

```<code>// To count how much interest was made
private static double interestRate;
</code>```

To indicate the access of static variables one should add the class name before, so instead write it like this:

```<code>// Method to add interest based on balance * interestRate / 12
public void addInterest() {
    balance += balance * IWUnit4Ch13Investor.interestRate / 12.0;
}
</code>```

The same holds for calling static methods, instead of

```<code>investor1.setInterestRate(rate);
investor2.setInterestRate(rate);
</code>```

do this

```<code>IWUnit4Ch13Investor.setInterestRate(rate);
</code>```

Due to the nature of static you then also need to set this only once since static variables are shared by all instances of that class.

Body:
I'm trying to grasp some comments that were made to me by my professor on a programming assignment.  The assignment was to write a program that calls upon another class.  This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period.
Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments.  I received a 90% on my program for my grade.

The following comments were made about my assignment:

"Your setInterest method was to be a class method not an instance
method. Also, your call should have been

IWUnit4Ch13Investor.setInterest(rate);"

I'm not exactly following what I did wrong or how I can fix it.  Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?

// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;

// main class
public class IWUnit4Ch13 {

    public static void main(String[] args) {

        // Declares local variables
        double rate, INTEREST_RATE;

        // Instantiate investor1 & investor2 objects using a two parameter constructor
        IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
        IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
        Scanner input = new Scanner(System.in);

        // Receives the APR by the user
        System.out.print("Please enter the APR in the form of .05 for 5%: ");
        rate = input.nextDouble();

        // Moves the decimal 2 places to the left (used later)
        INTEREST_RATE = rate * 100;

        // Sets the interest rate using a class variable
        investor1.setInterestRate(rate);
        investor2.setInterestRate(rate);

        // Prints the header for the table
        System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
        System.out.println("Month Account #   Balance Account #   Balance");
        System.out.println("----- ---------   ------- ---------   -------");

        // Loop that prints each month on the table
        // Uses class variables to add interest and get balance for display
        for (int i = 1; i <= 15; i++) {
            investor1.addInterest();
            investor2.addInterest();
            System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
            }

        // Prints the calculated interest earned by both investors
        System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n");
        System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n\n");

    } // end of internal main
} // end of main class

// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {

    // All variables are declared private
    private static double interestRate; // class variable
    private final int ACCOUNT_NUMBER;   // declare constant ACCOUNT_NUMBER
    private double balance;             // instance variable called balance
    private double initialBalance;      // to hold the initial balance
    private double interest;            // to count how much interest was made
    private double INTEREST_RATE;       // used to convert the float interestRate to int

    // Two parameter constructor to initialize account number and balance
    public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
        this.initialBalance = initialBalance;
        this.ACCOUNT_NUMBER = acctNum;
        balance = initialBalance;
    }

    // To return the balance to parent
    public double getBalance() {
        return balance;
    }

    // Class method to set the annual interest rate
    public void setInterestRate(double rate) {
        interestRate = rate;
    }

    // Method to add interest based on balance * interestRate / 12
    public void addInterest() {
        balance += balance * interestRate/12.0;
    }

    // To get account number in parent
    public int getACCOUNT_NUMBER() {
        return ACCOUNT_NUMBER;
    }

    // Used to get the amount of interested earned during 15 months
    public double getInterest() {
        interest = balance - initialBalance;
        return interest;
    }
} // end of class

Thank you all in advance for your help.

Body:
Terms

First of, please don't confuse terms. A variable is different to a method:

// A class
public class Dog {
    // Member variable
    private String name;

    // Method
    public void bark() {
        // Variable
        String textToBark = "Wuff";
        // Call to a method
        System.out.println(textToBark);
    }
}

Elsewhere:

// Creating a new instance of class "Dog"
// and saving a reference to it inside a variable
Dog bello = new Dog("Bello");

Explanation

Your teacher said he wants the setInterest to be a class method instead of an instance method. What he wants to say with that is that it should be declared static and thus not belonging to instances of the class but to the class itself. Here is more on what static means for methods: Java: when to use static methods

Solution

So the method should look like this:

// Method to set the annual interest rate
public static void setInterestRate(double rate) {
    IWUnit4Ch13Investor.interestRate = rate;
}

Where interestRate then also needs to be declared static (which you already did):

// To count how much interest was made
private static double interestRate;

To indicate the access of static variables one should add the class name before, so instead write it like this:

// Method to add interest based on balance * interestRate / 12
public void addInterest() {
    balance += balance * IWUnit4Ch13Investor.interestRate / 12.0;
}

The same holds for calling static methods, instead of

investor1.setInterestRate(rate);
investor2.setInterestRate(rate);

do this

IWUnit4Ch13Investor.setInterestRate(rate);

Due to the nature of static you then also need to set this only once since static variables are shared by all instances of that class.


问:
How to handle sand in unity3d
I have Crane Animation which will pick the sand (through its jaw) and drop it to the truck. I tried to find the way to handle sand in Unity but unfortunately found nothing.
So I made custom sand object (low poly) in max and bring them it Unity3d and apply box collider and rigidbody to them. But as I play the game, my FPS drops and player hardly moving. Profiler tell that physics is so heavy (and it should be as too many colliders with too many rigidbodies). I tried to optimize physics by collision matrix and layer but it didn't improve the performance.

Is this right approach to handle sand interaction with a crane?

答:
You could have the sand be a terrain and use the terrain.SetHeights() Method to lower a specific area of the terrain where you used the crane.

It would look like those classic terrain editing tools when you lower or heigher terrain.

Then wherever you "drop" off the sand you could heigher the area a bit.

I found this thread with some code examples to help you get going:
https://forum.unity.com/threads/edit-terrain-in-real-time.98410/

```<code>private void raiseTerrain(Vector3 point)
{
    int terX =(int)((point.x / myTerrain.terrainData.size.x) * xResolution);
    int terZ =(int)((point.z / myTerrain.terrainData.size.z) * zResolution);
    float[,] height = myTerrain.terrainData.GetHeights(terX - 4,terZ - 4,9,9);  //new float[1,1];

    for(int tempY = 0; tempY < 9; tempY++)
        for(int tempX = 0; tempX < 9; tempX++)
        {
            float dist_to_target = Mathf.Abs((float)tempY - 4f) + Mathf.Abs ((float)tempX - 4f);
            float maxDist = 8f;
            float proportion = dist_to_target / maxDist;

            height[tempX,tempY] += 0.001f * (1f - proportion);
            heights[terX - 4 + tempX,terZ - 4 + tempY] += 0.01f * (1f - proportion);
        }

    myTerrain.terrainData.SetHeights(terX - 4, terZ - 4, height);
}
</code>```

Title: How to handle sand in unity3d

Body:
You could have the sand be a terrain and use the terrain.SetHeights() Method to lower a specific area of the terrain where you used the crane.

It would look like those classic terrain editing tools when you lower or heigher terrain.

Then wherever you "drop" off the sand you could heigher the area a bit.

I found this thread with some code examples to help you get going:
https://forum.unity.com/threads/edit-terrain-in-real-time.98410/

private void raiseTerrain(Vector3 point)
{
    int terX =(int)((point.x / myTerrain.terrainData.size.x) * xResolution);
    int terZ =(int)((point.z / myTerrain.terrainData.size.z) * zResolution);
    float[,] height = myTerrain.terrainData.GetHeights(terX - 4,terZ - 4,9,9);  //new float[1,1];

    for(int tempY = 0; tempY < 9; tempY++)
        for(int tempX = 0; tempX < 9; tempX++)
        {
            float dist_to_target = Mathf.Abs((float)tempY - 4f) + Mathf.Abs ((float)tempX - 4f);
            float maxDist = 8f;
            float proportion = dist_to_target / maxDist;

            height[tempX,tempY] += 0.001f * (1f - proportion);
            heights[terX - 4 + tempX,terZ - 4 + tempY] += 0.01f * (1f - proportion);
        }

    myTerrain.terrainData.SetHeights(terX - 4, terZ - 4, height);
}


问:
How can I able to display latitude and longitude obtained by json data on google map by using modal for each of the search results in vue js?
I have the following search results coming as the json data. For each search result there is lat and lon. So, for each search result when I click on view map, a modal will pop up and shows the marker on the google map.. but using the following code i am not getting the same..

My json data is

```<code>{"status": true, "data": [{"pid": 1, "bussinessName": "ld", "lat": 9.5273308, "lon": 76.8228674, "contactName": "bin"}, {"pid": 2, "bussinessName": "lod", "lat": 9.523308, "lon": 76.8228674, "contactName": "son"},{"pid": 3, "bussinessName": "rd", "lat": 9.5273308, "lon": 76.822867, "contactName": "in"}]}
</code>```

My vue js code is

```<code> <script>
    searchContent = new Vue({
            el: "#searchContent",
            data: {
              vector: {}
            }
          });
    categories = new Vue({
        el: '#categories',
        data: {
            articles: [],
            services: [],
            category: 0,
            subcategory: 0,
            content: false
        },
         mounted() {
        var vm = this;

        $.ajax({
            url: "/get_all_category/",
            method: "GET",
            dataType: "JSON",
            success: function(e) {
                    console.log(e);

                 vm.articles = e;
                console.log(vm);

            },
        });
    },
              methods: {
              prefetch: function() {
                var filter = {};
                filter['category'] = this.category;
                if (this.content !== false)
                  this.content.abort()
                this.content = $.ajax({
                  'url': 'https:/filter/',
                  data: filter,
                  dataType: "JSON",
                  type: "POST",
                  success: function(e) {
                     window.searchContent.vector = e.data;
                    console.log(e);

                    var options = {
     zoom: 8,
     center: new google.maps.LatLng(e.data.lat , e.data.lon), // Centered
     mapTypeId: google.maps.MapTypeId.ROADMAP,
     mapTypeControl: false
     };

     // Init map
     var map = new google.maps.Map(document.getElementById('mapName'), options);
     //use code
    var i=0;

     // Init markers
     var marker = new google.maps.Marker({
     position: new google.maps.LatLng(e.data.lat , e.data.lon),
     map: map,
     title: 'Click Me ' + i,
     });

     // Process multiple info windows
     (function(marker, i) {
     // add click event
     google.maps.event.addListener(marker, 'click', function() {
     infowindow = new google.maps.InfoWindow({
     content: e.data.lat
     });
     infowindow.open(map, marker);
     });
     })(marker, i);
                  }
                })
              }
            }

    })
    </script>
</code>```

My html code to display the same is

```<code> <div id="searchContent" >
    <div v-for="row in vector" >
    <h6>{{row.bussinessName}}</h6>
<div>
<a data-toggle="modal" data-target="#myModal1">View Map</a></div>
    </div>
    </div>

<div id="myModal1" class="modal fade" role="dialog">
  <div class="modal-dialog">
      <!-- Modal content-->
      <div id="mapName" style="width:667px; height: 370px" />
    <!-- Replace the value of the key parameter with your own API key. -->
    </div>
      </div>
    </div>
</code>```

So, when I click on the view map I need to display the marker corresponding to the search result. can anyone please help me to solve the problem?

答:
Warning: this isn't a solution - following code only demostrates how easy is to use the ready-made web components. I just think, that this information has it's value and is related to this issue, because it can greatly simplify your code / solution / life :)

Look at this example. It's using extraneous, ready-made Polymer based custom web component from webcomponents.org. As you can see, these components fully interoperates with Vue. You can not only use them, you also have full control about their properties. And best of all, you can listen to their custom events, just like in other Vue components...

So, this is maybe the easiest way to achieve what you need. Just wrap my-map with modal and set the properties to the correct values... And of course, take a look to provided link for documentation for this google-map component.

Vue.component('my-map', {
  template: '#my-map',
  props: ['lat', 'long'],
  data () {
    return {
      latitude: '',
      longitude: ''
    }
  },
  methods: {
    setCoords (e) {
      if (e.type === 'latitude-changed')
        this.latitude = e.detail.value
      if (e.type === 'longitude-changed')
        this.longitude = e.detail.value
    }
  }
})

new Vue({
  el: '#app'
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>google-map {
  height: 186px;
}</code>```

<base href="https://raw-dot-custom-elements.appspot.com/GoogleWebComponents/google-map/v2.0.2/google-map/">
<link rel="import" href="google-map.html">

  <my-map lat="37.78" long="-122.4"></my-map>

<template id="my-map">

    Marker coords: lat {{ latitude }} / long {{ longitude }}
    <google-map fit-to-marker api-key="AIzaSyD3E1D9b-Z7ekrT3tbhl_dy8DCXuIuDDRc">
      <google-map-marker
        :latitude="lat"
        :longitude="long"
        draggable="true"
        slot="markers"
        title="Your location"
        @latitude-changed="setCoords"
        @longitude-changed="setCoords"
      >
      </google-map-marker>
    </google-map>

</template>

```

Honestly ... I think this combination of Vue, and Polymer based custom web components is pretty awesome. Now one can achieve unbelievable results with beautiful, declarative syntax. Did you noticed, that in this example is no additional javascript? Yes, modern browsers works with these custom components with no additional overhead. And for older browsers there is a polyfill...

Body:
I have the following search results coming as the json data. For each search result there is lat and lon. So, for each search result when I click on view map, a modal will pop up and shows the marker on the google map.. but using the following code i am not getting the same..

My json data is

{"status": true, "data": [{"pid": 1, "bussinessName": "ld", "lat": 9.5273308, "lon": 76.8228674, "contactName": "bin"}, {"pid": 2, "bussinessName": "lod", "lat": 9.523308, "lon": 76.8228674, "contactName": "son"},{"pid": 3, "bussinessName": "rd", "lat": 9.5273308, "lon": 76.822867, "contactName": "in"}]}

My vue js code is

My html code to display the same is

{{row.bussinessName}}

View Map

So, when I click on the view map I need to display the marker corresponding to the search result. can anyone please help me to solve the problem?

Body:
Warning: this isn't a solution - following code only demostrates how easy is to use the ready-made web components. I just think, that this information has it's value and is related to this issue, because it can greatly simplify your code / solution / life :)

Look at this example. It's using extraneous, ready-made Polymer based custom web component from webcomponents.org. As you can see, these components fully interoperates with Vue. You can not only use them, you also have full control about their properties. And best of all, you can listen to their custom events, just like in other Vue components...

So, this is maybe the easiest way to achieve what you need. Just wrap my-map with modal and set the properties to the correct values... And of course, take a look to provided link for documentation for this google-map component.

Vue.component('my-map', {
  template: '#my-map',
  props: ['lat', 'long'],
  data () {
    return {
      latitude: '',
      longitude: ''
    }
  },
  methods: {
    setCoords (e) {
      if (e.type === 'latitude-changed')
        this.latitude = e.detail.value
      if (e.type === 'longitude-changed')
        this.longitude = e.detail.value
    }
  }
})

new Vue({
  el: '#app'
})

google-map {
  height: 186px;
}

<base href="https://raw-dot-custom-elements.appspot.com/GoogleWebComponents/google-map/v2.0.2/google-map/">
<link rel="import" href="google-map.html">

<div id="app">
  <my-map lat="37.78" long="-122.4"></my-map>
</div>

<template id="my-map">
  <div>
    Marker coords: lat {{ latitude }} / long {{ longitude }}
    <google-map fit-to-marker api-key="AIzaSyD3E1D9b-Z7ekrT3tbhl_dy8DCXuIuDDRc">
      <google-map-marker
        :latitude="lat"
        :longitude="long"
        draggable="true"
        slot="markers"
        title="Your location"
        @latitude-changed="setCoords"
        @longitude-changed="setCoords"
      >
      </google-map-marker>
    </google-map>
  </div>
</template>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>

Honestly ... I think this combination of Vue, and Polymer based custom web components is pretty awesome. Now one can achieve unbelievable results with beautiful, declarative syntax. Did you noticed, that in this example is no additional javascript? Yes, modern browsers works with these custom components with no additional overhead. And for older browsers there is a polyfill...


问:
Java application crashing and producing an error log file
I have a java application that uses ICEpdf to render pdf documents.  Recently, java has been crashing and producing this error log:

```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x76dca05b, pid=2224, tid=1072
#
# JRE version: 6.0_23-b05
# Java VM: Java HotSpot(TM) Client VM (19.0-b09 mixed mode windows-x86 )
# Problematic frame:
# C  [msvcrt.dll+0xa05b]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x6148c000):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=1072, stack(0x61930000,0x61980000)]

siginfo: ExceptionCode=0xc0000005, writing address 0x00000000

Registers:
EAX=0x00000000, EBX=0x680b0020, ECX=0x0000333b, EDX=0x00000000
ESP=0x6197ef5c, EBP=0x6197ef64, ESI=0x680b0020, EDI=0x00000000
EIP=0x76dca05b, EFLAGS=0x00010212

Register to memory mapping:

EAX=0x00000000
0x00000000 is pointing to unknown location

EBX=0x680b0020
0x680b0020 is pointing to unknown location

ECX=0x0000333b
0x0000333b is pointing to unknown location

EDX=0x00000000
0x00000000 is pointing to unknown location

ESP=0x6197ef5c
0x6197ef5c is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

EBP=0x6197ef64
0x6197ef64 is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

ESI=0x680b0020
0x680b0020 is pointing to unknown location

EDI=0x00000000
0x00000000 is pointing to unknown location

Top of Stack: (sp=0x6197ef5c)
0x6197ef5c:   00199d80 00000000 6197ef94 76dca00b
0x6197ef6c:   00000000 680b0020 00199d80 6197ef84
0x6197ef7c:   00000020 c4a8eee9 680b0020 00000000
0x6197ef8c:   61a76ae8 08000030 6197efb4 704f7a70
0x6197ef9c:   00000000 680b0020 00199da0 0a435d04
0x6197efac:   08000030 61a76ae8 6197efcc 704dc9ab
0x6197efbc:   08000030 61a76ae8 08000000 2c827bd4
0x6197efcc:   6197efe8 704e81b2 00000145 08000028

Instructions: (pc=0x76dca05b)
0x76dca04b:   06 66 0f 6f 4e 10 66 0f 6f 56 20 66 0f 6f 5e 30
0x76dca05b:   66 0f 7f 07 66 0f 7f 4f 10 66 0f 7f 57 20 66 0f

Stack: [0x61930000,0x61980000],  sp=0x6197ef5c,  free space=315k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [msvcrt.dll+0xa05b]
C  [msvcrt.dll+0xa00b]
C  [prl_gldd.dll+0x27a70]
C  [prl_gldd.dll+0xc9ab]
C  [prl_gldd.dll+0x181b2]
C  [jogl.dll+0xf286]
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D1(IIIIIIIILjava/lang/Object;I)V+0
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D(IIIIIIIILjava/nio/Buffer;)V+85
j      com.sun.opengl.util.texture.Texture.updateSubImageImpl(Lcom/sun/opengl/util/texture/TextureData;IIIIIIII)V+658
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;I)V+1001
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;)V+3
j  com.sun.opengl.util.texture.Texture.<init>(Lcom/sun/opengl/util/texture/TextureData;)V+18
j  com.sun.opengl.util.texture.TextureIO.newTexture(Lcom/sun/opengl/util/texture/TextureData;)Lcom/sun/opengl/util/texture/Texture;+19
j  gov.nasa.worldwind.render.BasicWWTexture.initializeTexture(Lgov/nasa/worldwind/render/DrawContext;Ljava/lang/Object;)Lcom/sun/opengl/util/texture/Texture;+203
j  gov.nasa.worldwind.render.BasicWWTexture.bind(Lgov/nasa/worldwind/render/DrawContext;)Z+42
j  gov.nasa.worldwind.render.AbstractAnnotation.doDrawBackgroundTexture(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;Lgov/nasa/worldwind/render/WWTexture;)V+36
j  gov.nasa.worldwind.render.AbstractAnnotation.drawBackgroundImage(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.drawContent(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+19
j  gov.nasa.worldwind.render.AbstractAnnotation.doDraw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.draw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+47
j  gov.nasa.worldwind.render.AbstractAnnotation.drawTopLevelAnnotation(Lgov/nasa/worldwind/render/DrawContext;IIIIDDLgov/nasa/worldwind/geom/Position;)V+68
j  gov.nasa.worldwind.render.GlobeAnnotation.doRenderNow(Lgov/nasa/worldwind/render/DrawContext;)V+139
j  gov.nasa.worldwind.render.AbstractAnnotation.renderNow(Lgov/nasa/worldwind/render/DrawContext;)V+56
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.doRender(Lgov/nasa/worldwind/render/DrawContext;Lgov/nasa/worldwind/render/BasicAnnotationRenderer$OrderedAnnotation;)V+22
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.render(Lgov/nasa/worldwind/render/DrawContext;)V+20
J  gov.nasa.worldwind.AbstractSceneController.draw(Lgov/nasa/worldwind/render/DrawContext;)V
j  gov.nasa.worldwind.AbstractSceneController.repaint()I+49
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.doDisplay()I+4
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.display(Ljavax/media/opengl/GLAutoDrawable;)V+111
j  com.sun.opengl.impl.GLDrawableHelper.display(Ljavax/media/opengl/GLAutoDrawable;)V+29
j  javax.media.opengl.GLCanvas$DisplayAction.run()V+80
j  com.sun.opengl.impl.GLDrawableHelper.invokeGL(Ljavax/media/opengl/GLDrawable;Ljavax/media/opengl/GLContext;Ljava/lang/Runnable;Ljava/lang/Runnable;)V+418
j  javax.media.opengl.GLCanvas.maybeDoSingleThreadedWorkaround(Ljava/lang/Runnable;Ljava/lang/Runnable;)V+36
j  javax.media.opengl.GLCanvas.display()V+9
j  javax.media.opengl.GLCanvas.paint(Ljava/awt/Graphics;)V+125
j  javax.media.opengl.GLCanvas.update(Ljava/awt/Graphics;)V+2
j  sun.awt.RepaintArea.updateComponent(Ljava/awt/Component;Ljava/awt/Graphics;)V+6
j  sun.awt.RepaintArea.paint(Ljava/lang/Object;Z)V+263
j  sun.awt.windows.WComponentPeer.handleEvent(Ljava/awt/AWTEvent;)V+107
j  java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V+853
j  java.awt.Component.dispatchEvent(Ljava/awt/AWTEvent;)V+2
j  java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V+46
j  java.awt.EventDispatchThread.pumpOneEventForFilters(I)Z+204
j  java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V+30
j  java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11
j  java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4
j  java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3
j  java.awt.EventDispatchThread.run()V+9
v  ~StubRoutines::call_stub
V  [jvm.dll+0xf33c9]
V  [jvm.dll+0x188a91]
V  [jvm.dll+0xf3587]
V  [jvm.dll+0xf35eb]
V  [jvm.dll+0x11e780]
V  [jvm.dll+0x1ea6c4]
V  [jvm.dll+0x18843c]
C  [msvcr71.dll+0x9565]
C  [kernel32.dll+0x51194]
C  [ntdll.dll+0x5b495]
C  [ntdll.dll+0x5b468]
</code>```

I have never seen this before so I have no idea how to figure out what the problem is.

答:
The .23 release has given us some of those too.  Report it as requested

If you would like to submit a bug
  report, please visit:
     http://java.sun.com/webapps/bugreport/crash.jsp

and downgrade to an earlier version.  I believe at least .20 didn't have the problem.

ContentLicense: CC BY-SA 2.5

Body:
I have a java application that uses ICEpdf to render pdf documents.  Recently, java has been crashing and producing this error log:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x76dca05b, pid=2224, tid=1072
#
# JRE version: 6.0_23-b05
# Java VM: Java HotSpot(TM) Client VM (19.0-b09 mixed mode windows-x86 )
# Problematic frame:
# C  [msvcrt.dll+0xa05b]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x6148c000):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=1072, stack(0x61930000,0x61980000)]

siginfo: ExceptionCode=0xc0000005, writing address 0x00000000

Registers:
EAX=0x00000000, EBX=0x680b0020, ECX=0x0000333b, EDX=0x00000000
ESP=0x6197ef5c, EBP=0x6197ef64, ESI=0x680b0020, EDI=0x00000000
EIP=0x76dca05b, EFLAGS=0x00010212

Register to memory mapping:

EAX=0x00000000
0x00000000 is pointing to unknown location

EBX=0x680b0020
0x680b0020 is pointing to unknown location

ECX=0x0000333b
0x0000333b is pointing to unknown location

EDX=0x00000000
0x00000000 is pointing to unknown location

ESP=0x6197ef5c
0x6197ef5c is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

EBP=0x6197ef64
0x6197ef64 is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

ESI=0x680b0020
0x680b0020 is pointing to unknown location

EDI=0x00000000
0x00000000 is pointing to unknown location

Top of Stack: (sp=0x6197ef5c)
0x6197ef5c:   00199d80 00000000 6197ef94 76dca00b
0x6197ef6c:   00000000 680b0020 00199d80 6197ef84
0x6197ef7c:   00000020 c4a8eee9 680b0020 00000000
0x6197ef8c:   61a76ae8 08000030 6197efb4 704f7a70
0x6197ef9c:   00000000 680b0020 00199da0 0a435d04
0x6197efac:   08000030 61a76ae8 6197efcc 704dc9ab
0x6197efbc:   08000030 61a76ae8 08000000 2c827bd4
0x6197efcc:   6197efe8 704e81b2 00000145 08000028

Instructions: (pc=0x76dca05b)
0x76dca04b:   06 66 0f 6f 4e 10 66 0f 6f 56 20 66 0f 6f 5e 30
0x76dca05b:   66 0f 7f 07 66 0f 7f 4f 10 66 0f 7f 57 20 66 0f

Stack: [0x61930000,0x61980000],  sp=0x6197ef5c,  free space=315k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [msvcrt.dll+0xa05b]
C  [msvcrt.dll+0xa00b]
C  [prl_gldd.dll+0x27a70]
C  [prl_gldd.dll+0xc9ab]
C  [prl_gldd.dll+0x181b2]
C  [jogl.dll+0xf286]
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D1(IIIIIIIILjava/lang/Object;I)V+0
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D(IIIIIIIILjava/nio/Buffer;)V+85
j      com.sun.opengl.util.texture.Texture.updateSubImageImpl(Lcom/sun/opengl/util/texture/TextureData;IIIIIIII)V+658
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;I)V+1001
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;)V+3
j  com.sun.opengl.util.texture.Texture.<init>(Lcom/sun/opengl/util/texture/TextureData;)V+18
j  com.sun.opengl.util.texture.TextureIO.newTexture(Lcom/sun/opengl/util/texture/TextureData;)Lcom/sun/opengl/util/texture/Texture;+19
j  gov.nasa.worldwind.render.BasicWWTexture.initializeTexture(Lgov/nasa/worldwind/render/DrawContext;Ljava/lang/Object;)Lcom/sun/opengl/util/texture/Texture;+203
j  gov.nasa.worldwind.render.BasicWWTexture.bind(Lgov/nasa/worldwind/render/DrawContext;)Z+42
j  gov.nasa.worldwind.render.AbstractAnnotation.doDrawBackgroundTexture(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;Lgov/nasa/worldwind/render/WWTexture;)V+36
j  gov.nasa.worldwind.render.AbstractAnnotation.drawBackgroundImage(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.drawContent(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+19
j  gov.nasa.worldwind.render.AbstractAnnotation.doDraw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.draw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+47
j  gov.nasa.worldwind.render.AbstractAnnotation.drawTopLevelAnnotation(Lgov/nasa/worldwind/render/DrawContext;IIIIDDLgov/nasa/worldwind/geom/Position;)V+68
j  gov.nasa.worldwind.render.GlobeAnnotation.doRenderNow(Lgov/nasa/worldwind/render/DrawContext;)V+139
j  gov.nasa.worldwind.render.AbstractAnnotation.renderNow(Lgov/nasa/worldwind/render/DrawContext;)V+56
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.doRender(Lgov/nasa/worldwind/render/DrawContext;Lgov/nasa/worldwind/render/BasicAnnotationRenderer$OrderedAnnotation;)V+22
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.render(Lgov/nasa/worldwind/render/DrawContext;)V+20
J  gov.nasa.worldwind.AbstractSceneController.draw(Lgov/nasa/worldwind/render/DrawContext;)V
j  gov.nasa.worldwind.AbstractSceneController.repaint()I+49
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.doDisplay()I+4
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.display(Ljavax/media/opengl/GLAutoDrawable;)V+111
j  com.sun.opengl.impl.GLDrawableHelper.display(Ljavax/media/opengl/GLAutoDrawable;)V+29
j  javax.media.opengl.GLCanvas$DisplayAction.run()V+80
j  com.sun.opengl.impl.GLDrawableHelper.invokeGL(Ljavax/media/opengl/GLDrawable;Ljavax/media/opengl/GLContext;Ljava/lang/Runnable;Ljava/lang/Runnable;)V+418
j  javax.media.opengl.GLCanvas.maybeDoSingleThreadedWorkaround(Ljava/lang/Runnable;Ljava/lang/Runnable;)V+36
j  javax.media.opengl.GLCanvas.display()V+9
j  javax.media.opengl.GLCanvas.paint(Ljava/awt/Graphics;)V+125
j  javax.media.opengl.GLCanvas.update(Ljava/awt/Graphics;)V+2
j  sun.awt.RepaintArea.updateComponent(Ljava/awt/Component;Ljava/awt/Graphics;)V+6
j  sun.awt.RepaintArea.paint(Ljava/lang/Object;Z)V+263
j  sun.awt.windows.WComponentPeer.handleEvent(Ljava/awt/AWTEvent;)V+107
j  java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V+853
j  java.awt.Component.dispatchEvent(Ljava/awt/AWTEvent;)V+2
j  java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V+46
j  java.awt.EventDispatchThread.pumpOneEventForFilters(I)Z+204
j  java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V+30
j  java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11
j  java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4
j  java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3
j  java.awt.EventDispatchThread.run()V+9
v  ~StubRoutines::call_stub
V  [jvm.dll+0xf33c9]
V  [jvm.dll+0x188a91]
V  [jvm.dll+0xf3587]
V  [jvm.dll+0xf35eb]
V  [jvm.dll+0x11e780]
V  [jvm.dll+0x1ea6c4]
V  [jvm.dll+0x18843c]
C  [msvcr71.dll+0x9565]
C  [kernel32.dll+0x51194]
C  [ntdll.dll+0x5b495]
C  [ntdll.dll+0x5b468]

I have never seen this before so I have no idea how to figure out what the problem is.


问:
SQL Server transaction not committing
I have a SQL Server transaction which adds a column to a table, and then it adds some value to that column. It runs perfectly, but it doesn't commit the changes.

I checked with @@trancount, and it's value is 1 after running the query.

What is wrong with the transaction?

Thanks!

```<code>BEGIN TRANSACTION
    ALTER TABLE Table
        ADD ColumnName VARCHAR(200) NULL;
    GO

    BEGIN TRY
        UPDATE ColumnName
        SET ColumnName = 'some value'

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
    END CATCH;
</code>```

答:
You need to change your update to tell it which table to update.

```<code> UPDATE Table SET ColumnName = 'some value'
</code>```

Title: SQL Server transaction not committing

Body:
I have a SQL Server transaction which adds a column to a table, and then it adds some value to that column. It runs perfectly, but it doesn't commit the changes.

I checked with @@trancount, and it's value is 1 after running the query.

What is wrong with the transaction?

Thanks!

BEGIN TRANSACTION
    ALTER TABLE Table
        ADD ColumnName VARCHAR(200) NULL;
    GO

    BEGIN TRY
        UPDATE ColumnName
        SET ColumnName = 'some value'

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
    END CATCH;

Body:
You need to change your update to tell it which table to update.

 UPDATE Table SET ColumnName = 'some value'


问:
tkinter move object on canvas
I'm new in python. I'm trying to achieve a simple object movement on canvas.

The idea is to simply update X, Y coordinates and redraw the oval.

I've tried to use canvas.update() every time I update coordinates but it doesn't work this way.

```<code>class character():
    x = 10
    y = 10
    color = "red"
    canvas.create_oval(x, y, x + 40, y + 40, fill=color)

def moveup():
    character.y -= 10
def moveright():
    character.x += 10
def movedown():
    character.y += 10
def moveleft():
    character.x -= 10

def choose():
    choosen_move = randint(0, 4)

    if choosen_move == 0:
        moveup()
    elif choosen_move == 1:
        moveright()
    elif choosen_move == 2:
        movedown()
    elif choosen_move == 3:
        moveleft()

    print "%s | %s" % (character.x, character.y)
    canvas.update()
    sleep(1)

while True:
    choose()
root.mainloop()
</code>```

答:
**Please note: none of this code will work - it's just here to give you ideas about how to do stuff. :)

I've had objects bound to the keyboard that move around the screen when buttons are pressed.

instead of a loop, you can just change the x and y of an object with config and bind... when you press left on the keyboard the def will be run which moves the thing. (or things)

```<code>def move_object_left()...
   object.config(move left...)
</code>```

example of binding something:

```<code>entry.bind('<ButtonRelease-1>', lambda event: self.maximise_keyboard(event.widget))
</code>```

x_var = 5
y_var = 9

**Bind an object to the keyboard here:

```<code>*On_key_press('RIGHT'):
    x_var = x_var + 5
    object.config(x = x_var)
</code>```

You can move a bunch of stuff at once if you want... (though you will have to do the code yourself lol)

list_of_stuff = [tree, bush, snail]

```<code>    for entry in list_of_stuff:
        ...
        **Get object X and Y of the object...
        ** add a number to this X and Y...
</code>```

Title: tkinter move object on canvas

Body:
I'm new in python. I'm trying to achieve a simple object movement on canvas.

The idea is to simply update X, Y coordinates and redraw the oval.

I've tried to use canvas.update() every time I update coordinates but it doesn't work this way.

class character():
    x = 10
    y = 10
    color = "red"
    canvas.create_oval(x, y, x + 40, y + 40, fill=color)

def moveup():
    character.y -= 10
def moveright():
    character.x += 10
def movedown():
    character.y += 10
def moveleft():
    character.x -= 10

def choose():
    choosen_move = randint(0, 4)

    if choosen_move == 0:
        moveup()
    elif choosen_move == 1:
        moveright()
    elif choosen_move == 2:
        movedown()
    elif choosen_move == 3:
        moveleft()

    print "%s | %s" % (character.x, character.y)
    canvas.update()
    sleep(1)

while True:
    choose()
root.mainloop()

Body:
**Please note: none of this code will work - it's just here to give you ideas about how to do stuff. :)

I've had objects bound to the keyboard that move around the screen when buttons are pressed.

instead of a loop, you can just change the x and y of an object with config and bind... when you press left on the keyboard the def will be run which moves the thing. (or things)

def move_object_left()...
   object.config(move left...)

example of binding something:

entry.bind('<ButtonRelease-1>', lambda event: self.maximise_keyboard(event.widget))

x_var = 5
y_var = 9

**Bind an object to the keyboard here:

*On_key_press('RIGHT'):
    x_var = x_var + 5
    object.config(x = x_var)

You can move a bunch of stuff at once if you want... (though you will have to do the code yourself lol)

list_of_stuff = [tree, bush, snail]

    for entry in list_of_stuff:
        ...
        **Get object X and Y of the object...
        ** add a number to this X and Y...


问:
eth0 interface doesn't connect if the cable is plugged after the boot
I have a C# .net application running in my own embedded custom linux distro generated by buildroot tool, my hardware is a FriendlyArm4412. I use eth0 interfaces to connect my application to the internet without any problem. The problem is: If I connect the ethernet cable before the system boot everything is OK but if I plug the cable after the system boot my system can't get an ip address. I see this because my application shows on the screen "ip address: 127.0.0.1" which is just my local address.

I've already tried to use the Connman network manager which worked very well for the problem above, but I realized that connman ignores my /etc/network/interfaces settings which is bad because my application sets up some things in this file, like static ip address, wlan0 interface, etc.

What can I do ? Any idea ?

答:
Check DefaultAutoConnectTechnologies configuration parameter in /etc/connman/main.conf file. See whether ethernet is present or not.

Connman doesn't use /etc/network/interfaces file. You need to use Connman D-Bus API's to set static IP to your network interface. Download Connman source code and see doc/service-api.txt for D-Bus API. Also see test/set-ipv4-method python script in source directory for a quick code reference on how to set static IP using D-Bus API.

If you don't want to use D-Bus API, you can edit connman storage directory files to set static IP before connman start. But editing connman storage directory is not a right way to do this. Default Connman storage directory is /var/lib/connman/ethernet_$mac_address_cable/*.


问:
Select rows between rows fulfilling certain conditions in Python
I have a large pandas dataframe and I would like to select all user actions that happen between an entry (action1 == 0) and an exit point (action1 == 1). There are multiple such user sessions in the database. It looks something like this:

```<code>User_action   Reference   Other_data  Row_index
  action2         0          foo         a
  action1         0          bar         b
  action6         0          foo         c
  action4         0          foo         d
  action1         1          bar         e
  action7         0          foo         f
  action1         0          foo         g
  action3         0          bar         h
  action1         1          foo         i
  action1         1          foo         j
  action3         0          bar         k
  action1         0          foo         l
  action9         0          foo         m
  action1         1          foo         n
</code>```

The result should produce the rows with the indexes:  c,d,h and m:

```<code>User_action   Reference   Other_data  Row_index
  action6         0          foo         c
  action4         0          foo         d
  action3         0          bar         h
  action9         0          foo         m
</code>```

答:
Use:</p>

```<code>#filter only category
df1 = df[df['User_action'] == 'action1'].copy()

#test only pairs 0, 1 and reindex for same length as original df
m1 = df1['Reference'].eq(1) & df1['Reference'].shift(1).eq(0)
m1 = m1.reindex(df.index, fill_value=False)
m2 = df1['Reference'].eq(0) & df1['Reference'].shift(-1).eq(1)
m2 = m2.reindex(df.index, fill_value=False).shift().fillna(False)

a = np.select([m1, m2], [-1,1], default=0)
m = a.cumsum() == 1
#filter by final condition
df = df[m]

print (df)
   User_action  Reference Other_data Row_index
4      action6          0        foo         c
5      action4          0        foo         d
9      action3          0        bar         h
14     action9          0        foo         m
</code>```

Body:
I have a large pandas dataframe and I would like to select all user actions that happen between an entry (action1 == 0) and an exit point (action1 == 1). There are multiple such user sessions in the database. It looks something like this:

User_action   Reference   Other_data  Row_index
  action2         0          foo         a
  action1         0          bar         b
  action6         0          foo         c
  action4         0          foo         d
  action1         1          bar         e
  action7         0          foo         f
  action1         0          foo         g
  action3         0          bar         h
  action1         1          foo         i
  action1         1          foo         j
  action3         0          bar         k
  action1         0          foo         l
  action9         0          foo         m
  action1         1          foo         n

The result should produce the rows with the indexes:  c,d,h and m:

User_action   Reference   Other_data  Row_index
  action6         0          foo         c
  action4         0          foo         d
  action3         0          bar         h
  action9         0          foo         m

Body:
Use:

#filter only category
df1 = df[df['User_action'] == 'action1'].copy()

#test only pairs 0, 1 and reindex for same length as original df
m1 = df1['Reference'].eq(1) & df1['Reference'].shift(1).eq(0)
m1 = m1.reindex(df.index, fill_value=False)
m2 = df1['Reference'].eq(0) & df1['Reference'].shift(-1).eq(1)
m2 = m2.reindex(df.index, fill_value=False).shift().fillna(False)

a = np.select([m1, m2], [-1,1], default=0)
m = a.cumsum() == 1
#filter by final condition
df = df[m]

print (df)
   User_action  Reference Other_data Row_index
4      action6          0        foo         c
5      action4          0        foo         d
9      action3          0        bar         h
14     action9          0        foo         m


问:
How can I do a window that is always maximized?
I know that I can change the propertie 'WindowState' to 'Maximized' and also change the propertie 'MaximizeBox' to 'false', so my application starts maximized and there's no chance to restore my window by clicking on the restore button.

But I can drag the window and move down, so it automatically restores. Is there any way of universally blocking the restore?

Thank you in advance.

答:
Take a look at this link https://vaibhavgaikwad.wordpress.com/2006/06/05/creating-a-immovable-windows-form-in-c/ and override the WndProc with the following code.

```<code>protected override void WndProc(ref Message message)
{
  const int WM_SYSCOMMAND = 0x0112;
  const int SC_MOVE = 0xF010;

  switch(message.Msg)
  {
      case WM_SYSCOMMAND:
         int command = message.WParam.ToInt32() & 0xfff0;
         if (command == SC_MOVE)
            return;
         break;
  }

  base.WndProc(ref message);
}
</code>```

c# winforms

Body:
Take a look at this link https://vaibhavgaikwad.wordpress.com/2006/06/05/creating-a-immovable-windows-form-in-c/ and override the WndProc with the following code.

protected override void WndProc(ref Message message)
{
  const int WM_SYSCOMMAND = 0x0112;
  const int SC_MOVE = 0xF010;

  switch(message.Msg)
  {
      case WM_SYSCOMMAND:
         int command = message.WParam.ToInt32() & 0xfff0;
         if (command == SC_MOVE)
            return;
         break;
  }

  base.WndProc(ref message);
}

c# winforms


问:
Evaluate Excel VBA boolean condition (not a formula)
I have text in a cell A1 as below

```<code>((True And False Or True) And (True And (Not True))) And (False Or True)
</code>```

I need to evaluate this text and put Boolean result (True / False) in another cell B1 using VBA code.

I tried to use Evaluate function, it is not working.

When I read this cell, it always return string type with double quote enclose in both side. Hence it is treated as string and not evaluating the Boolean expression.

```<code>"((True And True Or True) And (True And (True))) And (True Or True)"
</code>```

I want to write this way, but it is not working

```<code>If Range("A1").Value = True Then
    Range("B1").Value = True
Else
    Range("B1").Value = False
End If
</code>```

I tried to store in Boolean variable also

```<code>Dim Result as Boolean
Result = CBool(Range("A1").Value)
</code>```

as it is string, I am getting type mismatch when I tried to convert using CBool.

答:
You could try something like this, taking advantage of the Eval function in Access.</p>

```<code>Public Function EvaluateExpression(Value As String) As Boolean
    With CreateObject("Access.Application")
        EvaluateExpression = .Eval(Value)
    End With
End Function

Public Sub T()
    Debug.Print EvaluateExpression("((True And True Or True) And (True And (True))) And (True Or True)")
End Sub

'True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have text in a cell A1 as below

((True And False Or True) And (True And (Not True))) And (False Or True)

I need to evaluate this text and put Boolean result (True / False) in another cell B1 using VBA code.

I tried to use Evaluate function, it is not working.

When I read this cell, it always return string type with double quote enclose in both side. Hence it is treated as string and not evaluating the Boolean expression.

"((True And True Or True) And (True And (True))) And (True Or True)"

I want to write this way, but it is not working

If Range("A1").Value = True Then
    Range("B1").Value = True
Else
    Range("B1").Value = False
End If

I tried to store in Boolean variable also

Dim Result as Boolean
Result = CBool(Range("A1").Value)

as it is string, I am getting type mismatch when I tried to convert using CBool.

Body:
You could try something like this, taking advantage of the Eval function in Access.

Public Function EvaluateExpression(Value As String) As Boolean
    With CreateObject("Access.Application")
        EvaluateExpression = .Eval(Value)
    End With
End Function

Public Sub T()
    Debug.Print EvaluateExpression("((True And True Or True) And (True And (True))) And (True Or True)")
End Sub

'True


问:
How to create custom JQuery function and how to use it?
I'm searching for information about that - "How to create custom (own) JQuery function and how to use it"

I've searched in Google, but I didn't found information about that.

Can you explain in details, about custom functions?

答:
I wanted my custom functions to be invoked like $.myfunction(). I defined those functions in an external js file somewhat like this

```<code>$.myfunction = function(){

//Your code here
};
</code>```

Body:
I wanted my custom functions to be invoked like $.myfunction(). I defined those functions in an external js file somewhat like this

$.myfunction = function(){

//Your code here
};


问:
cucumber jvm close browser after running all features
I'm testing a Spring Boot app using Cucumber-JVM and Selenium. I'm defining a web driver bean and passing a destroy method to quit (shutdown the webdriver and all instances of Chrome) but it is leaving the browser open.

```<code>@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}
</code>```

I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration.

```<code><bean class="org.openqa.selenium.support.events.EventFiringWebDriver" destroy-method="quit">
    <constructor-arg>
        <bean class="org.openqa.selenium.firefox.FirefoxDriver" />
    </constructor-arg>
</bean>
</code>```

How do I get the browser to close at the end of all tests?

答:
I thought the default bean scope was singleton, but the browser is correctly shut down if I add @Scope("singleton"). eg:</p>

```<code>@Bean(destroyMethod = "quit")
@Scope("singleton")
public WebDriver webDriver() {
    System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
    return new ChromeDriver();
}
</code>```

Body:
I'm testing a Spring Boot app using Cucumber-JVM and Selenium. I'm defining a web driver bean and passing a destroy method to quit (shutdown the webdriver and all instances of Chrome) but it is leaving the browser open.

@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}

I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration.

<bean class="org.openqa.selenium.support.events.EventFiringWebDriver" destroy-method="quit">
    <constructor-arg>
        <bean class="org.openqa.selenium.firefox.FirefoxDriver" />
    </constructor-arg>
</bean>

How do I get the browser to close at the end of all tests?

Body:
I thought the default bean scope was singleton, but the browser is correctly shut down if I add @Scope("singleton"). eg:

@Bean(destroyMethod = "quit")
@Scope("singleton")
public WebDriver webDriver() {
    System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
    return new ChromeDriver();
}


问:
Android: How to change specific name of the generated apk file in Android Studio?
By default IDE genarate a apk like app-debug.apk or app-release.apk file but I need to generate specific name of the Apk of the App.

For Example:
My application name is iPlanter so i need to generate iPlanter-debug.apk or iPlanter-release.apk instead of  app-debug.apk or app-release.apk respectively.

Thanks,

答:
This will help you. This code will create app name like iPlanter-release.apk or iPlanter-debug.apk

```<code>buildTypes {
   applicationVariants.all { variant ->
    variant.outputs.each { output ->
        project.ext { appName = 'iPlanter' }
        def newName = output.outputFile.name
        newName = newName.replace("app-", "$project.ext.appName-")
        output.outputFile = new File(output.outputFile.parent, newName)
     }
  }
}
</code>```

Update:

```<code>  applicationVariants.all { variant ->
    variant.outputs.all {
        outputFileName = "iPlanter_${variant.versionName}(${variant.versionCode}).apk"
    }
  }
</code>```

It set name like

iPlanter_0.0.1(25).apk

Body:
This will help you. This code will create app name like iPlanter-release.apk or iPlanter-debug.apk

buildTypes {
   applicationVariants.all { variant ->
    variant.outputs.each { output ->
        project.ext { appName = 'iPlanter' }
        def newName = output.outputFile.name
        newName = newName.replace("app-", "$project.ext.appName-")
        output.outputFile = new File(output.outputFile.parent, newName)
     }
  }
}

Update:

  applicationVariants.all { variant ->
    variant.outputs.all {
        outputFileName = "iPlanter_${variant.versionName}(${variant.versionCode}).apk"
    }
  }

It set name like

iPlanter_0.0.1(25).apk


问:
C string initializer doesn't include terminator?
I am a little confused by the following C code snippets:

```<code>printf("Peter string is %d bytes\n", sizeof("Peter")); // Peter string is 6 bytes
</code>```

This tells me that when C compiles a string in double quotes, it will automatically add an extra byte for the null terminator.

```<code>printf("Hello '%s'\n", "Peter");
</code>```

The printf function knows when to stop reading the string "Peter" because it reaches the null terminator, so ...

```<code>char myString[2][9] = {"123456789", "123456789" };
printf("myString: %s\n", myString[0]);
</code>```

Here, printf prints all 18 characters because there's no null terminators (and they wouldn't fit without taking out the 9's). Does C not add the null terminator in a variable definition?

答:
C allows unterminated strings, C++ does not.

C allows character arrays to be
  initialized with string constants. It
  also allows a string constant
  initializer to contain exactly one
  more character than the array it
  initializes, i.e., the implicit
  terminating null character of the
  string may be ignored. For example:

```<code>char  name1[] =  "Harry";   // Array of 6 char

char  name2[6] = "Harry";   // Array of 6 char

char  name3[] =  { 'H', 'a', 'r', 'r', 'y', '\0' };
                            // Same as 'name1' initialization

char  name4[5] = "Harry";   // Array of 5 char, no null char
</code>```

C++ also allows character arrays to be
  initialized with string constants, but
  always includes the terminating null
  character in the initialization. Thus
  the last initializer (name4) in the
  example above is invalid in C++.

OwnerDisplayName: Peter

Body:
I am a little confused by the following C code snippets:

printf("Peter string is %d bytes\n", sizeof("Peter")); // Peter string is 6 bytes

This tells me that when C compiles a string in double quotes, it will automatically add an extra byte for the null terminator.

printf("Hello '%s'\n", "Peter");

The printf function knows when to stop reading the string "Peter" because it reaches the null terminator, so ...

char myString[2][9] = {"123456789", "123456789" };
printf("myString: %s\n", myString[0]);

Here, printf prints all 18 characters because there's no null terminators (and they wouldn't fit without taking out the 9's). Does C not add the null terminator in a variable definition?

Body:
C allows unterminated strings, C++ does not.

C allows character arrays to be
  initialized with string constants. It
  also allows a string constant
  initializer to contain exactly one
  more character than the array it
  initializes, i.e., the implicit
  terminating null character of the
  string may be ignored. For example:

char  name1[] =  "Harry";   // Array of 6 char

char  name2[6] = "Harry";   // Array of 6 char

char  name3[] =  { 'H', 'a', 'r', 'r', 'y', '\0' };
                            // Same as 'name1' initialization

char  name4[5] = "Harry";   // Array of 5 char, no null char

C++ also allows character arrays to be
  initialized with string constants, but
  always includes the terminating null
  character in the initialization. Thus
  the last initializer (name4) in the
  example above is invalid in C++.

OwnerDisplayName: Checkers


问:
Dynamicly sorting a MYSQL Stored Procedure / Function
I have a MYSQL function called spGetVideosByLocation. Currently I call it like this:

```<code>CALL spGetVideosByLocation(location);
</code>```

This basically calls a query similar to this:

```<code>SELECT * FROM Videos WHERE LocationId = location;
</code>```

My question is, is there a way to define ORDER BY when I call the function?
How do I get this:

```<code>CALL spGetVideosByLocation(location, "tableName", DESC);
</code>```

To query this:

```<code>SELECT * FROM Videos WHERE LocationId = location ORDER BY tableName DESC;
</code>```

答:
What programming language are you using?  Assuming you are using php, here is the code I would use:</p>

```<code>function spGetVideosByLocation($locationid, $order, $orderby)
{
    $sql = "SELECT * FROM Videos WHERE LocationId = '$locationid' ORDER BY $order $orderby";
    $result = mysql_query($sql) or die(mysql_error());
    //do whatever you need to to get results
}
</code>```

Body:
I have a MYSQL function called spGetVideosByLocation. Currently I call it like this:

CALL spGetVideosByLocation(location);

This basically calls a query similar to this:

SELECT * FROM Videos WHERE LocationId = location;

My question is, is there a way to define ORDER BY when I call the function?
How do I get this:

CALL spGetVideosByLocation(location, "tableName", DESC);

To query this:

SELECT * FROM Videos WHERE LocationId = location ORDER BY tableName DESC;

Body:
What programming language are you using?  Assuming you are using php, here is the code I would use:

function spGetVideosByLocation($locationid, $order, $orderby)
{
    $sql = "SELECT * FROM Videos WHERE LocationId = '$locationid' ORDER BY $order $orderby";
    $result = mysql_query($sql) or die(mysql_error());
    //do whatever you need to to get results
}


问:
ESXi web client auto-fill credentials
I'm trying to write a greasemonkey script that autofills ESXi login web page with credentials. The following code fills the input fields and enables the submit button:

```<code>// ==UserScript==
// @name         ESXi autofill credentials
// @namespace    https://esx_address/ui/*
// @version      0.1
// @description  Autofills user and password inputs
// @author       Mirek
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require      https://gist.github.com/raw/2625891/waitForKeyElements.js
// @match        https://esx_address/ui/*
// @grant        none
// ==/UserScript==

try {
    waitForKeyElements ("#password", function(jNode) {jNode.val("password");});
    waitForKeyElements ("#username", function(jNode) {jNode.val("user");});
    waitForKeyElements ("#submit", function(jNode) {jNode.prop("disabled", false);});
} catch(err) {
    console.log("Something went wrong: " + err.message);
}
</code>```

Unfortunately, after I click the submit button I see Cannot complete login due to an incorrect user name or password. even though the credentials are correct.

The issue is probably with the submit button enabling. The login page enables it once the user types something into username field. Unfortunately, the script doesn't trigger this behavior. I found out that with the script enabled, when I go to the login page and re-type the last letters of username and password fields, the login succeeds.

How could I fill the input fields in a way that will trigger the submit button to turn on?

答:
Thanks to Brock's input I was able to succeed. Thanks! Works with ESXi version: 6.5.0, Client version: 1.18.0.

The change and blur events successfully enable the submit button.

```<code>function loginSite() {
    waitForKeyElements("#username", function(jNode) {jNode.val(username);}, true);
    waitForKeyElements ("#password", function(jNode) {jNode.val(password);}, true);
    setTimeout(function() {
        changeAndBlur("#username");
        changeAndBlur("#password");
    }, 400);
}

function changeAndBlur(jSelector) {
    let node = $(jSelector);
    if (node.length) {
        var evChng = new Event("change");
        node[0].dispatchEvent(evChng);
        var evBlur = new Event("blur");
        node[0].dispatchEvent(evBlur);
    }
}

waitForKeyElements("#submit", loginSite, true);
</code>```

Title: ESXi web client auto-fill credentials

Body:
I'm trying to write a greasemonkey script that autofills ESXi login web page with credentials. The following code fills the input fields and enables the submit button:

// ==UserScript==
// @name         ESXi autofill credentials
// @namespace    https://esx_address/ui/*
// @version      0.1
// @description  Autofills user and password inputs
// @author       Mirek
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require      https://gist.github.com/raw/2625891/waitForKeyElements.js
// @match        https://esx_address/ui/*
// @grant        none
// ==/UserScript==

try {
    waitForKeyElements ("#password", function(jNode) {jNode.val("password");});
    waitForKeyElements ("#username", function(jNode) {jNode.val("user");});
    waitForKeyElements ("#submit", function(jNode) {jNode.prop("disabled", false);});
} catch(err) {
    console.log("Something went wrong: " + err.message);
}

Unfortunately, after I click the submit button I see Cannot complete login due to an incorrect user name or password. even though the credentials are correct.

The issue is probably with the submit button enabling. The login page enables it once the user types something into username field. Unfortunately, the script doesn't trigger this behavior. I found out that with the script enabled, when I go to the login page and re-type the last letters of username and password fields, the login succeeds.

How could I fill the input fields in a way that will trigger the submit button to turn on?

Body:
Thanks to Brock's input I was able to succeed. Thanks! Works with ESXi version: 6.5.0, Client version: 1.18.0.

The change and blur events successfully enable the submit button.

function loginSite() {
    waitForKeyElements("#username", function(jNode) {jNode.val(username);}, true);
    waitForKeyElements ("#password", function(jNode) {jNode.val(password);}, true);
    setTimeout(function() {
        changeAndBlur("#username");
        changeAndBlur("#password");
    }, 400);
}

function changeAndBlur(jSelector) {
    let node = $(jSelector);
    if (node.length) {
        var evChng = new Event("change");
        node[0].dispatchEvent(evChng);
        var evBlur = new Event("blur");
        node[0].dispatchEvent(evBlur);
    }
}

waitForKeyElements("#submit", loginSite, true);


问:
Java: Read text from a file that was previously selected in another class
Using JavaFX, I have  the user input information into text fields.
My MainController class allows the user to save that inputted text to a txt file and save it at a given location.

Im wondering if its possible to pass what was entered in that text file into another class so I can parse and have my program use its data.

I used strings and .getText() then used a filewriter and bufferedWriter.
Can I get the .getText input into another class?

答:
You should research for Java - Access Modifiers

but as an ideia,

```<code>public class MainController {

    private String savedFilePath;

    public String getSavedFilePath() {
        return savedFilePath;
    }

    public void setSavedFilePath(String savedFilePath) {
        this.savedFilePath = savedFilePath;
    }
}
</code>```

and from the other class, when you save the file you can call:

```<code>MainController controller = new MainController();
controller.setSavedFilePath("file path");
</code>```

If you don't want to create a new object MainController, you can define the savedFilePath as static

```<code>public class MainController {

    private static String savedFilePath;

    public static void setSavedFilePath(String paramSavedFilePath) {
        savedFilePath = paramSavedFilePath;
    }
}
</code>```

and just call:

```<code>MainController.setSavedFilePath("file path");
</code>```

Body:
You should research for Java - Access Modifiers

but as an ideia,

public class MainController {

    private String savedFilePath;

    public String getSavedFilePath() {
        return savedFilePath;
    }

    public void setSavedFilePath(String savedFilePath) {
        this.savedFilePath = savedFilePath;
    }
}

and from the other class, when you save the file you can call:

MainController controller = new MainController();
controller.setSavedFilePath("file path");

If you don't want to create a new object MainController, you can define the savedFilePath as static

public class MainController {

    private static String savedFilePath;

    public static void setSavedFilePath(String paramSavedFilePath) {
        savedFilePath = paramSavedFilePath;
    }
}

and just call:

MainController.setSavedFilePath("file path");


问:
Table from Excel to another table
Suppose there are 3 columns. In 1 column number (a1), in the second name (b1), in the third description (c1). I want to make another 1 table, so that the data would spread to it, but with 1 condition. If in the 3 column, in one cell more than 500 characters, then continue to copy the data from the rows to the next cell. (For example, there is a line a2, b2, c2 In cell c2, 600 symbols are obtained, then the remaining characters are transferred to one cell, c3 and copy the text from cells a2, b2) Is it possible to trace it? To make, some counter, that he would count the symbols in the cell.
enter image description here

table

tabletest1

答:
VB Macro

After some tries, i got a VB macro which makes that

```<code>Sub copyTable()
    Dim colRange As Variant
    colRange = Array(1, 2, 3) 'Columns where your data is'
    Dim destColRange As Variant
    destColRange = Array(5, 6, 7) 'Columns where you want data be copied'
    n = UBound(colRange) - LBound(colRange)
    i = 2 'Initial row'
    newI = i
    maxLen = 10 'Maximum size allowed in one cell'
    While Not (Cells(i, colRange(0)) Is Nothing) And (Cells(i, colRange(0)) <> "")
        Text = Cells(i, colRange(n))
        Do
            For j = 0 To n - 1
                Cells(newI, destColRange(j)) = Cells(i, colRange(j))
            Next j
            Cells(newI, destColRange(j)) = Mid(Text, 1, maxLen)
            Text = Mid(Text, maxLen + 1)
            newI = newI + 1
        Loop Until Len(Text) <= 0
        i = i + 1
    Wend
End Sub
</code>```

Variables explanation

colRange:     Indexes of columns with origin data

destColRange: Indexes of columns where data will be written

i:            Initial row

maxLen:       Maximum length allowed per cell

Note that this snippet only cares about size of the last cell, if any other has more length it will copy them as they are.

when you run it you got something like

I've never made a VB code, so don't be critic, it surely can be better

Title: Table from Excel to another table

Body:
VB Macro

After some tries, i got a VB macro which makes that

Sub copyTable()
    Dim colRange As Variant
    colRange = Array(1, 2, 3) 'Columns where your data is'
    Dim destColRange As Variant
    destColRange = Array(5, 6, 7) 'Columns where you want data be copied'
    n = UBound(colRange) - LBound(colRange)
    i = 2 'Initial row'
    newI = i
    maxLen = 10 'Maximum size allowed in one cell'
    While Not (Cells(i, colRange(0)) Is Nothing) And (Cells(i, colRange(0)) <> "")
        Text = Cells(i, colRange(n))
        Do
            For j = 0 To n - 1
                Cells(newI, destColRange(j)) = Cells(i, colRange(j))
            Next j
            Cells(newI, destColRange(j)) = Mid(Text, 1, maxLen)
            Text = Mid(Text, maxLen + 1)
            newI = newI + 1
        Loop Until Len(Text) <= 0
        i = i + 1
    Wend
End Sub

Variables explanation

colRange:     Indexes of columns with origin data

destColRange: Indexes of columns where data will be written

i:            Initial row

maxLen:       Maximum length allowed per cell

Note that this snippet only cares about size of the last cell, if any other has more length it will copy them as they are.

when you run it you got something like

I've never made a VB code, so don't be critic, it surely can be better


问:
Scanning media files with ionic using the file cordova plugin
I'm building a music player application using Ionic, so how can I scan music files from the file storage  using the file cordova plugin  so users can be able to select songs to play .P.S I'm pretty new to Ionic.</p>

答:
This code will list all folders and files:</p>

```<code>    import { File } from "@ionic-native/file";
    import { Diagnostic } from "@ionic-native/diagnostic";

    constructor(
        ...
        public file: File,
        public diagnostic: Diagnostic
        ){

  // -------------------------
  listFileSys( which){

    // <which> chooses the file system - see switch below
    this.jcDebug += "\n" + "listFileSysSKOFLO(" + which + ")";

    let fileSysArray = [];
    let basePath = "";

    let tag = "unknown";

    // ************** RECURSE *************
    let jcListDir = (thisDir)=>{

      tag = "jcListDir: [" + thisDir + "]";

      this.file.listDir(basePath, thisDir)
      .then( (data)=>{
        tag = "listDir:" + thisDir;
        this.jcError += "\n" + tag + ":" + JSON.stringify( data);
        for( let ii = 0; ii < data.length; ii += 1){
          this.jcError += "\n" + data[ii].name + (data[ii].isDirectory? " [D]" : " [F]");

          let currentPath = thisDir;
          currentPath += (currentPath.length ? "/" : "");
          currentPath += data[ii].name;
          this.jcError += "\n" + "currentPath:" + currentPath;

          fileSysArray.push( currentPath);

          if( data[ii].isDirectory && ok2recurse){
            jcListDir( currentPath);         // RECURSE !!!
          }
        }
      }, (errData)=>{
        tag = "listDir";
        this.jcError += "\n" + tag + ":ERR:" + JSON.stringify( errData);
      });
    };
    // ************** RECURSE *************

    // ***********************
    let runListDir = ()=>{
        this.jcDebug += "\n" + "basePath:" + basePath;

        // !!! START listing from basePath !!!
        jcListDir( ".");
    }

    // ***********************
    switch( which)
    {
      case 1:
        this.diagnostic.getExternalSdCardDetails()
        .then( (data) => {
          this.jcDebug += "\n" + "sd:" + JSON.stringify( data);
          this.jcDebug += "\n" + "Number of cards: " + data.length;
          for( let ii = 0; ii < data.length; ii += 1){
            let thisElem = data[ii];
            if( thisElem.type.toLowerCase() === "application" && thisElem.canWrite){
              basePath = thisElem.filePath;
              break;
            }
          }
          if( !basePath){
            this.jcDebug += "\n" + "no SD card found";
            return;
          }
          runListDir();
        }, (errData)=>{
          tag = "getExternalSdCardDetails";
          this.jcError += "\n" + tag + ":ERR:" + JSON.stringify( errData);
        });
      break;
      case 2:
        basePath = this.file.externalDataDirectory;
        this.jcError += "\n" + "externalDataDirectory:" + basePath;
        runListDir();
        break;
      case 3:
        basePath = this.file.dataDirectory;
        this.jcError += "\n" + "dataDirectory:";
        runListDir();
        break;
      default:
        alert( "which???:" + which);
        return;
    }

    // wait for all to comnplete, then show
    // assume 1000 ms is adequate delay per promise
    let lastFileSysLen = -1
    let checkCount = 30; // max 30 * 1000 ms = 30 seconds

    // ************** RECURSE *************
      let checkComplete = () => {
      this.jcDebug += "\n" + "checkComplete " + checkCount + " [" + fileSysArray.length + "]";
      setTimeout( ()=>{

        // fileSysArr length stable?
        if( fileSysArray.length === lastFileSysLen){
          checkCount = 0;
        }
        lastFileSysLen = fileSysArray.length;

        checkCount -= 1;
        if( checkCount > 0){
          checkComplete();    // recurse
        } else {

          // STOP !!! and show FileSysArray
          this.jcInfo += "\n" + "show FileSysArray";
          this.jcInfo += "\n" + "fileSysArray.length = " + " [" + fileSysArray.length + "]";

          fileSysArray.sort();

          for( let elem of fileSysArray){
            this.jcInfo += "\n" + elem;
          }
        }
      }, 1000);
    };
    // ************** RECURSE *************
    checkComplete();
  }
</code>```

Body:
This code will list all folders and files:

    import { File } from "@ionic-native/file";
    import { Diagnostic } from "@ionic-native/diagnostic";

    constructor(
        ...
        public file: File,
        public diagnostic: Diagnostic
        ){

  // -------------------------
  listFileSys( which){

    // <which> chooses the file system - see switch below
    this.jcDebug += "\n" + "listFileSysSKOFLO(" + which + ")";

    let fileSysArray = [];
    let basePath = "";

    let tag = "unknown";

    // ************** RECURSE *************
    let jcListDir = (thisDir)=>{

      tag = "jcListDir: [" + thisDir + "]";

      this.file.listDir(basePath, thisDir)
      .then( (data)=>{
        tag = "listDir:" + thisDir;
        this.jcError += "\n" + tag + ":" + JSON.stringify( data);
        for( let ii = 0; ii < data.length; ii += 1){
          this.jcError += "\n" + data[ii].name + (data[ii].isDirectory? " [D]" : " [F]");

          let currentPath = thisDir;
          currentPath += (currentPath.length ? "/" : "");
          currentPath += data[ii].name;
          this.jcError += "\n" + "currentPath:" + currentPath;

          fileSysArray.push( currentPath);

          if( data[ii].isDirectory && ok2recurse){
            jcListDir( currentPath);         // RECURSE !!!
          }
        }
      }, (errData)=>{
        tag = "listDir";
        this.jcError += "\n" + tag + ":ERR:" + JSON.stringify( errData);
      });
    };
    // ************** RECURSE *************

    // ***********************
    let runListDir = ()=>{
        this.jcDebug += "\n" + "basePath:" + basePath;

        // !!! START listing from basePath !!!
        jcListDir( ".");
    }

    // ***********************
    switch( which)
    {
      case 1:
        this.diagnostic.getExternalSdCardDetails()
        .then( (data) => {
          this.jcDebug += "\n" + "sd:" + JSON.stringify( data);
          this.jcDebug += "\n" + "Number of cards: " + data.length;
          for( let ii = 0; ii < data.length; ii += 1){
            let thisElem = data[ii];
            if( thisElem.type.toLowerCase() === "application" && thisElem.canWrite){
              basePath = thisElem.filePath;
              break;
            }
          }
          if( !basePath){
            this.jcDebug += "\n" + "no SD card found";
            return;
          }
          runListDir();
        }, (errData)=>{
          tag = "getExternalSdCardDetails";
          this.jcError += "\n" + tag + ":ERR:" + JSON.stringify( errData);
        });
      break;
      case 2:
        basePath = this.file.externalDataDirectory;
        this.jcError += "\n" + "externalDataDirectory:" + basePath;
        runListDir();
        break;
      case 3:
        basePath = this.file.dataDirectory;
        this.jcError += "\n" + "dataDirectory:";
        runListDir();
        break;
      default:
        alert( "which???:" + which);
        return;
    }

    // wait for all to comnplete, then show
    // assume 1000 ms is adequate delay per promise
    let lastFileSysLen = -1
    let checkCount = 30; // max 30 * 1000 ms = 30 seconds

    // ************** RECURSE *************
      let checkComplete = () => {
      this.jcDebug += "\n" + "checkComplete " + checkCount + " [" + fileSysArray.length + "]";
      setTimeout( ()=>{

        // fileSysArr length stable?
        if( fileSysArray.length === lastFileSysLen){
          checkCount = 0;
        }
        lastFileSysLen = fileSysArray.length;

        checkCount -= 1;
        if( checkCount > 0){
          checkComplete();    // recurse
        } else {

          // STOP !!! and show FileSysArray
          this.jcInfo += "\n" + "show FileSysArray";
          this.jcInfo += "\n" + "fileSysArray.length = " + " [" + fileSysArray.length + "]";

          fileSysArray.sort();

          for( let elem of fileSysArray){
            this.jcInfo += "\n" + elem;
          }
        }
      }, 1000);
    };
    // ************** RECURSE *************
    checkComplete();
  }


问:
Mysql Color Scheme
Is there a way to set a color scheme for the mysql client? It might sound trivial, but I'd like to be able to set some level of colors for terminal client.</p>

答:
Add this to your ~/.profile [or ~/.bashrc]</p>

```<code>export MYSQL_PS1="$(echo -e '\033[1;32mmysql \d> \033[0m')"
</code>```

Title: Mysql Color Scheme

Body:
Add this to your ~/.profile [or ~/.bashrc]

export MYSQL_PS1="$(echo -e '\033[1;32mmysql \d> \033[0m')"


问:
Rpy2: how to access the R list-type variable?
I can fit a model in Jupyter/Python using rpy2, however, the result returned is a list type value in R. For example

```<code># Cell #1, load rpy2 and re
%load_ext rpy2.ipython
%R require(ggplot2)
%R require(movMF)

# Cell #2, generate data from Python
from scipy.stats import vonmises
kappa = 5
samples = vonmises.rvs(kappa, size=100)
data = [cos(samples), sin(samples)]

# Cell #3, fit model using R and rpy2
%%R -i data -o result
result = movMF(data, 1, nruns = 10)

# Cell #4, print result
print(result)
</code>```

The result looks like this:

If I type result it returns

```<code>R object with classes: ('movMF',) mapped to:
<ListVector - Python:0x00000000103B4448 / R:0x0000000010CB2380>
[Matrix, Float..., Float..., ..., IntVe..., Float..., ListV...]
  theta: <class 'rpy2.robjects.vectors.Matrix'>
  R object with classes: ('matrix',) mapped to:
<Matrix - Python:0x0000000004FCF388 / R:0x0000000010C5B2B8>
[5.235426, -0.023640]
  alpha: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x00000000103B4588 / R:0x0000000011F6B6B0>
[1.000000]
  L: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x00000000103B4BC8 / R:0x00000000114FB6F0>
[118.877731]
  ...
  theta: <class 'rpy2.robjects.vectors.IntVector'>
  R object with classes: ('integer',) mapped to:
<IntVector - Python:0x0000000011441248 / R:0x0000000011F6B980>
[       1]
  alpha: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('logLik',) mapped to:
<FloatVector - Python:0x00000000114415C8 / R:0x000000000EE447E0>
[118.877731]
R object with classes: ('movMF',) mapped to:
<ListVector - Python:0x00000000103B4448 / R:0x0000000010CB2380>
[Matrix, Float..., Float..., ..., IntVe..., Float..., ListV...]
</code>```

I want to know, how can I access to its inner values?

So far I can only play with result[0], not sure if this is the right way.

In R environment, this is the data structure:

and I can access the value like result$theta

答:
I found two ways of doing this.
Suppose your list is:

```<code>a_list <- list(x1 = c(1,2,3), x2 = c(4,5,6))
</code>```

You can access a_list$x1 via rpy2 by doing:

```<code>print(a_list.rx2('x1'))
</code>```

or ( https://rpy2.github.io/doc/latest/html/vector.html#assigning-r-style ):

```<code>print(a_list[a_list.names.index('x1')])
</code>```

Body:
I can fit a model in Jupyter/Python using rpy2, however, the result returned is a list type value in R. For example

# Cell #1, load rpy2 and re
%load_ext rpy2.ipython
%R require(ggplot2)
%R require(movMF)

# Cell #2, generate data from Python
from scipy.stats import vonmises
kappa = 5
samples = vonmises.rvs(kappa, size=100)
data = [cos(samples), sin(samples)]

# Cell #3, fit model using R and rpy2
%%R -i data -o result
result = movMF(data, 1, nruns = 10)

# Cell #4, print result
print(result)

The result looks like this:

If I type result it returns

R object with classes: ('movMF',) mapped to:
<ListVector - Python:0x00000000103B4448 / R:0x0000000010CB2380>
[Matrix, Float..., Float..., ..., IntVe..., Float..., ListV...]
  theta: <class 'rpy2.robjects.vectors.Matrix'>
  R object with classes: ('matrix',) mapped to:
<Matrix - Python:0x0000000004FCF388 / R:0x0000000010C5B2B8>
[5.235426, -0.023640]
  alpha: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x00000000103B4588 / R:0x0000000011F6B6B0>
[1.000000]
  L: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x00000000103B4BC8 / R:0x00000000114FB6F0>
[118.877731]
  ...
  theta: <class 'rpy2.robjects.vectors.IntVector'>
  R object with classes: ('integer',) mapped to:
<IntVector - Python:0x0000000011441248 / R:0x0000000011F6B980>
[       1]
  alpha: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('logLik',) mapped to:
<FloatVector - Python:0x00000000114415C8 / R:0x000000000EE447E0>
[118.877731]
R object with classes: ('movMF',) mapped to:
<ListVector - Python:0x00000000103B4448 / R:0x0000000010CB2380>
[Matrix, Float..., Float..., ..., IntVe..., Float..., ListV...]

I want to know, how can I access to its inner values?

So far I can only play with result[0], not sure if this is the right way.

In R environment, this is the data structure:

and I can access the value like result$theta

Body:
I found two ways of doing this.
Suppose your list is:

a_list <- list(x1 = c(1,2,3), x2 = c(4,5,6))

You can access a_list$x1 via rpy2 by doing:

print(a_list.rx2('x1'))

or ( https://rpy2.github.io/doc/latest/html/vector.html#assigning-r-style ):

print(a_list[a_list.names.index('x1')])