问:
MySQL: Expression of generated column contains disallowed function
I have a curious problem with MySQL. Specifically with Stored Procedures and Generated Columns.

The Problem

With the Stored Procedure, an exception is thrown:

Error Code: 3102. Expression of generated column 'unique_name' contains a disallowed function.

However, if I run the query (the stored procedure calls the same query), it works fine. Subsequently, the stored procedure works properly (well, most of the time anyway). What I mean is:

There were no changes made to the table structure in the time these queries were fired.

Any help, explanation and advice on this would be really appreciated. Thanks!

Additional Details

MySQL version: 5.7.20-0ubuntu0.17.10.1 (Ubuntu)

Table schema:

The Stored Procedure in question:

```<code>DELIMITER //
CREATE PROCEDURE createPost
(IN author INT(11), IN title CHAR(100), IN content LONGTEXT)
BEGIN
    INSERT INTO `blog`.`posts` (`author`, `title`, `content`) VALUES (author, title, content);
    SELECT last_insert_id() as last_insert_id;
END //
DELIMITER ;
</code>```

How I call it:

```<code>CALL createPost('1','223','12');
</code>```

The Expression for the Generated Column (unique_name):

```<code>replace(concat(`title`,'-',`date_time`),' ','_')
</code>```

答:
Failing to make generated columns work, I decided to work around it. Changing the unique_name column to non-generated column (prototyping phase, so dropping the table was an option), I decided to create the entry, then update it in the stored procedure, like so:

```<code>DELIMITER //
CREATE PROCEDURE createPost
(IN author INT(11), IN title CHAR(100), IN content LONGTEXT)
BEGIN
    INSERT INTO `blog`.`posts` (`author`, `title`, `content`) VALUES (author, title, content);
    UPDATE `blog`.`posts`
    SET `posts`.`unique_name` = replace(concat(`title`,'-',SUBSTR(UUID(),1,8)),' ','_')
    WHERE `posts`.`post_id` = last_insert_id();
    SELECT last_insert_id() as last_insert_id;
END //
DELIMITER ;
</code>```

It seems to be working alright now. My best guess is that generated columns don't play nicely with timestamps. Any insight/feedback into the correctness of my approach would still be appreciated. Cheers :)

Body:
I have a curious problem with MySQL. Specifically with Stored Procedures and Generated Columns.

The Problem

With the Stored Procedure, an exception is thrown:

Error Code: 3102. Expression of generated column 'unique_name' contains a disallowed function.

However, if I run the query (the stored procedure calls the same query), it works fine. Subsequently, the stored procedure works properly (well, most of the time anyway). What I mean is:

There were no changes made to the table structure in the time these queries were fired.

Any help, explanation and advice on this would be really appreciated. Thanks!

Additional Details

MySQL version: 5.7.20-0ubuntu0.17.10.1 (Ubuntu)

Table schema:

The Stored Procedure in question:

DELIMITER //
CREATE PROCEDURE createPost
(IN author INT(11), IN title CHAR(100), IN content LONGTEXT)
BEGIN
    INSERT INTO `blog`.`posts` (`author`, `title`, `content`) VALUES (author, title, content);
    SELECT last_insert_id() as last_insert_id;
END //
DELIMITER ;

How I call it:

CALL createPost('1','223','12');

The Expression for the Generated Column (unique_name):

replace(concat(`title`,'-',`date_time`),' ','_')

Body:
Failing to make generated columns work, I decided to work around it. Changing the unique_name column to non-generated column (prototyping phase, so dropping the table was an option), I decided to create the entry, then update it in the stored procedure, like so:

DELIMITER //
CREATE PROCEDURE createPost
(IN author INT(11), IN title CHAR(100), IN content LONGTEXT)
BEGIN
    INSERT INTO `blog`.`posts` (`author`, `title`, `content`) VALUES (author, title, content);
    UPDATE `blog`.`posts`
    SET `posts`.`unique_name` = replace(concat(`title`,'-',SUBSTR(UUID(),1,8)),' ','_')
    WHERE `posts`.`post_id` = last_insert_id();
    SELECT last_insert_id() as last_insert_id;
END //
DELIMITER ;

It seems to be working alright now. My best guess is that generated columns don't play nicely with timestamps. Any insight/feedback into the correctness of my approach would still be appreciated. Cheers :)


来源: stackexchange

问:
Django has no attribute 'GeoManager' issue
```<code>from django.db import models
from django.contrib.gis.db import models
location = models.PointField(srid=4326,null=True,blank=True)
objects = models.GeoManager()
</code>```

I am hosting my Django project on AWS server. I am unable to run the project because of the error I added below, but I implemented the same project in my Ubuntu system and it's working fine.

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f527104b6a8> Traceback (most recent call last): File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/ubuntu/django_env/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 10, in <module> class BusStop(models.Model): File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 17, in BusStop objects = models.GeoManager() AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager'

答:
You could try:

```<code>from django.contrib.gis.db.models.manager import GeoManager
</code>```

Also you'll want to avoid situations like this

```<code>from django.db import models
from django.contrib.gis.db import models
</code>```

The problem is this, you've imported two models modules - which one does Python use when you try to use models.Whatever?

Try something like this:

```<code>from django.db import models
from django.contrib.gis.db import models as gis_models
</code>```

ContentLicense: CC BY-SA 3.0

Body:
from django.db import models
from django.contrib.gis.db import models
location = models.PointField(srid=4326,null=True,blank=True)
objects = models.GeoManager()

I am hosting my Django project on AWS server. I am unable to run the project because of the error I added below, but I implemented the same project in my Ubuntu system and it's working fine.

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f527104b6a8> Traceback (most recent call last): File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/ubuntu/django_env/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 10, in <module> class BusStop(models.Model): File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 17, in BusStop objects = models.GeoManager() AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager'

Body:
You could try:

from django.contrib.gis.db.models.manager import GeoManager

Also you'll want to avoid situations like this

from django.db import models
from django.contrib.gis.db import models

The problem is this, you've imported two models modules - which one does Python use when you try to use models.Whatever?

Try something like this:

from django.db import models
from django.contrib.gis.db import models as gis_models


问:
Find which is installed gcc or clang or both
I need to locate gcc or clang, whatever is installed, from my nodejs script. If both are installed I need to find both. How to do that?

In bash you usually just type which gcc. I know I can enumerate process.env.PATH.split(':').map(......fs.stat()......) but is there a easier builtin way?

答:
```<code>var fs = require('fs')
var path = require('path')

function find_binaries(binaries) {
    var dirs = process.env.PATH.split(path.delimiter)
    var result = {}
    binaries.forEach(b=>result[b] = false)
    dirs.forEach(dir => {
        try {
            binaries.map(binary => {
                var f = dir + path.sep + binary
                var s = fs.statSync(f)
                result[binary] = true
            })
        }
        catch (e) {
            return
        }
    })
    return result
}

exports = find_binaries

console.log(find_binaries(['clang', 'gcc']))
</code>```

returns:

```<code>{clang: true, gcc: false}
</code>```

Body:
var fs = require('fs')
var path = require('path')

function find_binaries(binaries) {
    var dirs = process.env.PATH.split(path.delimiter)
    var result = {}
    binaries.forEach(b=>result[b] = false)
    dirs.forEach(dir => {
        try {
            binaries.map(binary => {
                var f = dir + path.sep + binary
                var s = fs.statSync(f)
                result[binary] = true
            })
        }
        catch (e) {
            return
        }
    })
    return result
}

exports = find_binaries

console.log(find_binaries(['clang', 'gcc']))

returns:

{clang: true, gcc: false}


问:
NSNotification concept - what piece of code goes where?
Part of me thinks I understand the NSNotification concept. It's a centralized broadcast system with string based notifications. Post on one side, observe on one or multiple other sides and act accordingly. Another part of me though, the part that has to write the code, gets confused every time I need a notification. What piece of code goes into which header/implementation, what files actually do the observing and how do I keep it from becoming a mess? Time to straighten it out, will you help me verify these assumptions? I'm fairly confident up to number 4, but number 5 hits the confusion jackpot.

NSNotifications are created with help from the [NSNotification defaultCenter], one does not alloc/init a NSNotification. Correct?

The object performing the postNofification feat always passes self into the posting code: [[NSNotificationCenter defaultCenter] postNotificationName:@"note name" object:self]. Correct?

Event bubbling exists in other languages, but not in Objective-C with NSNotification. You don't pass along notifications, you make the notification name specific enough for the global broadcast. Correct?

If you still want to pass along a notification posted by object A, you observe it in B, handle it and post a new, more specific notification for object C to observe. Eg. @"MenuItemTapped" from A to B, and @"NavigateTo" from B to C. Correct?

The name of a notification is a NSString. Because both the poster and the observer want to avoid typos, we store the NSString constant in a [extern const|define|class method|none of the above]. Could you help me pick one?

One attempt was to create something like a NotificationNames.h file, which would contain all the extern NSString *const NOTE_NAME declarations. Yet that undermines the portability of a notification.

Another attempt was to subclass NSNotification (with an XCode template to keep the creation fast), but because this concept is taken from subclassing the Event-class in AS3, it seemed very un-objective-c-ish. There's also the weirdness that you can't call [super init] on a NSNotification, so things started to get out of hand.

My troubles with this one arise from the cumbersome #import statements. How to minimize typo's, yet keep the constants/defines portable?

答:
You can directly create NSNotification objects if you so wish. postNotificationName:object: is just a convenience method that creates, configures and posts a notification object for you.

You can pass any object you like. Its purpose is to allow notification subscribers to only receive notifications about a particular object, so ideally you pass in the object the notification is about, which will often - but not always - be self.

Notifcations are not events. They're global broadcasts within the application.

You don't send notifications to a particular object - They're broadcasts. If you want to send a message to a particular object, you just call a method on that object.

Externs in the header file are fine.

ContentLicense: CC BY-SA 2.5


问:
Spying in Blue prism
I am using SAP mode for spying the elements in SAP GUI.

I want to click on a label in which label will be the input parameter.

For instance, If i pass "Customer", then Customer label should be clicked.

But label text field comes under Informational note. Captured by Application navigator - Informational Note is disabled

Please suggest.

答:
The BluePrism SAP Mode is connecting with SAP using SAP Scripting language. The standard queries in SAP look like that:

```<code>session.findbyid("ID").Activate
</code>```

The BluePrism implementation is the simplest one possible - they are using only the standard queries. BluePrism always finds the items in SAP using exact ID. Because of that, using standard BluePrism spying tool, it is impossible to search for items using different kind of parameters (e.g. label, position etc. etc).

If you'd like to implement something like that, then you'll need to:

Create a new object (we call it SAP - Utility)

Connect to SAP using SAP API

Use applicable SAP scripting method. session.FindByName() or session.FindByLabel()

That's no easy task!

Title: Spying in Blue prism

Body:
The BluePrism SAP Mode is connecting with SAP using SAP Scripting language. The standard queries in SAP look like that:

session.findbyid("ID").Activate

The BluePrism implementation is the simplest one possible - they are using only the standard queries. BluePrism always finds the items in SAP using exact ID. Because of that, using standard BluePrism spying tool, it is impossible to search for items using different kind of parameters (e.g. label, position etc. etc).

If you'd like to implement something like that, then you'll need to:

Create a new object (we call it SAP - Utility)

Connect to SAP using SAP API

Use applicable SAP scripting method. session.FindByName() or session.FindByLabel()

That's no easy task!


问:
Loading images to UITableViewCell and rounding corners using Alamofire
Alamofire has a very convenient method to load images directly from a URL as a UIImageView extension.

```<code>cell.avatarImageView.af_setImageWithURL(downloadURL)
</code>```

I'd also like to round the corners of the image. AlamofireImage has a method to do this as well (it's a UIImage extension),

```<code>image.af_imageRoundedIntoCircle()
</code>```

However is there a way to use both of these methods at once? First method directly calls on UIImageView not UIImage so I'm unable to use it.

If I call something like this just after the  af_setImageWithURL call,

```<code>cell.avatarImageView.image = cell.avatarImageView.image?.af_imageRoundedIntoCircle()
</code>```

It works only when tableView cells are redrawing. It has no effect on already visible cells.

Are there any other methods to achieve this? or Is there a workaround for this?

答:
yes, there is a method for that:

```<code>public func af_setImage(
        withURLRequest urlRequest: URLRequestConvertible,
        placeholderImage: UIImage? = nil,
        filter: ImageFilter? = nil,
        progress: ImageDownloader.ProgressHandler? = nil,
        progressQueue: DispatchQueue = DispatchQueue.main,
        imageTransition: ImageTransition = .noTransition,
        runImageTransitionIfCached: Bool = false,
        completion: ((DataResponse<UIImage>) -> Void)? = nil)
</code>```

You should specify CircleFilter() as filter parameter for circular image view or RoundedCornersFilter(radius: CGFloat, divideRadiusByImageScale: Bool) if you would like to have rounded corners

Body:
Alamofire has a very convenient method to load images directly from a URL as a UIImageView extension.

cell.avatarImageView.af_setImageWithURL(downloadURL)

I'd also like to round the corners of the image. AlamofireImage has a method to do this as well (it's a UIImage extension),

image.af_imageRoundedIntoCircle()

However is there a way to use both of these methods at once? First method directly calls on UIImageView not UIImage so I'm unable to use it.

If I call something like this just after the  af_setImageWithURL call,

cell.avatarImageView.image = cell.avatarImageView.image?.af_imageRoundedIntoCircle()

It works only when tableView cells are redrawing. It has no effect on already visible cells.

Are there any other methods to achieve this? or Is there a workaround for this?

Body:
yes, there is a method for that:

public func af_setImage(
        withURLRequest urlRequest: URLRequestConvertible,
        placeholderImage: UIImage? = nil,
        filter: ImageFilter? = nil,
        progress: ImageDownloader.ProgressHandler? = nil,
        progressQueue: DispatchQueue = DispatchQueue.main,
        imageTransition: ImageTransition = .noTransition,
        runImageTransitionIfCached: Bool = false,
        completion: ((DataResponse<UIImage>) -> Void)? = nil)

You should specify CircleFilter() as filter parameter for circular image view or RoundedCornersFilter(radius: CGFloat, divideRadiusByImageScale: Bool) if you would like to have rounded corners


问:
How to use values from that is obtained from a function call within a function in javascript?
I am trying to figure out how to use values from a function call (Bmi in BMI) within another function (HealthCat) and I'm trying to use the values obtained to perform control flow to get desired output onto my html. However, I am not sure how can I utilize the values from the double function call. Help is greatly appreciated! thx in advance!

Here is my html:

```<code><!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="css/styles.css">
    <title>BMI Calculator</title>
</head>

<body>
    <h1>BMI Calculator</h1>
    <p>
      <label>Enter weight:</label>
      <input type="text" id="weight" placeholder = "Enter your weight in kg">
    </p>

    <p>
      <label>Enter height:</label>
      <input type="text" id="height" placeholder="Enter your height in m">
    </p>

    <!--Display-->
    <input type="button" onclick="BMI()" value="BMI"/>
    <p id="result"></p>

    <input type="button" onclick="HealthCat()" value="HealthCat"/>
    <p id="Hresult"></p>

    <script src="bmiScript.js"></script>
</body>
</html>
</code>```

And here is my javascript:

```<code>function BMI(){
   var Weight = document.getElementById("weight").value;
   var Height = document.getElementById("height").value;
   var Bmi = Weight/(Height*Height);
   document.getElementById("result").innerHTML = Bmi;
}

function HealthCat(){
   BMI();
   if(Bmi<18.50){
      document.getElementById("Hresult").innerHTML="Under weight";

   }else if (Bmi>18.5 && Bmi <23) {
      document.getElementById("Hresult").innerHTML="Normal weight";

   }else if (Bmi>23 && Bmi <27.5) {
      document.getElementById("Hresult").innerHTML="Over weight";

   }else if (Bmi>27.5) {
      document.getElementById("Hresult").innerHTML="Obese";
   }
}
</code>```

答:
You can't use the value of a local variable in one function from another function. Once the execution of a function completes, the local variables are destroyed and can no longer be used. To use the Bmi variable from outside the BMI function, you need to return the variable so that the calling function can use it:

```<code>function BMI(){
   var Weight = document.getElementById("weight").value;
   var Height = document.getElementById("height").value;
   var Bmi =  Weight/(Height*Height);
   document.getElementById("result").innerHTML =Bmi;
   return Bmi; // Return the Bmi value.
}

function HealthCat(){
   var Bmi = BMI(); // Use the returned Bmi value
   if(Bmi<18.50){
      document.getElementById("Hresult").innerHTML="Under weight";

   }else if (Bmi>18.5 && Bmi <23) {
      document.getElementById("Hresult").innerHTML="Normal weight";

   }else if (Bmi>23 && Bmi <27.5) {
      document.getElementById("Hresult").innerHTML="Over weight";

   }else if (Bmi>27.5) {
      document.getElementById("Hresult").innerHTML="Obese";
   }
}
</code>```

Body:
I am trying to figure out how to use values from a function call (Bmi in BMI) within another function (HealthCat) and I'm trying to use the values obtained to perform control flow to get desired output onto my html. However, I am not sure how can I utilize the values from the double function call. Help is greatly appreciated! thx in advance!

Here is my html:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="stylesheet" href="css/styles.css">
    <title>BMI Calculator</title>

BMI Calculator

      Enter weight:
      <input type="text" id="weight" placeholder = "Enter your weight in kg">

      Enter height:
      <input type="text" id="height" placeholder="Enter your height in m">

    <input type="button" onclick="BMI()" value="BMI"/>

    <input type="button" onclick="HealthCat()" value="HealthCat"/>

And here is my javascript:

function BMI(){
   var Weight = document.getElementById("weight").value;
   var Height = document.getElementById("height").value;
   var Bmi = Weight/(Height*Height);
   document.getElementById("result").innerHTML = Bmi;
}

function HealthCat(){
   BMI();
   if(Bmi<18.50){
      document.getElementById("Hresult").innerHTML="Under weight";

   }else if (Bmi>18.5 && Bmi <23) {
      document.getElementById("Hresult").innerHTML="Normal weight";

   }else if (Bmi>23 && Bmi <27.5) {
      document.getElementById("Hresult").innerHTML="Over weight";

   }else if (Bmi>27.5) {
      document.getElementById("Hresult").innerHTML="Obese";
   }
}

Body:
You can't use the value of a local variable in one function from another function. Once the execution of a function completes, the local variables are destroyed and can no longer be used. To use the Bmi variable from outside the BMI function, you need to return the variable so that the calling function can use it:

function BMI(){
   var Weight = document.getElementById("weight").value;
   var Height = document.getElementById("height").value;
   var Bmi =  Weight/(Height*Height);
   document.getElementById("result").innerHTML =Bmi;
   return Bmi; // Return the Bmi value.
}

function HealthCat(){
   var Bmi = BMI(); // Use the returned Bmi value
   if(Bmi<18.50){
      document.getElementById("Hresult").innerHTML="Under weight";

   }else if (Bmi>18.5 && Bmi <23) {
      document.getElementById("Hresult").innerHTML="Normal weight";

   }else if (Bmi>23 && Bmi <27.5) {
      document.getElementById("Hresult").innerHTML="Over weight";

   }else if (Bmi>27.5) {
      document.getElementById("Hresult").innerHTML="Obese";
   }
}


问:
How to sum/multiply a split of an item in a listbox?
So I am making a program in which you can select products from a combo box, select the quantity and it will return with the price and the quantity in a list box.

However, I want to be able to multiply the price of a product in each line by the quantity, then add up all of the lines cost to figure out a "total cost". How would I be able to do it?

Here is the form:

TL;DR How to multiply the price of a product for each line, then add up all of the total prices in each line. Thank you heaps!!

Here is my code: IGNORE OLEDB PART - SOME OF THE NAMING IS INCORRECT AS IT IS A WIP

```<code>Imports System.Data.OleDb
Public Class frmOrderProduct
    Dim iPadCasePrice As String
    Dim iPad2Price As String
    Dim prod_list As List(Of String)

    Private Sub frmOrderProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        cmboxProduct.Items.Add("iPad Case")
        cmboxProduct.Items.Add("iPad 2")

        iPadCasePrice = "$20.00"
        iPad2Price = "$200.00"

        txtUsername.Text = frmLogin.txtUsername.Text

    End Sub

    Private Sub btnAddToCart_Click(sender As Object, e As EventArgs) Handles btnAddToCart.Click

        If cmboxProduct.SelectedItem = "" Or txtQuantity.Text = "" Then
            MsgBox("Please fill out all required fields", MsgBoxStyle.OkOnly, "Invalid entered data")
        Else
            ListBoxCart.Items.Add("x" & txtQuantity.Text & " " & cmboxProduct.SelectedItem & " " & txtPriceEach.Text)

            'txtShoppingCart.AppendText("x" & txtQuantity.Text & " " & Product1 & Environment.NewLine)
        End If
    End Sub

    Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles txtQuantity.KeyPress

        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                e.Handled = True
            End If
        End If

    End Sub

    Private Sub btnOrderProducts_Click(sender As Object, e As EventArgs) Handles btnOrderProducts.Click

        Dim numberOfItems = ListBoxCart.Items.Count
        For Each item As String In ListBoxCart.Items

            Try

                cm = New OleDbCommand
                With cm
                    .Connection = cn
                    .CommandType = CommandType.Text
                    .CommandText = "INSERT INTO tblOrders ([ProductName],[Quantity],[PriceEach],[TotalPrice],[Username]) VALUES (@ProductName,@Quantity,@PriceEach,@TotalPrice,@Username)"

                    prod_list = item.Split(" ").ToList
                    Dim prod_name = prod_list.ElementAt(1)
                    Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))
                    Dim price_each = prod_list.ElementAt(2)

                    .Parameters.Add(New OleDbParameter("@ProductName", OleDbType.VarChar, 255, prod_name))
                    .Parameters.Add(New OleDbParameter("@Quantity", OleDbType.VarChar, 255, prod_quantity))
                    .Parameters.Add(New OleDbParameter("@PriceEach", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@TotalPrice", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@Username", OleDbType.VarChar, 255, txtUsername.Text))
                    prod_list = New List(Of String)

                    cm.Parameters("@ProductName").Value = prod_name
                    cm.Parameters("@Quanity").Value = prod_quantity
                    cm.Parameters("@PriceEach").Value = price_each
                    cm.Parameters("@TotalPrice").Value =
                    cm.Parameters("@Username").Value = txtUsername.Text

                    cm.ExecuteNonQuery()
                    MsgBox("Record saved.", MsgBoxStyle.Information)
                    cmboxProduct.SelectedItem = ""
                    txtQuantity.Text = ListBoxCart.Text = ""

                    Exit Sub
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try

        Next

    End Sub

    Private Sub btnClearCart_Click(sender As Object, e As EventArgs) Handles btnClearCart.Click

        ListBoxCart.Items.Clear()

    End Sub

    Private Sub cmboxProduct_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmboxProduct.SelectedIndexChanged

        If cmboxProduct.SelectedItem = "iPad Case" Then
            txtPriceEach.Text = iPadCasePrice
        End If

        If cmboxProduct.SelectedItem = "iPad 2" Then
            txtPriceEach.Text = iPad2Price
        End If

    End Sub
End Class
</code>```

答:
You can bind a List(Of ...) to the ListBox and sum up the items based on the list.

Here's an example with a list of Tuple.

Of course you can create your own Class and use it instead of Tuple:

```<code>'Initialize a new list
Dim CartList As New List(Of Tuple(Of String, Decimal, Decimal))

'Add Items to the list (product-name, cost, quantity)
CartList.Add(New Tuple(Of String, Decimal, Decimal)("iPad Case", 20, 1))
CartList.Add(New Tuple(Of String, Decimal, Decimal)("iPad 2", 200, 2))

'Set the first item of the Tuple (the String) as DisplayMember
'(This will be the item-text shown inside the ListBox)
ListBoxCart.DisplayMember = "Item1"
ListBoxCart.ValueMember = "Item2"
ListBoxCart.DataSource = CartList 'Bind the list to the Listbox

Dim SumOfAllItems As Decimal

'Get the total of all items with Linq
'(This line calculates the sum of all items (cost * quantity)
'and assigns the value to the variable 'SumOfAllItems')
SumOfAllItems = ListBoxCart.Items.Cast(Of Tuple(Of String, Decimal, Decimal)).Sum(Function(itm) itm.Item2 * itm.Item3)

'Loop through the items in the list
'and print quantity, product-name and total to the console
For Each itm As Tuple(Of String, Decimal, Decimal) In CartList
    Console.WriteLine(itm.Item3 & "x " & itm.Item1 & " -> Total: " & (itm.Item2 * itm.Item3))
Next
</code>```

Note:
After adding a new item to the list you have to re-bind the datasource of the listbox each time, otherwise the list won't refresh:

```<code>ListBoxCart.DataSource = CartList
</code>```

Body:
So I am making a program in which you can select products from a combo box, select the quantity and it will return with the price and the quantity in a list box.

However, I want to be able to multiply the price of a product in each line by the quantity, then add up all of the lines cost to figure out a "total cost". How would I be able to do it?

Here is the form:

TL;DR How to multiply the price of a product for each line, then add up all of the total prices in each line. Thank you heaps!!

Here is my code: IGNORE OLEDB PART - SOME OF THE NAMING IS INCORRECT AS IT IS A WIP

Imports System.Data.OleDb
Public Class frmOrderProduct
    Dim iPadCasePrice As String
    Dim iPad2Price As String
    Dim prod_list As List(Of String)

    Private Sub frmOrderProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        cmboxProduct.Items.Add("iPad Case")
        cmboxProduct.Items.Add("iPad 2")

        iPadCasePrice = "$20.00"
        iPad2Price = "$200.00"

        txtUsername.Text = frmLogin.txtUsername.Text

    End Sub

    Private Sub btnAddToCart_Click(sender As Object, e As EventArgs) Handles btnAddToCart.Click

        If cmboxProduct.SelectedItem = "" Or txtQuantity.Text = "" Then
            MsgBox("Please fill out all required fields", MsgBoxStyle.OkOnly, "Invalid entered data")
        Else
            ListBoxCart.Items.Add("x" & txtQuantity.Text & " " & cmboxProduct.SelectedItem & " " & txtPriceEach.Text)

            'txtShoppingCart.AppendText("x" & txtQuantity.Text & " " & Product1 & Environment.NewLine)
        End If
    End Sub

    Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles txtQuantity.KeyPress

        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                e.Handled = True
            End If
        End If

    End Sub

    Private Sub btnOrderProducts_Click(sender As Object, e As EventArgs) Handles btnOrderProducts.Click

        Dim numberOfItems = ListBoxCart.Items.Count
        For Each item As String In ListBoxCart.Items

            Try

                cm = New OleDbCommand
                With cm
                    .Connection = cn
                    .CommandType = CommandType.Text
                    .CommandText = "INSERT INTO tblOrders ([ProductName],[Quantity],[PriceEach],[TotalPrice],[Username]) VALUES (@ProductName,@Quantity,@PriceEach,@TotalPrice,@Username)"

                    prod_list = item.Split(" ").ToList
                    Dim prod_name = prod_list.ElementAt(1)
                    Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))
                    Dim price_each = prod_list.ElementAt(2)

                    .Parameters.Add(New OleDbParameter("@ProductName", OleDbType.VarChar, 255, prod_name))
                    .Parameters.Add(New OleDbParameter("@Quantity", OleDbType.VarChar, 255, prod_quantity))
                    .Parameters.Add(New OleDbParameter("@PriceEach", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@TotalPrice", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@Username", OleDbType.VarChar, 255, txtUsername.Text))
                    prod_list = New List(Of String)

                    cm.Parameters("@ProductName").Value = prod_name
                    cm.Parameters("@Quanity").Value = prod_quantity
                    cm.Parameters("@PriceEach").Value = price_each
                    cm.Parameters("@TotalPrice").Value =
                    cm.Parameters("@Username").Value = txtUsername.Text

                    cm.ExecuteNonQuery()
                    MsgBox("Record saved.", MsgBoxStyle.Information)
                    cmboxProduct.SelectedItem = ""
                    txtQuantity.Text = ListBoxCart.Text = ""

                    Exit Sub
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try

        Next

    End Sub

    Private Sub btnClearCart_Click(sender As Object, e As EventArgs) Handles btnClearCart.Click

        ListBoxCart.Items.Clear()

    End Sub

    Private Sub cmboxProduct_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmboxProduct.SelectedIndexChanged

        If cmboxProduct.SelectedItem = "iPad Case" Then
            txtPriceEach.Text = iPadCasePrice
        End If

        If cmboxProduct.SelectedItem = "iPad 2" Then
            txtPriceEach.Text = iPad2Price
        End If

    End Sub
End Class

Body:
You can bind a List(Of ...) to the ListBox and sum up the items based on the list.

Here's an example with a list of Tuple.

Of course you can create your own Class and use it instead of Tuple:

'Initialize a new list
Dim CartList As New List(Of Tuple(Of String, Decimal, Decimal))

'Add Items to the list (product-name, cost, quantity)
CartList.Add(New Tuple(Of String, Decimal, Decimal)("iPad Case", 20, 1))
CartList.Add(New Tuple(Of String, Decimal, Decimal)("iPad 2", 200, 2))

'Set the first item of the Tuple (the String) as DisplayMember
'(This will be the item-text shown inside the ListBox)
ListBoxCart.DisplayMember = "Item1"
ListBoxCart.ValueMember = "Item2"
ListBoxCart.DataSource = CartList 'Bind the list to the Listbox

Dim SumOfAllItems As Decimal

'Get the total of all items with Linq
'(This line calculates the sum of all items (cost * quantity)
'and assigns the value to the variable 'SumOfAllItems')
SumOfAllItems = ListBoxCart.Items.Cast(Of Tuple(Of String, Decimal, Decimal)).Sum(Function(itm) itm.Item2 * itm.Item3)

'Loop through the items in the list
'and print quantity, product-name and total to the console
For Each itm As Tuple(Of String, Decimal, Decimal) In CartList
    Console.WriteLine(itm.Item3 & "x " & itm.Item1 & " -> Total: " & (itm.Item2 * itm.Item3))
Next

Note:
After adding a new item to the list you have to re-bind the datasource of the listbox each time, otherwise the list won't refresh:

ListBoxCart.DataSource = CartList


问:
How do I change TextView Value inside Java Code?
I am working on a android program. A user clicks on a button I do some math and I would like to change the values that I have on my view in some TextView objects.  Can someone please tell me how to do it in my code?</p>

答:
First we need to find a Button:

```<code>Button mButton = (Button) findViewById(R.id.my_button);
</code>```

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

```<code>mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});
</code>```

Body:
First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});


问:
Make screen take same proportion of screen independently of resolution
I would like for my website to take the whole page height and without scrolling bar. But if i set the height in px it will change depending on the screen resolution. How can I do it so that is takes the whole page independently of the screen resolution?</p>

答:
You are looking for the view height unit.

1vh is relative to 1% of the height of the viewport, so if you set it to 100 it will be exactly the height of the users viewport.

```<code>body {
  height: 100vh;
}
</code>```

Body:
You are looking for the view height unit.

1vh is relative to 1% of the height of the viewport, so if you set it to 100 it will be exactly the height of the users viewport.

body {
  height: 100vh;
}


问:
SAS Library not showing all datasets existing in unix folder
I have unix folder containing about 700 sas datasets.
When I assign a library to this folder, I am able to view only 30 of the 700 datasets. I checked unix permissions for the datasets and see no difference between the ones that are visible and the ones that are not.

1) This is a pre-assigned library in SAS Management console.
2) The Datasets are still accessible if i name them in data and proc steps,Just not visible in the library.

答: Please check the library references for local and unix libraries. they should be exactly similar. then only we can see the datasets in window environment. </p>


问:
AVPlayer not stop playing when going back to the previous view
I have two View Controllers a TableViewController where I have a list of musics and a UIViewController where it plays the music. The music automatically plays when the view is loaded and pauses when the pause button is pressed.

However whenever I go back to the previous TableViewController to select another music, the music continues to play. And if i select another music, both of them are playing together.

My Codes:

```<code>var audioplayer = AVPlayer()

override func viewDidLoad() {
        super.viewDidLoad()

    play()
}

func play(){

    var songUrl = songList[selectedItem].url

    audioplayer = AVPlayer(url: songUrl!)

    audioplayer.play()

}
</code>```

答: I already fixed my problem. I remove all player items in view controller and create new class for player. Now ıt ıs workıng smoothly.</p>

Body:
I have two View Controllers a TableViewController where I have a list of musics and a UIViewController where it plays the music. The music automatically plays when the view is loaded and pauses when the pause button is pressed.

However whenever I go back to the previous TableViewController to select another music, the music continues to play. And if i select another music, both of them are playing together.

My Codes:

var audioplayer = AVPlayer()

override func viewDidLoad() {
        super.viewDidLoad()

    play()
}

func play(){

    var songUrl = songList[selectedItem].url

    audioplayer = AVPlayer(url: songUrl!)

    audioplayer.play()

}


问:
Anaconda Installed but Cannot Launch Navigator
Anaconda (listed as "Python 3.6.0 (Anaconda 4.3.1 64 bit)" ) is in my programs and features list, but there is seeming no Anaconda Navigator desktop app, as their seems to be no icon on my desktop and I am unable to search for it through "Start". Could this be because I have the 32-bit version of Anaconda downloaded and I have a 64-bit OS (I thought I should do this because Python on my computer was 64-bit) or because I downloaded Anaconda under "users" instead of Desktop. I also downloaded Anaconda twice, if that could be causing some of the problem. I have a Windows 10 laptop, if that is any help.

答:
Open up a command terminal (CTRL+ALT+T)
and try running this command:

```<code>anaconda-navigator
</code>```

When I installed Anaconda, and read the website docs, they said that they tend to not add a file or menu path to run the navigator because there are so many different versions of different systems, instead they give the above terminal command to start the navigator GUI and advise on setting up a shortcut to do this process manually - if that works for you it shouldn't be too much trouble to do it this way - I do it like this personally

Body:
Open up a command terminal (CTRL+ALT+T)
and try running this command:

anaconda-navigator

When I installed Anaconda, and read the website docs, they said that they tend to not add a file or menu path to run the navigator because there are so many different versions of different systems, instead they give the above terminal command to start the navigator GUI and advise on setting up a shortcut to do this process manually - if that works for you it shouldn't be too much trouble to do it this way - I do it like this personally


问:
How can I use C++ boost geometry to create ring (donut) from two polgons?

I am trying to calculate the differences between 2 polygons (in fact, rectilinear shapes for simplicity). For example, shape1 has point list {0 0, 100, 0, 100 100, 0 100} and shape2 has point list {25 25, 75 25, 75 75, 25 75}.
So by concept, I expect "shape1 - shape2" will provide me with 4 rectangular boxes, which can make a ring or donut shape.  I don't know how to achieve that, but I found "boost" library online and tried it like this:

```<code>#include <iostream>
#include <list>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include <boost/foreach.hpp>

int main()
{
    typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

    polygon green, blue;

    boost::geometry::read_wkt( "POLYGON((0 0 100 0 100 100 0 100))", green);

    boost::geometry::read_wkt( "POLYGON((25 25 75 22 75 75 25 75))", blue);

    std::list<polygon> output;
    boost::geometry::difference(green, blue, output);

    int i = 0;
    std::cout << "green - blue:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    output.clear();
    boost::geometry::difference(blue, green, output);

    i = 0;
    std::cout << "blue - green:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    return 0;
}
</code>```

However, nothing was printed out ... My plan was to figure out a way to convert the output results to rectangular boxes {0 0 100 0 100 25 0 25} {0 75 100 75 100 100 0 100} {0 25 25 25 25 75 0 75}  and {75 25 100 25 100 75 75 75},but I feel frustrated that the above code not print out anything at all.

Could anyone give me some guidance?
I have attached a picture showing what I want to do. In fact, I have already had all the point coordinates to represent this donut, so maybe I can skip "difference() function" ?  If this is the case, the difficult part will be to convert the donut into rectangular segments. (Let us assume all polygons here are rectilinear shapes.)
Thanks.

答:
Your starting polygons do not have the required orientation. You can find this out for yourself with is_valid. Conveniently, you can use correct to fix the most common problems with your input data:

```<code>std::string reason;
if (!bg::is_valid(geometry, reason))
{
    std::cout << "Correcting " << bg::wkt(geometry) << " to ";
    bg::correct(geometry);
    std::cout << bg::wkt(geometry) << "\n";

    if (!bg::is_valid(geometry, reason))
        std::cout << "UNCORRECTIBLE: " << reason << "\n";
}
</code>```

When you do, you will find:

```<code>Correcting POLYGON((0 0,100 0,100 100,0 100,0 0)) to POLYGON((0 0,0 100,100 100,100 0,0 0))
Correcting POLYGON((25 25,75 22,75 75,25 75,25 25)) to POLYGON((25 25,25 75,75 75,75 22,25 25))
</code>```

Now, when you get the difference, you will get the expected outcome:

```<code>auto do_diff = [](std::string caption, auto const& a, auto const& b) {
    multi output;
    bg::difference(a, b, output);

    std::cout << caption << bg::wkt(output) << std::endl;
};

do_diff("green - blue:", green, blue);
do_diff("blue - green:", blue, green);
</code>```

Full Demo

Live On Coliru

```<code>#include <iostream>
#include <fstream>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>

#include <boost/foreach.hpp>

namespace bg = boost::geometry;

int main() {
    typedef bg::model::d2::point_xy<double> point;
    typedef bg::model::polygon<point> polygon;
    typedef bg::model::multi_polygon<polygon> multi;

    polygon green, blue;

    bg::read_wkt("POLYGON((0 0 100 0 100 100 0 100))", green);
    bg::read_wkt("POLYGON((25 25 75 22 75 75 25 75))", blue);

    auto test = [](polygon& geometry) {
        std::string reason;
        if (!bg::is_valid(geometry, reason))
        {
            std::cout << "Correcting " << bg::wkt(geometry) << " to ";
            bg::correct(geometry);
            std::cout << bg::wkt(geometry) << "\n";

            if (!bg::is_valid(geometry, reason))
                std::cout << "UNCORRECTIBLE: " << reason << "\n";
        }
    };

    test(green);
    test(blue);

    auto do_diff = [](std::string caption, polygon const& a, polygon const& b) {
        multi output;
        bg::difference(a, b, output);

        std::cout << caption << bg::wkt(output) << std::endl;
    };

    do_diff("green - blue:", green, blue);
    do_diff("blue - green:", blue, green);

    {
        std::ofstream svg("output.svg");
        boost::geometry::svg_mapper<point> mapper(svg, 400, 400);
        mapper.add(blue);
        mapper.add(green);

        mapper.map(blue, "fill-opacity:0.5;fill:rgb(0,0,153);stroke:rgb(0,0,200);stroke-width:2");
        mapper.map(green, "fill-opacity:0.5;fill:rgb(0,153,0);stroke:rgb(0,200,0);stroke-width:2");
    }
}
</code>```

Prints

```<code>Correcting POLYGON((0 0,100 0,100 100,0 100,0 0)) to POLYGON((0 0,0 100,100 100,100 0,0 0))
Correcting POLYGON((25 25,75 22,75 75,25 75,25 25)) to POLYGON((25 25,25 75,75 75,75 22,25 25))
green - blue:MULTIPOLYGON(((0 0,0 100,100 100,100 0,0 0),(25 25,75 22,75 75,25 75,25 25)))
blue - green:MULTIPOLYGON()
</code>```

And writes the svg for:

Body:
I am trying to calculate the differences between 2 polygons (in fact, rectilinear shapes for simplicity). For example, shape1 has point list {0 0, 100, 0, 100 100, 0 100} and shape2 has point list {25 25, 75 25, 75 75, 25 75}.
So by concept, I expect "shape1 - shape2" will provide me with 4 rectangular boxes, which can make a ring or donut shape.  I don't know how to achieve that, but I found "boost" library online and tried it like this:

#include <iostream>
#include <list>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include <boost/foreach.hpp>

int main()
{
    typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

    polygon green, blue;

    boost::geometry::read_wkt( "POLYGON((0 0 100 0 100 100 0 100))", green);

    boost::geometry::read_wkt( "POLYGON((25 25 75 22 75 75 25 75))", blue);

    std::list<polygon> output;
    boost::geometry::difference(green, blue, output);

    int i = 0;
    std::cout << "green - blue:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    output.clear();
    boost::geometry::difference(blue, green, output);

    i = 0;
    std::cout << "blue - green:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    return 0;
}

However, nothing was printed out ... My plan was to figure out a way to convert the output results to rectangular boxes {0 0 100 0 100 25 0 25} {0 75 100 75 100 100 0 100} {0 25 25 25 25 75 0 75}  and {75 25 100 25 100 75 75 75},but I feel frustrated that the above code not print out anything at all.

Could anyone give me some guidance?
I have attached a picture showing what I want to do. In fact, I have already had all the point coordinates to represent this donut, so maybe I can skip "difference() function" ?  If this is the case, the difficult part will be to convert the donut into rectangular segments. (Let us assume all polygons here are rectilinear shapes.)
Thanks.

Body:
Your starting polygons do not have the required orientation. You can find this out for yourself with is_valid. Conveniently, you can use correct to fix the most common problems with your input data:

std::string reason;
if (!bg::is_valid(geometry, reason))
{
    std::cout << "Correcting " << bg::wkt(geometry) << " to ";
    bg::correct(geometry);
    std::cout << bg::wkt(geometry) << "\n";

    if (!bg::is_valid(geometry, reason))
        std::cout << "UNCORRECTIBLE: " << reason << "\n";
}

When you do, you will find:

Correcting POLYGON((0 0,100 0,100 100,0 100,0 0)) to POLYGON((0 0,0 100,100 100,100 0,0 0))
Correcting POLYGON((25 25,75 22,75 75,25 75,25 25)) to POLYGON((25 25,25 75,75 75,75 22,25 25))

Now, when you get the difference, you will get the expected outcome:

auto do_diff = [](std::string caption, auto const& a, auto const& b) {
    multi output;
    bg::difference(a, b, output);

    std::cout << caption << bg::wkt(output) << std::endl;
};

do_diff("green - blue:", green, blue);
do_diff("blue - green:", blue, green);

Full Demo

Live On Coliru

#include <iostream>
#include <fstream>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>

#include <boost/foreach.hpp>

namespace bg = boost::geometry;

int main() {
    typedef bg::model::d2::point_xy<double> point;
    typedef bg::model::polygon<point> polygon;
    typedef bg::model::multi_polygon<polygon> multi;

    polygon green, blue;

    bg::read_wkt("POLYGON((0 0 100 0 100 100 0 100))", green);
    bg::read_wkt("POLYGON((25 25 75 22 75 75 25 75))", blue);

    auto test = [](polygon& geometry) {
        std::string reason;
        if (!bg::is_valid(geometry, reason))
        {
            std::cout << "Correcting " << bg::wkt(geometry) << " to ";
            bg::correct(geometry);
            std::cout << bg::wkt(geometry) << "\n";

            if (!bg::is_valid(geometry, reason))
                std::cout << "UNCORRECTIBLE: " << reason << "\n";
        }
    };

    test(green);
    test(blue);

    auto do_diff = [](std::string caption, polygon const& a, polygon const& b) {
        multi output;
        bg::difference(a, b, output);

        std::cout << caption << bg::wkt(output) << std::endl;
    };

    do_diff("green - blue:", green, blue);
    do_diff("blue - green:", blue, green);

    {
        std::ofstream svg("output.svg");
        boost::geometry::svg_mapper<point> mapper(svg, 400, 400);
        mapper.add(blue);
        mapper.add(green);

        mapper.map(blue, "fill-opacity:0.5;fill:rgb(0,0,153);stroke:rgb(0,0,200);stroke-width:2");
        mapper.map(green, "fill-opacity:0.5;fill:rgb(0,153,0);stroke:rgb(0,200,0);stroke-width:2");
    }
}

Prints

Correcting POLYGON((0 0,100 0,100 100,0 100,0 0)) to POLYGON((0 0,0 100,100 100,100 0,0 0))
Correcting POLYGON((25 25,75 22,75 75,25 75,25 25)) to POLYGON((25 25,25 75,75 75,75 22,25 25))
green - blue:MULTIPOLYGON(((0 0,0 100,100 100,100 0,0 0),(25 25,75 22,75 75,25 75,25 25)))
blue - green:MULTIPOLYGON()

And writes the svg for:


问:
C Language: I want to add all the positive integers when a negative number is inserted
I want to add all the positive integers when a negative number is entered.

Click for Example

```<code>int number;
int total;
int loopcount;
int a;
number = 0;
a = 0;
total = 0;

for(loopcount = 0; loopcount >=0; loopcount = loopcount + 1)
{
    printf("Enter Integer: ");
    scanf("%d", &number);
    a = number;

    if (a >= 0)
    {
        total = total + number;
    }
    else if(a < 0)
    {
        printf("Total positive int = %d\n", &total);
        break;
    }
}
</code>```

答:
The problem is this:

```<code>printf("Total positive int = %d\n", &total);
                                    ^
</code>```

Instead of printing value of total variable, you are printing the address of it. Remove &.
Correct way is:

```<code>printf("Total positive int = %d\n", total);
</code>```

Body:
I want to add all the positive integers when a negative number is entered.

Click for Example

int number;
int total;
int loopcount;
int a;
number = 0;
a = 0;
total = 0;

for(loopcount = 0; loopcount >=0; loopcount = loopcount + 1)
{
    printf("Enter Integer: ");
    scanf("%d", &number);
    a = number;

    if (a >= 0)
    {
        total = total + number;
    }
    else if(a < 0)
    {
        printf("Total positive int = %d\n", &total);
        break;
    }
}

Body:
The problem is this:

printf("Total positive int = %d\n", &total);
                                    ^

Instead of printing value of total variable, you are printing the address of it. Remove &.
Correct way is:

printf("Total positive int = %d\n", total);


问:
How to obtain the Table A rows that are not present in Table B with GORM without using an inList closure?
I have a domain definition which generates the following example for database table:

I want to do the following query: Obtain all domain objects related to Table A that are not present in Table B

I was using the inList closure as follow:

```<code>    List<DMiembro> m = DMiembro.list()

    List<DUsuario> usuarios = DUsuario.createCriteria().list(params) {
        if (m) {
            not {
                m*.usuario.id.collate(1000).each { def lista ->
                    or {
                        inList("id", lista)
                    }
                }
            }
        }
        eq("enabled", true)
        order("nombre", "asc")
    } as List<DUsuario>
</code>```

This works fine. However, data in DMiembro is growing to big. Now I am getting a database error related to the size of the query. And that's logical, because the number of parameters of the query is too large

So, is there another way to build a query for gathering Dusuario objects that are not present in DMiembro?

答:
Solution 1:
You can use GORM DetachedCriteria inside your criteria.

```<code>import grails.gorm.DetachedCriteria
List<DUsuario> usuarios = DUsuario.createCriteria().list(params) {
      not {
          'in'('id', new DetachedCriteria(DMiembro).build {
               projections {
                   property 'id'
               }
           })
      }
      eq("enabled", true)
      order("nombre", "asc")
} as List<DUsuario>
</code>```

As you can see, this will be a NOT IN SQL request, which isn't a good idea for performances. However, the request is more "understandable" and is still a good solution, no matter the volumetry (except for the request's execution time).

Solution 2:
Avoid the NOT IN operator with a LEFT JOIN or RIGHT JOIN and a NULL check on DMiembro table. See here for a solution with a left join as plain SQL.

Body:
I have a domain definition which generates the following example for database table:

I want to do the following query: Obtain all domain objects related to Table A that are not present in Table B

I was using the inList closure as follow:

    List<DMiembro> m = DMiembro.list()

    List<DUsuario> usuarios = DUsuario.createCriteria().list(params) {
        if (m) {
            not {
                m*.usuario.id.collate(1000).each { def lista ->
                    or {
                        inList("id", lista)
                    }
                }
            }
        }
        eq("enabled", true)
        order("nombre", "asc")
    } as List<DUsuario>

This works fine. However, data in DMiembro is growing to big. Now I am getting a database error related to the size of the query. And that's logical, because the number of parameters of the query is too large

So, is there another way to build a query for gathering Dusuario objects that are not present in DMiembro?

Body:
Solution 1:
You can use GORM DetachedCriteria inside your criteria.

import grails.gorm.DetachedCriteria
List<DUsuario> usuarios = DUsuario.createCriteria().list(params) {
      not {
          'in'('id', new DetachedCriteria(DMiembro).build {
               projections {
                   property 'id'
               }
           })
      }
      eq("enabled", true)
      order("nombre", "asc")
} as List<DUsuario>

As you can see, this will be a NOT IN SQL request, which isn't a good idea for performances. However, the request is more "understandable" and is still a good solution, no matter the volumetry (except for the request's execution time).

Solution 2:
Avoid the NOT IN operator with a LEFT JOIN or RIGHT JOIN and a NULL check on DMiembro table. See here for a solution with a left join as plain SQL.


问:
Best practice for acceptance tests in Java
We have a program that that we would like to do acceptance tests on it.
The input is an XML file with different "tasks".
The output is another XML file with results.

What would be the best practice to automate acceptance tests for it?

We will probably have to store pairs of input and output files, run the program on the inputs and compare result to the provided outputs.

Is Ant good for this task?

Should the acceptance tests cover all corner cases, or only test that the functionality is in general working.

Any other tips regarding acceptance tests in java would be appreciated.

答:
Some general tips

Make sure that non technical people such as clients or business analysts understand the tests.

Strive to organize your test suites well. Probably you could organize them per feature or functionality. Also try to separate tests for corner cases from the "normal" tests.

I think that XMLUnit can do diffing of XML files http://xmlunit.sourceforge.net/


问:
Branch.io: Extract custom value from link
we're facing a problem right now: We're using the SMS gateway feature from branch.io which simply does not work properly worldwide (e.g. Lituanian cell phones won't receive any messages at all).

Therefore i need a fallback method for people that cannot receive an SMS to their phone with the downloadlink in the Appstore. (The branch.io Links have an effect on the branding of our app)

The fallback is to let them use a voucher code which COULD be generated from a custom value that we store for each Link

This is an ordinary Link with its 2 custom values

The landing page http://learnmat.ch/spark7 opens in the browser and i'd like to be able to identify the SponsorID on the website so that i can return a voucher code that is suitable for the specific SponsorID of the Link.

Right now i've already integrated the Web SDK into the website.

Is that "reverse engineering of the SponsorID" possible based on the Link and the WebSDK integration?

I'd really appreciate your help!

Thank you,
Sven

答:
Jackie from Branch here.

Our SMS page service supports international numbers but only if the number the SMS has to be delivered is in the same country the SMS is being sent from. Could you please make sure the sender is physically located in Lithuania? I'd also suggest creating your own Twilio integration if you want to bypass these restrictions we have on our system https://docs.branch.io/pages/web/text-me-the-app/#use-your-own-sms-service

Regarding your fallback method: you want to have users click on a Branch link that will open your website and based on the link data (sponsor ID), you want to provide them with unique voucher codes? If my assumption is correct, you can achieve this by custom event tracking and user identity tracking. (relevant docs: https://docs.branch.io/pages/dashboard/analytics/#user-value-attribution)

Hopefully, this helps. Let us know if you have additional questions about the info above, or about anything else related to integrating Branch.

Best,

Jackie Choi


问:
Does anyone have a better way to do this? Im just learning how to play around with CSS
The image is the goal. I need to position each color correctly within the box. It must also be in the center of the browser. The result I got is exactly what the image is just with words. I'm really looking for a better way to do this because I kind of had to guess the left and bottom pixels. I also know it could have been done better and would really love to learn how.

.border{
  border: 2px solid black;
  width: 500px;
  height: 700px;
  margin:25px 450px;
  padding: 1px;
}

#one {
  background: red;
  height:100px;
}

#two{
 background: yellow;
 height:600px;
 width:100px;
}

#three {
  background: blue;
  height:550px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 600px;
}

#four{
  background: yellow;
  height: 600px;
  width:100px;
  position: relative;
  left:400px;
  bottom: 1150px;
}

#five{
  background: green;
  height:50px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 1200px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div class="border">
    <div id="one">One</div>
    <div id="two">Two</div>
    <div id="three">Three</div>
    <div id="four">Four</div>
    <div id="five">Five</div>
   </div></code>```

答:
To extend @Obsidian Age's answer, you could also achieve this by using css flexbox.

More info:

MDN

CSS-tricks

.border {
  border: 2px solid black;
  width: 50vw;
  height: 100vh;
  padding: 1px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap
}

.top {
  background: red;
  height: 20%;
  flex: 100%;
}

.left,
.right,
.middle_container,
.middle {
  height: 80%;
}

.left,
.right {
  background: yellow;
  flex: 1
}

.middle_container {
  flex: 3;
}

.middle {
  background: blue;
}

.bottom {
  background: green;
  height: 20%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">
  <div class="top">Top</div>
  <div class="left">Left</div>
  <div class="middle_container">
    <div class="middle">Middle</div>
    <div class="bottom">Bottom</div>
  </div>
  <div class="right">Right</div>
</div></code>```

Body:
The image is the goal. I need to position each color correctly within the box. It must also be in the center of the browser. The result I got is exactly what the image is just with words. I'm really looking for a better way to do this because I kind of had to guess the left and bottom pixels. I also know it could have been done better and would really love to learn how.

.border{
  border: 2px solid black;
  width: 500px;
  height: 700px;
  margin:25px 450px;
  padding: 1px;
}

#one {
  background: red;
  height:100px;
}

#two{
 background: yellow;
 height:600px;
 width:100px;
}

#three {
  background: blue;
  height:550px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 600px;
}

#four{
  background: yellow;
  height: 600px;
  width:100px;
  position: relative;
  left:400px;
  bottom: 1150px;
}

#five{
  background: green;
  height:50px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 1200px;
 }

One

Two

Three

Four

Five

Body:
To extend @Obsidian Age's answer, you could also achieve this by using css flexbox.

More info:

MDN

CSS-tricks

.border {
  border: 2px solid black;
  width: 50vw;
  height: 100vh;
  padding: 1px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap
}

.top {
  background: red;
  height: 20%;
  flex: 100%;
}

.left,
.right,
.middle_container,
.middle {
  height: 80%;
}

.left,
.right {
  background: yellow;
  flex: 1
}

.middle_container {
  flex: 3;
}

.middle {
  background: blue;
}

.bottom {
  background: green;
  height: 20%;
}

<div class="border">
  <div class="top">Top</div>
  <div class="left">Left</div>
  <div class="middle_container">
    <div class="middle">Middle</div>
    <div class="bottom">Bottom</div>
  </div>
  <div class="right">Right</div>
</div>


问:
How to load .OBJ and .MTL using ThreeJS? (HTML)
I'm trying to load a 3D globe into my HTML site using a ThreeJS script (found below) But it's stitched together with code from other sources, meaning the camera is mapped to MouseX and MouseY positions. I want the object to sit in the center of the page with a simple slow spin, but every time I try and achieve this the object vanishes.

The Javascript:

```<code><script>
        var container;

        var camera, scene, renderer;

        var mouseX = 0, mouseY = 0;

        var windowHalfX = window.innerWidth / 2;
        var windowHalfY = window.innerHeight / 2;

        init();
        animate();

        function init() {

            container = document.createElement( 'div' );
            document.body.appendChild( container );

            camera = new THREE.PerspectiveCamera( 5, window.innerWidth / window.innerHeight, 1, 5000 );
            camera.position.z = 250;

            scene = new THREE.Scene();

            var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.8 );
            scene.add( ambientLight );

            var pointLight = new THREE.PointLight( 0xFFF1CF, 0.6 , 0 );

            camera.add( pointLight );
            scene.add( camera );

            var manager = new THREE.LoadingManager();
            manager.onProgress = function ( item, loaded, total ) {

                console.log( item, loaded, total );

            };

            var onProgress = function ( xhr ) {
                if ( xhr.lengthComputable ) {
                    var percentComplete = xhr.loaded / xhr.total * 100;
                    console.log( Math.round(percentComplete, 2) + '% downloaded' );
                }
            };

            var onError = function ( xhr ) {;
            };

            var mtlLoader = new THREE.MTLLoader();
        mtlLoader.load('planet.mtl', function(materials) {
        materials.preload();
        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials(materials);
        objLoader.load('planet.obj', function(object) {
         object.position.y = 0;
         scene.add(object);
        }, onProgress, onError);
        });

            //

            renderer = new THREE.WebGLRenderer( {alpha: true});
           renderer.setClearColor( 0x000000, 0 );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            container.appendChild( renderer.domElement );

            document.addEventListener( 'mousemove', onDocumentMouseMove, false );
                     document.addEventListener( 'mouseclick', onmousedown, false);

            //

            window.addEventListener( 'resize', onWindowResize, false );

        }

        function onWindowResize() {

            windowHalfX = window.innerWidth / 2;
            windowHalfY = window.innerHeight / 2;

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

        }

        function onDocumentMouseMove( event ) {

            mouseX = ( event.clientX );
            mouseY = ( event.clientY );

        }

        //

        function animate() {

            requestAnimationFrame( animate );
            render();

        }

        function render() {

            camera.position.x += ( mouseX - camera.position.x ) * .05;
            camera.position.y += ( - mouseY - camera.position.y ) * .05;

            camera.lookAt( scene.position );

            renderer.render( scene, camera );

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

答:
You need to change your code a little bit,

In the 'init' function, change the object loading logic as follows

```<code>var mtlLoader = new THREE.MTLLoader();
var objLoader = new THREE.OBJLoader();
mtlLoader.load( 'planet.mtl', function(materials) {
    materials.preload();
    objLoader.setMaterials(materials);
    objLoader.load( 'planet.obj', function( object ){
        object.position.set( 0, 0, 0 ); // set the position as (0,0,0)
        globe = object; // globe is the object to be added to the scene
        scene.add(globe);
        animate(); //call the animate function only after the object is loaded
    }, onProgress, onError);
} );
</code>```

And change the render method,

```<code>function render() {
    globe.rotation.y += 0.01; // this will rotate the object
    camera.lookAt( scene.position );
    renderer.render( scene, camera );
}
</code>```

Body:
You need to change your code a little bit,

In the 'init' function, change the object loading logic as follows

var mtlLoader = new THREE.MTLLoader();
var objLoader = new THREE.OBJLoader();
mtlLoader.load( 'planet.mtl', function(materials) {
    materials.preload();
    objLoader.setMaterials(materials);
    objLoader.load( 'planet.obj', function( object ){
        object.position.set( 0, 0, 0 ); // set the position as (0,0,0)
        globe = object; // globe is the object to be added to the scene
        scene.add(globe);
        animate(); //call the animate function only after the object is loaded
    }, onProgress, onError);
} );

And change the render method,

function render() {
    globe.rotation.y += 0.01; // this will rotate the object
    camera.lookAt( scene.position );
    renderer.render( scene, camera );
}


问:
Error spotting inspiration required: certificate_unknown and SSLHandshakeException on Payara
I'm banging my head where the error is, so I need a little error tracking inspiration.

I try to call a webservice on a remote server from a Java web app that is running on my dockerized Payara 4.1. Docker image is using Alpine Linux with Java 8.

When I attempt to call the service I get a

Certificate_unknown thrown by an SSLHandshakeException

I know this means that the chain of trust is not complete and a certificate (root/intermediary) is missing.

When I check the ssl connection via openssl with

```<code>openssl s_client -connect server:port -CAfile certificate_exported_from_remote_server.per
</code>```

its working fine ('Verify return code: 0 (ok)'.

```<code>openssl s_client -connect server:port -CAfile path_to_payara/config/cacerts.jks
</code>```

does not work (Verify return code: 20 (unable to get local issuer certificate)), but I haven't found out if I can use openssl with a keystore.

Anyway, I've imported all certificates (root/intermediary) I could download from the remote webservice' server and installed them via keytool

```<code>keytool -import -v -trustcacerts -alias cert -file downloadedcertificate.cer -keystore payara_path/config/cacerts.jks --storepass pwd -noprompt
</code>```

When I list using keytool -list -keystore it shows that the certificates were imported.

In the domain.xml the jvm-option -Djavax.ssl.trustStore points to the cacerts.jks.

I thought that this is the correct way, but I still get this error and I'm too blind to see what I did wrong.

Thus, I'm asking for some inspiration to spot the error.

答:
If you need to use a locally generated certificate, you need to import it to the remote server. What you did is you imported remote certificate to a local trust store which could possibly work if OpenSSL picked that exact one from the trust store, but I assume there are more certificates in the loca ltrust store and it picks a certificate that's not on the remote server's trust store.

The rule is simple: the certificate used by the client has to be present in the remote server's truststore

Body:
I'm banging my head where the error is, so I need a little error tracking inspiration.

I try to call a webservice on a remote server from a Java web app that is running on my dockerized Payara 4.1. Docker image is using Alpine Linux with Java 8.

When I attempt to call the service I get a

Certificate_unknown thrown by an SSLHandshakeException

I know this means that the chain of trust is not complete and a certificate (root/intermediary) is missing.

When I check the ssl connection via openssl with

openssl s_client -connect server:port -CAfile certificate_exported_from_remote_server.per

its working fine ('Verify return code: 0 (ok)'.

openssl s_client -connect server:port -CAfile path_to_payara/config/cacerts.jks

does not work (Verify return code: 20 (unable to get local issuer certificate)), but I haven't found out if I can use openssl with a keystore.

Anyway, I've imported all certificates (root/intermediary) I could download from the remote webservice' server and installed them via keytool

keytool -import -v -trustcacerts -alias cert -file downloadedcertificate.cer -keystore payara_path/config/cacerts.jks --storepass pwd -noprompt

When I list using keytool -list -keystore it shows that the certificates were imported.

In the domain.xml the jvm-option -Djavax.ssl.trustStore points to the cacerts.jks.

I thought that this is the correct way, but I still get this error and I'm too blind to see what I did wrong.

Thus, I'm asking for some inspiration to spot the error.


问:
Error when execute MavenCli in the loop (maven-embedder)?
What is the problem when I execute the maven command in the loop ? The goal is to update the version of pom.xml of the list of bundles. The first iteration, maven execute correctly (update pom.xml), but it makes error for all item after.

```<code>for (String bundlePath: bundlesToUpdate)
{
    MavenCli cli = new MavenCli();
String[] arguments = {
    "-Dtycho.mode=maven",
        "org.eclipse.tycho:tycho-versions-plugin:set-version",
    "-DgenerateBackupPoms=false",
    "-DnewVersion=" + version};
    int result = cli.doMain(arguments, bundlePath, System.out, System.err);
}
</code>```

Same error with the code:

```<code>`MavenCli cli = new MavenCli();
for (String bundlePath: bundlesToUpdate)
{
    String[] arguments = {
    "-Dtycho.mode=maven",
    "org.eclipse.tycho:tycho-versions-plugin:set-version",
    "-DgenerateBackupPoms=false",
    "-DnewVersion=" + version};
int result = cli.doMain(arguments, bundlePath, System.out, System.err);
}`
</code>```

First time, it's ok:

```<code>[main] INFO org.eclipse.tycho.versions.manipulation.PomManipulator -   pom.xml//project/version: 2.2.6-SNAPSHOT => 2.2.7-SNAPSHOT
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - Reactor Summary:
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger -
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - XXXX project   ....................... SUCCESS [  0.216 s]
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - com.sungard.valdi.bus.fixbroker.client.bnp ........ SKIPPED
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - XXX project Feature ...................... SKIPPED
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - BUILD SUCCESS
</code>```

After the errors are:

```<code>[main] ERROR org.apache.maven.cli.MavenCli - Error executing Maven.
[main] ERROR org.apache.maven.cli.MavenCli - java.util.NoSuchElementException
  role: org.apache.maven.eventspy.internal.EventSpyDispatcher
roleHint:
[main] ERROR org.apache.maven.cli.MavenCli - Caused by: null
[main] ERROR org.apache.maven.cli.MavenCli - Error executing Maven.
[main] ERROR org.apache.maven.cli.MavenCli - java.util.NoSuchElementException
      role: org.apache.maven.eventspy.internal.EventSpyDispatcher
roleHint:
</code>```

答:
This works for me inside a custom maven plugin (using Maven 3.5.0):

```<code>ClassRealm classRealm = (ClassRealm) Thread.currentThread().getContextClassLoader();
MavenCli cli = new MavenCli(classRealm.getWorld());
cli.doMain( ... );
</code>```

The plexus Launcher sets the context class loader to its ClassRealm, which has access to the "global" ClassWorld.

Not sure how stable that solution is, but so far looking good.

Used imports:

```<code>import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.apache.maven.cli.MavenCli;
</code>```

Body:
What is the problem when I execute the maven command in the loop ? The goal is to update the version of pom.xml of the list of bundles. The first iteration, maven execute correctly (update pom.xml), but it makes error for all item after.

for (String bundlePath: bundlesToUpdate)
{
    MavenCli cli = new MavenCli();
String[] arguments = {
    "-Dtycho.mode=maven",
        "org.eclipse.tycho:tycho-versions-plugin:set-version",
    "-DgenerateBackupPoms=false",
    "-DnewVersion=" + version};
    int result = cli.doMain(arguments, bundlePath, System.out, System.err);
}

Same error with the code:

`MavenCli cli = new MavenCli();
for (String bundlePath: bundlesToUpdate)
{
    String[] arguments = {
    "-Dtycho.mode=maven",
    "org.eclipse.tycho:tycho-versions-plugin:set-version",
    "-DgenerateBackupPoms=false",
    "-DnewVersion=" + version};
int result = cli.doMain(arguments, bundlePath, System.out, System.err);
}`

First time, it's ok:

[main] INFO org.eclipse.tycho.versions.manipulation.PomManipulator -   pom.xml//project/version: 2.2.6-SNAPSHOT => 2.2.7-SNAPSHOT
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - Reactor Summary:
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger -
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - XXXX project   ....................... SUCCESS [  0.216 s]
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - com.sungard.valdi.bus.fixbroker.client.bnp ........ SKIPPED
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - XXX project Feature ...................... SKIPPED
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - BUILD SUCCESS

After the errors are:

[main] ERROR org.apache.maven.cli.MavenCli - Error executing Maven.
[main] ERROR org.apache.maven.cli.MavenCli - java.util.NoSuchElementException
  role: org.apache.maven.eventspy.internal.EventSpyDispatcher
roleHint:
[main] ERROR org.apache.maven.cli.MavenCli - Caused by: null
[main] ERROR org.apache.maven.cli.MavenCli - Error executing Maven.
[main] ERROR org.apache.maven.cli.MavenCli - java.util.NoSuchElementException
      role: org.apache.maven.eventspy.internal.EventSpyDispatcher
roleHint:

Body:
This works for me inside a custom maven plugin (using Maven 3.5.0):

ClassRealm classRealm = (ClassRealm) Thread.currentThread().getContextClassLoader();
MavenCli cli = new MavenCli(classRealm.getWorld());
cli.doMain( ... );

The plexus Launcher sets the context class loader to its ClassRealm, which has access to the "global" ClassWorld.

Not sure how stable that solution is, but so far looking good.

Used imports:

import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.apache.maven.cli.MavenCli;


问:
Cannot GET /aboutus page after refreshing in react router 4.2 using webpack 3.8
onclick routing is going perfect but on refresh page not found error is coming. I am using react router 4.2 and webpack 3.8. when i am going to dashboard to about us component it is correctly routing but when we refresh that page there is coming an error can not get aboutus page.
This is my webpack.config.js

```<code>var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js',
    publicPath: '/'
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './',
    hot: true
  },
  plugins: [
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery'
  })
  ],
  watch: true,
  module : {
    loaders : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader'
      }
    ]
  },
};

module.exports = config;
</code>```

and my package.json is

```<code>{
  "name": "react-setup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server",
    "dev": "webpack -d --progress --colors --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^3.3.7",
    "create-react-class": "^15.6.2",
    "jquery": "^3.2.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "webpack": "^3.8.1"
  }
}
</code>```

here is my index.jsx component.

```<code>import AwesomeComponent from './awesomecomponent.jsx';
import Dashboard from './dashboard.jsx';
import App from './app.jsx';
import AboutUs from'./aboutus.jsx';
import React from 'react';
import {render} from 'react-dom';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link, Prompt, Switch} from 'react-router-dom'

ReactDOM.render((
  <Router>
    <Switch>
        <Route exact path='/' component={Dashboard} />
        <Dashboard>
            <Route path='/aboutus' component={AboutUs} />
        </Dashboard>
        <Route path='/awesomecomponent' component={AwesomeComponent} />
    </Switch>
  </Router>
), document.getElementById('app'))
</code>```

I do not understand, What am I doing wrong? or What do I missed?
please help me.

答: Use contentBase as '.' not './'. Then re-run start and dev command.</p>

Body:
onclick routing is going perfect but on refresh page not found error is coming. I am using react router 4.2 and webpack 3.8. when i am going to dashboard to about us component it is correctly routing but when we refresh that page there is coming an error can not get aboutus page.
This is my webpack.config.js

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js',
    publicPath: '/'
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './',
    hot: true
  },
  plugins: [
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery'
  })
  ],
  watch: true,
  module : {
    loaders : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader'
      }
    ]
  },
};

module.exports = config;

and my package.json is

{
  "name": "react-setup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server",
    "dev": "webpack -d --progress --colors --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^3.3.7",
    "create-react-class": "^15.6.2",
    "jquery": "^3.2.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "webpack": "^3.8.1"
  }
}

here is my index.jsx component.

import AwesomeComponent from './awesomecomponent.jsx';
import Dashboard from './dashboard.jsx';
import App from './app.jsx';
import AboutUs from'./aboutus.jsx';
import React from 'react';
import {render} from 'react-dom';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link, Prompt, Switch} from 'react-router-dom'

ReactDOM.render((
  <Router>
    <Switch>
        <Route exact path='/' component={Dashboard} />
        <Dashboard>
            <Route path='/aboutus' component={AboutUs} />
        </Dashboard>
        <Route path='/awesomecomponent' component={AwesomeComponent} />
    </Switch>
  </Router>
), document.getElementById('app'))

I do not understand, What am I doing wrong? or What do I missed?
please help me.


问:
Unable to clone locally a repository from VS Team Services using any version of Visual Studio 2017
I'm having a problem cloning a repository locally from Visual Studio Team Services when using any version of Visual Studio 2017. Here's the error I'm getting:

```<code>Error encountered while cloning the remote repository: Git failed with a fatal error.
fatal: Win32Exception encountered.
Failed to write credentials
error: cannot spawn askpass: No such file or directory
fatal: could not read Username for 'https://XXX.visualstudio.com':terminal prompts disabled
</code>```

I have another computer that run Visual Studio 2015 and everything works just fine. Is there any reason I'm having this problem?

答:
I had the same error after updating the Visual studio 2017.

here is my error message (which is almost identical to yours, with some slight differences)

Error: cannot spawn askpass: No such file or directory

  Error encountered while pushing to the remote repository: Git failed with a fatal error.

  could not read Password for 'https://something@bitbucket.org': terminal prompts disabled

The Visual studio was asking me for the password every time, and I was not able to make any pull or push request

this appears to be bug in Visual studio

here is the solution:

Open Command Prompt

Run setx GIT_TRACE %UserProfile%\git.log

Run setx GCM_TRACE %GIT_TRACE%

Restart your PowerShell console

Run your git command again, with the goal of reproducing the issue again.

Go back to Command Prompt

Run setx GIT_TRACE ""

Run setx GCM_TRACE ""

Actually the problem has been solved for me just after executing the first three steps.

here is the source https://developercommunity.visualstudio.com/content/problem/31370/git-error-when-running-vs-under-account-from-diffe.html

Body:
I'm having a problem cloning a repository locally from Visual Studio Team Services when using any version of Visual Studio 2017. Here's the error I'm getting:

Error encountered while cloning the remote repository: Git failed with a fatal error.
fatal: Win32Exception encountered.
Failed to write credentials
error: cannot spawn askpass: No such file or directory
fatal: could not read Username for 'https://XXX.visualstudio.com':terminal prompts disabled

I have another computer that run Visual Studio 2015 and everything works just fine. Is there any reason I'm having this problem?


问:
Origin http://localhost is not allowed by Access-Control-Allow-Origin
I'm trying to do a fetch from backbone.js to my node.js server. However, I get the following error in the console:

Origin http://localhost is not allowed by Access-Control-Allow-Origin.

I added the following to my node.js server:

```<code>var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "http://localhost");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
};

app.configure(function() {
    app.use(allowCrossDomain);
});
</code>```

But it's still returning the same error. However, even if this did work, it doesn't seem like the ideal solution, as I would like users from all over to be able to send requests.

答:
This approach resolved my issue to allow multiple domain  </p>

```<code>app.use(function(req, res, next) {
      var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });
</code>```

Body:
I'm trying to do a fetch from backbone.js to my node.js server. However, I get the following error in the console:

Origin http://localhost is not allowed by Access-Control-Allow-Origin.

I added the following to my node.js server:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "http://localhost");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
};

app.configure(function() {
    app.use(allowCrossDomain);
});

But it's still returning the same error. However, even if this did work, it doesn't seem like the ideal solution, as I would like users from all over to be able to send requests.

Body:
This approach resolved my issue to allow multiple domain

app.use(function(req, res, next) {
      var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });


问:
Image does not display with directory but displays with the image code
Chrome does not display my .svg image but displays once the code of the image is inserted along with html.

For example (without image code)

with image code

Why does this happen and what is the cause of it?

答:
these are 2 different possible solutions

1) be sure that your path is correct

2) try removing that height and write style="height:20px;"


问:
"Can only update a mounted or mounting component " warning in componentDidMount
Theoretically, I should be able to asynchronously fetch some data and update my component inside of componentDidMount. Here's my component:

```<code>import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class App extends Component {
  constructor () {
    super()
    this.state = {}
  }

  componentDidMount () {
    fetch('/api/sessions')
      .then(response => response.json())
      .then(data => {
        this.setState({ sessions: data.body })
      })
  }

  render () {
    return (
      <div>
        <h1>Sessions</h1>
        <ul>
          {this.state.sessions && this.state.sessions.map(session => {
            return <li key={`session-${session._id}`}>{session._id}</li>
          })}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.querySelector('#root'))
</code>```

The component renders, and re-renders when the data is received. But I'm getting a warning:

```<code>Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Please check the code for the App component.
</code>```

Shouldn't I be able to assume that componentDidMount implies the component actually mounted? What am I doing wrong here?

答:
To prevent it You can maintain a state say isMounted and update it on componentWillMount and componentWillUnmount. And whenever you are asynchronously trying to set state, first check whether the component is still mounted or not.</p>

```<code>componentWillMount = () => {
  this.setState({
      isMounted: true
  })
}

componentWillUnmount = () => {
  this.setState({
      isMounted: false
  })
}

componentDidMount () {
 fetch('/api/sessions')
  .then(response => response.json())
  .then(data => {
    if (this.state.isMounted) {
       this.setState({ sessions: data.body })
    }
  })
}
</code>```

Body:
Theoretically, I should be able to asynchronously fetch some data and update my component inside of componentDidMount. Here's my component:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class App extends Component {
  constructor () {
    super()
    this.state = {}
  }

  componentDidMount () {
    fetch('/api/sessions')
      .then(response => response.json())
      .then(data => {
        this.setState({ sessions: data.body })
      })
  }

  render () {
    return (

Sessions

          {this.state.sessions && this.state.sessions.map(session => {
            return <li key={`session-${session._id}`}>{session._id}

          })}

    )
  }
}

ReactDOM.render(<App />, document.querySelector('#root'))

The component renders, and re-renders when the data is received. But I'm getting a warning:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Please check the code for the App component.

Shouldn't I be able to assume that componentDidMount implies the component actually mounted? What am I doing wrong here?

Body:
To prevent it You can maintain a state say isMounted and update it on componentWillMount and componentWillUnmount. And whenever you are asynchronously trying to set state, first check whether the component is still mounted or not.

componentWillMount = () => {
  this.setState({
      isMounted: true
  })
}

componentWillUnmount = () => {
  this.setState({
      isMounted: false
  })
}

componentDidMount () {
 fetch('/api/sessions')
  .then(response => response.json())
  .then(data => {
    if (this.state.isMounted) {
       this.setState({ sessions: data.body })
    }
  })
}


问:
Calling remote method in spring with parameters
I have a class annoted with Service Annotation on server 1 .

```<code>@Service
public class MainHandler implements AbstractHandler {

   @Autowired
   private ServiceLocal defaultService;

   @Override
   public boolean execute(HttpServletRequest request, HttpServletResponse response) throws MsisdnServiceException {
          System.out.println("The default Request" + request);
   }
}
</code>```

I want to call this method from other remote server after passing the request and get the response from this  , what is the way to do in spring .

答:
Invoking methods remotely would be using a technology called RMI, which you can google easily.

However, since you want to use HttpServletRequest and HttpServletResponse, you probably should write an Http Controller using Spring MVC. For that you can also google and very easily find excellent tutorials and guides.

Body:
I have a class annoted with Service Annotation on server 1 .

@Service
public class MainHandler implements AbstractHandler {

   @Autowired
   private ServiceLocal defaultService;

   @Override
   public boolean execute(HttpServletRequest request, HttpServletResponse response) throws MsisdnServiceException {
          System.out.println("The default Request" + request);
   }
}

I want to call this method from other remote server after passing the request and get the response from this  , what is the way to do in spring .