问:
nested XML to data frame in R
Hello I'm new to R and XML files.

I'm trying to get this XML SOAP response into a dataframe:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <PrepareDataByClientResponse xmlns="urn:HM-schema">
      <PrepareDataByClientResult>
        <READOUT>
          <SerialNumber>1728527</SerialNumber>
          <Date>1510505992000</Date>
          <Type>1</Type>
          <Value>78.2</Value>
          <Status>OK</Status>
        </READOUT>
        <READOUT>
          <SerialNumber>1728527</SerialNumber>
          <Date>1510509592000</Date>
          <Type>1</Type>
          <Value>76.87</Value>
          <Status>OK</Status>
        </READOUT>
        <READOUT>
          <SerialNumber>1728527</SerialNumber>
          <Date>1510513192000</Date>
          <Type>1</Type>
          <Value>75.61</Value>
          <Status>OK</Status>
        </READOUT>
        <READOUT>
          <SerialNumber>e2ddeed13b4cc4d132f8c6a67d67eed3</SerialNumber>
          <Date>4531528776000</Date>
          <Type>3</Type>
          <Value>230.68</Value>
          <Status>OK</Status>
        </READOUT>
      </PrepareDataByClientResult>
        </PrepareDataByClientResponse>
      </soap:Body>
    </soap:Envelope>
</code>```

I have tried several options like:

```<code>xmlout <- do.call(rbind, xpathApply(xmldoc,'//soap:Envelope/soap:Body/PrepareDataByClientResponse', xmlToDataFrame))
xmlout <- as.data.frame(t(xpathSApply(xmldoc,"//readout",function(x) xmlSApply(x,xmlValue))))
xmlout <- as.data.frame(t(xmlSApply(xmldoc["/PrepareDataByClientResponse/PrepareDataByClientResult/READOUT"],xmlAttrs)),stringsAsFactors=FALSE)
xmlout <- ldply(xmlToList(xmldoc), data.frame)
</code>```

After extensive research in SO and other google searches, I have been unable to produce the desired results. All I can get is a data frame with a single row and all the observations in a different column each.

I'm trying to get a table of READOUTS like:

```<code>    SerialNumber    Date            Type    Value    Status
1   1728527         1510505992000   1       78.2     OK
2   1728527         1510509592000   1       76.87    OK
3   1728527         1510513192000   1       75.61    OK
</code>```

Is there any way to get this sort of table to work?

Thanks in advance.

答:
Because you have a default namespace at the <PrepareDataByClientResponse> tag (i.e., xmlns without a colon separated prefix), all its children follow under this default namespace.

To parse the <READOUT> tags, consider declaring a prefix to use in a getNodeSet() call. Below uses nm. Such a call can then be used inside the convenience method xmlToDataFrame which can easily migrate relatively flat XML like you have into dataframes:

```<code>library(XML)

doc <- xmlParse('/path/to/SOAP/Response.xml')

df <- xmlToDataFrame(doc, nodes=getNodeSet(doc, "//nm:READOUT",
                                           namespaces=c(nm="urn:HM-schema")))

df
#                       SerialNumber          Date Type  Value Status
# 1                          1728527 1510505992000    1   78.2     OK
# 2                          1728527 1510509592000    1  76.87     OK
# 3                          1728527 1510513192000    1  75.61     OK
# 4 e2ddeed13b4cc4d132f8c6a67d67eed3 4531528776000    3 230.68     OK
</code>```

Title: nested XML to data frame in R

Body:
Hello I'm new to R and XML files.

I'm trying to get this XML SOAP response into a dataframe:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <PrepareDataByClientResponse xmlns="urn:HM-schema">
      <PrepareDataByClientResult>
        <READOUT>
          <SerialNumber>1728527</SerialNumber>
          <Date>1510505992000</Date>
          <Type>1</Type>
          <Value>78.2</Value>
          <Status>OK</Status>
        </READOUT>
        <READOUT>
          <SerialNumber>1728527</SerialNumber>
          <Date>1510509592000</Date>
          <Type>1</Type>
          <Value>76.87</Value>
          <Status>OK</Status>
        </READOUT>
        <READOUT>
          <SerialNumber>1728527</SerialNumber>
          <Date>1510513192000</Date>
          <Type>1</Type>
          <Value>75.61</Value>
          <Status>OK</Status>
        </READOUT>
        <READOUT>
          <SerialNumber>e2ddeed13b4cc4d132f8c6a67d67eed3</SerialNumber>
          <Date>4531528776000</Date>
          <Type>3</Type>
          <Value>230.68</Value>
          <Status>OK</Status>
        </READOUT>
      </PrepareDataByClientResult>
        </PrepareDataByClientResponse>
      </soap:Body>
    </soap:Envelope>

I have tried several options like:

xmlout <- do.call(rbind, xpathApply(xmldoc,'//soap:Envelope/soap:Body/PrepareDataByClientResponse', xmlToDataFrame))
xmlout <- as.data.frame(t(xpathSApply(xmldoc,"//readout",function(x) xmlSApply(x,xmlValue))))
xmlout <- as.data.frame(t(xmlSApply(xmldoc["/PrepareDataByClientResponse/PrepareDataByClientResult/READOUT"],xmlAttrs)),stringsAsFactors=FALSE)
xmlout <- ldply(xmlToList(xmldoc), data.frame)

After extensive research in SO and other google searches, I have been unable to produce the desired results. All I can get is a data frame with a single row and all the observations in a different column each.

I'm trying to get a table of READOUTS like:

    SerialNumber    Date            Type    Value    Status
1   1728527         1510505992000   1       78.2     OK
2   1728527         1510509592000   1       76.87    OK
3   1728527         1510513192000   1       75.61    OK

Is there any way to get this sort of table to work?

Thanks in advance.

Body:
Because you have a default namespace at the <PrepareDataByClientResponse> tag (i.e., xmlns without a colon separated prefix), all its children follow under this default namespace.

To parse the <READOUT> tags, consider declaring a prefix to use in a getNodeSet() call. Below uses nm. Such a call can then be used inside the convenience method xmlToDataFrame which can easily migrate relatively flat XML like you have into dataframes:

library(XML)

doc <- xmlParse('/path/to/SOAP/Response.xml')

df <- xmlToDataFrame(doc, nodes=getNodeSet(doc, "//nm:READOUT",
                                           namespaces=c(nm="urn:HM-schema")))

df
#                       SerialNumber          Date Type  Value Status
# 1                          1728527 1510505992000    1   78.2     OK
# 2                          1728527 1510509592000    1  76.87     OK
# 3                          1728527 1510513192000    1  75.61     OK
# 4 e2ddeed13b4cc4d132f8c6a67d67eed3 4531528776000    3 230.68     OK


来源: stackexchange

问:
Simple Python: about structure of code
```<code>print ("This program reads an unsigned binary number of arbitrary length
\nand tries to compute the decimal equivalent. The program reports an error
\nif the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

    if((bin % 10) == True):
        dec += factor
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")

print ("I think your binary number in decimal form is: " ,dec)
</code>```

This is my code for a program that is supposed to convert a binary number from the user into a decimal number. It works fine, but I'm trying to add an "else" statement that will print "unrecognized bit" if the user enters a number other than 0 or 1. It kinds works, however the program prints "Unrecognized bit" even if the user has only entered 0 and 1's. This shouldn't happen. Also, see picture related. I've entered 12343 to test the program, and it says Unrecognized bit which is good but it also takes the "1" in that number and converts it to 16 which shouldn't happen, it should just say unrecognized bit. I think these two problems are simple to fix but I'm just not sure. Thank you!

picture

答:
Two problems:

The conditional is only satisfied if your binary input has a remainder of 1, since 0 == False evaluates to True. That is to say, if your number ends with a zero (or in fact, contains a zero), (bin%10) == True will evaluate to False (side point: there's actually no need to add the == True on the right).

You're adding factor to dec regardless of whether the digit you're looking at is a 1 or 0; you shouldn't be adding if you encounter a zero.

So your code should look like this:

```<code>while(bin > 0):
    remainder = (bin % 10)
    if remainder in (0,1):
        dec += factor * remainder
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")
        break
</code>```

ContentLicense: CC BY-SA 3.0

Title: Simple Python: about structure of code

Body:
print ("This program reads an unsigned binary number of arbitrary length
\nand tries to compute the decimal equivalent. The program reports an error
\nif the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

    if((bin % 10) == True):
        dec += factor
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")

print ("I think your binary number in decimal form is: " ,dec)

This is my code for a program that is supposed to convert a binary number from the user into a decimal number. It works fine, but I'm trying to add an "else" statement that will print "unrecognized bit" if the user enters a number other than 0 or 1. It kinds works, however the program prints "Unrecognized bit" even if the user has only entered 0 and 1's. This shouldn't happen. Also, see picture related. I've entered 12343 to test the program, and it says Unrecognized bit which is good but it also takes the "1" in that number and converts it to 16 which shouldn't happen, it should just say unrecognized bit. I think these two problems are simple to fix but I'm just not sure. Thank you!

picture

Body:
Two problems:

The conditional is only satisfied if your binary input has a remainder of 1, since 0 == False evaluates to True. That is to say, if your number ends with a zero (or in fact, contains a zero), (bin%10) == True will evaluate to False (side point: there's actually no need to add the == True on the right).

You're adding factor to dec regardless of whether the digit you're looking at is a 1 or 0; you shouldn't be adding if you encounter a zero.

So your code should look like this:

while(bin > 0):
    remainder = (bin % 10)
    if remainder in (0,1):
        dec += factor * remainder
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")
        break


问:
How to split an string inside a multidimensional array in php
new to the stackoverflow community, so do be forgiving if I've done anything incorrect. As I'm an amateur in coding in php, I'm currently facing a difficulty in multi dimensional arrays.

Currently, I have this array being returned to me.

```<code>Array(
    [trialID] => 1
    [trialMixedArray] => 1,2,3,4,5,6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)
</code>```

How do I split the trialMixedArray and return it to the original array so that it becomes formatted to be like the following result:

```<code>Array(
    [trialID] => 1
    [trialMixedArray] => Array(
                               [0] => 1
                               [1] => 2
                               [2] => 3
                               [3] => 4
                               [4] => 5
                               [5] => 6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)
</code>```

Thanks for the help in advance! Cheers! :)

答:
Use explode function, which splits string to array. Manual.

$results['trialMixedArray'] = explode(',', $results['trialMixedArray']);

Body:
new to the stackoverflow community, so do be forgiving if I've done anything incorrect. As I'm an amateur in coding in php, I'm currently facing a difficulty in multi dimensional arrays.

Currently, I have this array being returned to me.

Array(
    [trialID] => 1
    [trialMixedArray] => 1,2,3,4,5,6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)

How do I split the trialMixedArray and return it to the original array so that it becomes formatted to be like the following result:

Array(
    [trialID] => 1
    [trialMixedArray] => Array(
                               [0] => 1
                               [1] => 2
                               [2] => 3
                               [3] => 4
                               [4] => 5
                               [5] => 6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)

Thanks for the help in advance! Cheers! :)


问:
Getting undefined at the end of the sentence when printing to console
```<code>const words = ['hello', 'thank you', 'brother', 'welcome', 'dancing', 'milk', 'bike', 'ruffles'];

const getSentence = (words, index = 0) => {

  if (words[index] === undefined) {
    return;
  }
  return words[index] + ' ' + getSentence(words, index + 1)
}

console.log(getSentence(words));
</code>```

答:
the problem is in last call your function return nothing so it print undefined you should have try to return some like some empty string try this code instead not sure if this will do what you want but give it a try</p>

```<code>const words = ['hello', 'thank you', 'brother', 'welcome', 'dancing', 'milk', 'bike', 'ruffles'];

const getSentence = (words, index = 0) => {

if (words[index] === undefined) {
    return '';
}
return words[index] + ' ' + getSentence(words, index + 1)
}

console.log(getSentence(words));
</code>```

Body:
the problem is in last call your function return nothing so it print undefined you should have try to return some like some empty string try this code instead not sure if this will do what you want but give it a try

const words = ['hello', 'thank you', 'brother', 'welcome', 'dancing', 'milk', 'bike', 'ruffles'];

const getSentence = (words, index = 0) => {

if (words[index] === undefined) {
    return '';
}
return words[index] + ' ' + getSentence(words, index + 1)
}

console.log(getSentence(words));


问:
Android store user purchased media file so only app can access
I am building an app that plays music and video packs that are purchased by the app user. The media needs to be downloaded to the device where it can be accessed offline. The files will be downloaded to the device.

The methods I know of to download the files leaves the ability for the file to be accessed through file manager and MediaStore. The problem with this is that some of the files are only licensed to play in the app.

Is there a way to lock the file or place it in the system media (audio and video) so the user cannot access it outside of the app.

Thanks

答:
As per android official documents you need to store your file in private location

Using the Internal Storage

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.

```<code>String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
</code>```

Body:
As per android official documents you need to store your file in private location

Using the Internal Storage

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();


问:
Control css transition with javascript
There is this progress bar that I am trying to control from javascript. In its demo it has this pretty nice flow, however if I try to set its width with javascript jquery $($0).css({'width': '80%'}), it looses its animation.

```<code>.progress-bar {
    margin: 0 auto;
    width: 100%;
    height: 10px;
    background-color: #e5e9eb;
}

.progress-bar .progress {
    position: relative;
    background-color: #90ee90;
    height: 10px;
    width: 100%;
    -webkit-animation-duration: 5s;
    -webkit-animation-name: width;
}

.progress-bar .progress .progress-shadow {
    background-image: linear-gradient(to bottom, #eaecee, transparent);
    position: absolute;
    height: 4em;
    width: 100%;
    top: 100%;
    transform: skew(-22.5deg);
    transform-origin: 0 0;
}

@-webkit-keyframes width {
    0%, 100% {
        transition-timing-function: cubic-bezier(1, 0, 0.65, 0.85);
    }

    0% {
        width: 0;
    }

    100% {
        width: 100%;
    }
  }
</code>```

How can I control its width without losing its animation?

https://jsfiddle.net/u2c8ft0k/

答:
Something like this?

$('#change-0').click(function() {
   $('.progress').css('width', '0%');
});
$('#change-50').click(function() {
   $('.progress').css('width', '50%');
});
$('#change-100').click(function() {
   $('.progress').css('width', '100%');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.progress-bar {
    margin: 0 auto;
    width: 100%;
    height: 10px;
    background-color: #e5e9eb;
}
.progress {
    position: relative;
    background-color: #90ee90;
    height: 10px;
    width: 0%;
    transition: width 2s;
}
.progress-shadow {
    background-image: linear-gradient(to bottom, #eaecee, transparent);
    position: absolute;
    height: 4em;
    width: 100%;
    top: 100%;
    transform: skew(-22.5deg);
    transform-origin: 0 0;
}</code>```

<button id="change-0">0%</button>
<button id="change-50">50%</button>
<button id="change-100">100%</button>```

Title: Control css transition with javascript

Body:
There is this progress bar that I am trying to control from javascript. In its demo it has this pretty nice flow, however if I try to set its width with javascript jquery $($0).css({'width': '80%'}), it looses its animation.

.progress-bar {
    margin: 0 auto;
    width: 100%;
    height: 10px;
    background-color: #e5e9eb;
}

.progress-bar .progress {
    position: relative;
    background-color: #90ee90;
    height: 10px;
    width: 100%;
    -webkit-animation-duration: 5s;
    -webkit-animation-name: width;
}

.progress-bar .progress .progress-shadow {
    background-image: linear-gradient(to bottom, #eaecee, transparent);
    position: absolute;
    height: 4em;
    width: 100%;
    top: 100%;
    transform: skew(-22.5deg);
    transform-origin: 0 0;
}

@-webkit-keyframes width {
    0%, 100% {
        transition-timing-function: cubic-bezier(1, 0, 0.65, 0.85);
    }

    0% {
        width: 0;
    }

    100% {
        width: 100%;
    }
  }

How can I control its width without losing its animation?

https://jsfiddle.net/u2c8ft0k/

Body:
Something like this?

$('#change-0').click(function() {
   $('.progress').css('width', '0%');
});
$('#change-50').click(function() {
   $('.progress').css('width', '50%');
});
$('#change-100').click(function() {
   $('.progress').css('width', '100%');
});

.progress-bar {
    margin: 0 auto;
    width: 100%;
    height: 10px;
    background-color: #e5e9eb;
}
.progress {
    position: relative;
    background-color: #90ee90;
    height: 10px;
    width: 0%;
    transition: width 2s;
}
.progress-shadow {
    background-image: linear-gradient(to bottom, #eaecee, transparent);
    position: absolute;
    height: 4em;
    width: 100%;
    top: 100%;
    transform: skew(-22.5deg);
    transform-origin: 0 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container text-center">
  <div class="progress-bar">
    <div class="progress">
      <div class="progress-shadow"></div>
    </div>
  </div>
</section>
<br /><br /><br /><br />
<button id="change-0">0%</button>
<button id="change-50">50%</button>
<button id="change-100">100%</button>


问:
Access local variable inside a callback function
```<code>var inner = function() { console.log(x); }

// test 1
(function(cb) { var x = 123; cb(); })(inner);

// test 2
(function(cb) { var x = 123; cb.apply(this); })(inner);

// test 3
(function(cb) { var x = 123; cb.bind(this)(); })(inner);

// test 4
(function(cb) { cb.bind({x: 123})(); })(inner);
</code>```

All tests result in:
ReferenceError: x is not defined

Do someone know how it is possible to access 'x' as a local variable inside the callback?

答:
You could redefine the callback function in the current scope:

```<code>var inner = function() { console.log(x); }

(function(cb) { var x = 123; eval('cb = ' + cb.toString()); cb(); })(inner);

// or

(function(cb) { var x = 123; eval('(' + cb.toString() + ')')(); })(inner);
</code>```

This will not work if the function relies on anything in the scope in which it was originally defined or if the Javascript file has been minified.  The use of eval may introduce security, performance, and code quality issues.

Body:
var inner = function() { console.log(x); }

// test 1
(function(cb) { var x = 123; cb(); })(inner);

// test 2
(function(cb) { var x = 123; cb.apply(this); })(inner);

// test 3
(function(cb) { var x = 123; cb.bind(this)(); })(inner);

// test 4
(function(cb) { cb.bind({x: 123})(); })(inner);

All tests result in:
ReferenceError: x is not defined

Do someone know how it is possible to access 'x' as a local variable inside the callback?

Body:
You could redefine the callback function in the current scope:

var inner = function() { console.log(x); }

(function(cb) { var x = 123; eval('cb = ' + cb.toString()); cb(); })(inner);

// or

(function(cb) { var x = 123; eval('(' + cb.toString() + ')')(); })(inner);

This will not work if the function relies on anything in the scope in which it was originally defined or if the Javascript file has been minified.  The use of eval may introduce security, performance, and code quality issues.


答:
you can try something like this</p>

```<code>$finalArray = [];
fetchItems($array_variable) {
  foreach($array_variable as $item){
    if(is_array($item) {
      fetchItems($item);
    } else {
      $finalArray[] = $item;
    }
  }
}

fetchItems($originaArray);
</code>```

Title: How to split an string inside a multidimensional array in php

Body:
you can try something like this

$finalArray = [];
fetchItems($array_variable) {
  foreach($array_variable as $item){
    if(is_array($item) {
      fetchItems($item);
    } else {
      $finalArray[] = $item;
    }
  }
}

fetchItems($originaArray);


问:
iOS: Notification when MKMapView is loaded and annotations/overlays are added?
I am aware of the delegate methods used to let me know when the map has loaded and annotations and overlays have been added. (mapViewDidFinishLoadingMap: mapView:didAddAnnotationViews: mapView:didAddOverlayViews:)

I am wanting to create a UIImage from my MKMapView once everything has loaded.  Currently I am creating my UIImage once mapView:didAddOverlayViews: is called, but this is not always reliable, because sometimes the overlay take longer to be added, sometimes mapViewDidFinishLoadingMap: is called more than once or it takes a long time to load.  Sometimes it is NOT called because tiles are cached. So, it is very hard to know exactly when everything has loaded.  I have tried using a timer but that doesn't make it reliable either.

My question is, how can I know when everything has completely loaded, including all map tiles, all annotations and all overlays?

答:
I have tried all ways from other answers.

It looks like impossible to get the time when it was fully loaded at least for iOS 11.1

I have found undocumented notification VKMapViewDidBecomeFullyDrawnNotification from VKMapView object but even it happens too early.

So it looks like only one way exist - wait couple seconds for full load and cross fingers to hope load the map was done.


问:
passing arguments in python, missing 4 required positional arguments?
I am currently working on a stock calculator project for a class, and can't figure out how to pass an argument from function to function. It keeps on giving me an error type of calculateProfit() missing 4 required positional arguments

```<code>def main():
    CONTINUE = 'y'
    while CONTINUE == 'y' or CONTINUE == 'Y':
        getInfo()
        pricePerShare, numOfShares, commissionRate, shareSold = calculateProfit()
        commissionPercent, spentOnShare, spentOnCommission, totalShareSold, profit, eightPercent = displayResults()
    CONTINUE = input("Would you like to continue? (Y/N)")
    if (CONTINUE.lower() == "n"):
        quit
</code>```

Am I missing something?

答:
calculateProfit() have to be called like this calculateProfit(a, b, c, d), where a, b, c and d is arguments. I don't know what that arguments should be, but what your code does is assigning the result of calculateProfit() to pricePerShare, numOfShares, commissionRate, shareSold.

Maybe you had in mind something like this calculateProfit(pricePerShare, numOfShares, commissionRate, shareSold) ?

Body:
I am currently working on a stock calculator project for a class, and can't figure out how to pass an argument from function to function. It keeps on giving me an error type of calculateProfit() missing 4 required positional arguments

def main():
    CONTINUE = 'y'
    while CONTINUE == 'y' or CONTINUE == 'Y':
        getInfo()
        pricePerShare, numOfShares, commissionRate, shareSold = calculateProfit()
        commissionPercent, spentOnShare, spentOnCommission, totalShareSold, profit, eightPercent = displayResults()
    CONTINUE = input("Would you like to continue? (Y/N)")
    if (CONTINUE.lower() == "n"):
        quit

Am I missing something?


问:
how to vertical align middle to multiple position absolute child div
I am currently facing a problem to vertical align the multiple position:absolute div to middle. Although I apply width:100% and height:100%, but the elements seems overflow too. Please help me on this. Thank you.

```<code><div class="wrapper">
  <div class="wrapper-inner">
    <div class="section-1">
      <h2>Heading Here</h2>
      <p>Some text here</p>
    </div>
    <div class="section-2">
      <p>Another text here.</p>
      <p>One more time.</p>
    </div>
  </div>
</div>

html,
body {
  width: 100%;
  height: 100%;
}
.wrapper {
  width: 100%;
  height: 100%;
}
.wrapper-inner {
  width: 100%;
  height: 100%;
  position: relative;
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}
</code>```

demo: https://codepen.io/rae0724/pen/jamzbX

I can't find a way to make those content at the current position and middle on this full screen height, except top:50% and minus it's height, but it's bad for responsive.

答:
Try using CSS Positioning. Like:

```<code>.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
.wrapper-inner {
  position: absolute;
  top: 50%;
  transform: translateY(-41px);
}
</code>```

Have a look at the snippet below:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
.wrapper-inner {
  position: absolute;
  top: 50%;
  transform: translateY(-41px);
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="wrapper-inner">
    <div class="section-1">
      <h2>Heading Here</h2>
      <p>Some text here</p>
    </div>
    <div class="section-2">
      <p>Another text here.</p>
      <p>One more time.</p>
    </div>
  </div>
</div></code>```

Hope this helps!

Body:
I am currently facing a problem to vertical align the multiple position:absolute div to middle. Although I apply width:100% and height:100%, but the elements seems overflow too. Please help me on this. Thank you.

Heading Here

Some text here

Another text here.

One more time.

html,
body {
  width: 100%;
  height: 100%;
}
.wrapper {
  width: 100%;
  height: 100%;
}
.wrapper-inner {
  width: 100%;
  height: 100%;
  position: relative;
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}

demo: https://codepen.io/rae0724/pen/jamzbX

I can't find a way to make those content at the current position and middle on this full screen height, except top:50% and minus it's height, but it's bad for responsive.

Body:
Try using CSS Positioning. Like:

.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
.wrapper-inner {
  position: absolute;
  top: 50%;
  transform: translateY(-41px);
}

Have a look at the snippet below:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
.wrapper-inner {
  position: absolute;
  top: 50%;
  transform: translateY(-41px);
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}

<div class="wrapper">
  <div class="wrapper-inner">
    <div class="section-1">
      <h2>Heading Here</h2>
      <p>Some text here</p>
    </div>
    <div class="section-2">
      <p>Another text here.</p>
      <p>One more time.</p>
    </div>
  </div>
</div>

Hope this helps!


问:
Build fails when using 'kotlin-kapt' with Realm
Environment : Android Studio 2.3.3, Gradle 2.3.3 and Kotlin 1.1.4-3

When I create a new Android project with Kotlin, everything works fine at first, adding

```<code>//in project's build.gradle
classpath "io.realm:realm-gradle-plugin:3.5.0"

//in app's build.gradle
apply plugin: 'realm-android'
</code>```

is OK. But after I add

```<code>apply plugin: 'kotlin-kapt'
</code>```

always raising Execution failed

```<code>e: Wrong plugin option format: null, should be plugin:<pluginId>:<optionName>=<value>
FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
</code>```

Stacktrace :

```<code>* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
    at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:8)
    at org.jetbrains.kotlin.gradle.internal.KaptTask.compile(KaptTask.kt:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:632)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:615)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 81 more
</code>```

I haven't added anything else, so everything is a default setup from Android Studio (with Empty Activity) and configured for Kotlin Android project.

Edit :

Order of plugins :

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'
</code>```

Moving apply plugin: 'realm-android' before apply plugin: 'kotlin-android' will make the build success. But making Realm doesn't work in the project, it always raise java.lang.IllegalArgumentException: MyObject is not part of the schema for this Realm

答: This looks like KT-20235. Please check if the path to your project (or any of your classpath dependencies) contains commas.</p>

Body:
Environment : Android Studio 2.3.3, Gradle 2.3.3 and Kotlin 1.1.4-3

When I create a new Android project with Kotlin, everything works fine at first, adding

//in project's build.gradle
classpath "io.realm:realm-gradle-plugin:3.5.0"

//in app's build.gradle
apply plugin: 'realm-android'

is OK. But after I add

apply plugin: 'kotlin-kapt'

always raising Execution failed

e: Wrong plugin option format: null, should be plugin:<pluginId>:<optionName>=<value>
FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.

Stacktrace :

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
    at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:8)
    at org.jetbrains.kotlin.gradle.internal.KaptTask.compile(KaptTask.kt:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:632)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:615)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 81 more

I haven't added anything else, so everything is a default setup from Android Studio (with Empty Activity) and configured for Kotlin Android project.

Edit :

Order of plugins :

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'

Moving apply plugin: 'realm-android' before apply plugin: 'kotlin-android' will make the build success. But making Realm doesn't work in the project, it always raise java.lang.IllegalArgumentException: MyObject is not part of the schema for this Realm


问:
variable === undefined vs. typeof variable === "undefined"
The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.

Global Variables: typeof variable === "undefined"

Local Variables: variable === undefined

Properties: object.prop === undefined

Why does jQuery use one approach for global variables and another for locals and properties?

答: Because undefined is not always declared, but jQuery declares undefined in its main function. So they use the safe undefined value internally, but outside, they use the typeof style to be safe.

ContentLicense: CC BY-SA 4.0


问:
JS click function open url in new windown
I create a link with text using html and i want to create when user click it goes to specific url. I new in javascript!!

here my code

```<code><a class="dt-button add_new_table_entry DTTT_button DTTT_button_new" tabindex="0" aria-controls="table_1" href="#">
<span>Add new</span>
</a>
</code>```

my script

```<code>$("dt-button add_new_table_entry DTTT_button DTTT_button_new").click(function () {
window.location="http://project.co/add-new/";
});
</code>```

UPDATE
I have create my script

```<code> let classic = document.getElementsByClassName('add_new DTTT_button DTTT_button_new');
for (var i=0; i < classic.length; i++) {
classic[i].addEventListener("click", clickfunc, false);
}
function.clickfunc(){
document.location.href="http://google.com";
}
</code>```

but give error unexpected token ;

答:
create a function :

```<code>function openlink()
{
window.open("http://project.co/add-new/","mywindow","menubar=no,resizable=1,width=400,height=400");
}
</code>```

then you call the function using this :

```<code><a href="javascript:openlink();">Link Text</a>
</code>```

Body:
I create a link with text using html and i want to create when user click it goes to specific url. I new in javascript!!

here my code

Add new

my script

$("dt-button add_new_table_entry DTTT_button DTTT_button_new").click(function () {
window.location="http://project.co/add-new/";
});

UPDATE
I have create my script

 let classic = document.getElementsByClassName('add_new DTTT_button DTTT_button_new');
for (var i=0; i < classic.length; i++) {
classic[i].addEventListener("click", clickfunc, false);
}
function.clickfunc(){
document.location.href="http://google.com";
}

but give error unexpected token ;

Body:
create a function :

function openlink()
{
window.open("http://project.co/add-new/","mywindow","menubar=no,resizable=1,width=400,height=400");
}

then you call the function using this :

<a href="javascript:openlink();">Link Text</a>


问:
Is it possible to send a request with the Needle module through another IP?
The request module has the parameter localAddress.

```<code> options = {
         url: "https://ru.tradeskinsfast.com/ajax/botsinventory",
         method: "post",
         headers: {
             'accept': 'application/json, text/javascript, */*; q=0.01',
             'accept-encoding' : 'gzip :deflate, br',
             'accept-language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
         },
         localAdress: someIp,
}
request(options, function(error, response, body){}
</code>```

How can I do it with the needle module?

答:
Needle is still a wrapper around Nodes http.request like request but needle doesn't allow you to pass localAddress specifically or to pass arbitrary options through to http.request.

Needle does support adding a custom http.Agent for a request though and the agent.createConnection method supports passing localAddress as it uses a standard socket connect.

A bit more complex to setup but possible to override the default behaviour.

```<code>const http = require('http')
const https = require('https')
const needle = require('needle')

class HttpAgentLocal extends http.Agent {

  constructor(options){
    super(options)
    if (options && options.localAddress) this._localAddress = options.localAddress
  }

  createConnection(options, callback){
     if (this._localAddress) options.localAddress = this._localAddress
     return super.createConnection(options, callback)
  }
}

class HttpsAgentLocal extends https.Agent {

  constructor(options){
    this._localAddress = options.localAddress
  }

  createConnection(options, callback){
     options.localAddress = this._localAddress
     return super.createConnection(options, callback)
  }
}

let server = http.createServer((req, res) => {
  console.log('request: %s - %s', req.method,req.url, req.connection.remoteAddress)
  res.end('hello\n')
})

server.listen(3121, async ()=> {
  console.log('listening')
  const agent = new HttpAgentLocal({ localAddress: '10.8.8.8' })
  let res = await needle('get','http://localhost:3121/', null, { agent: agent })
  console.log(res.body.toString())
  server.close()
})
</code>```

Body:
The request module has the parameter localAddress.

 options = {
         url: "https://ru.tradeskinsfast.com/ajax/botsinventory",
         method: "post",
         headers: {
             'accept': 'application/json, text/javascript, */*; q=0.01',
             'accept-encoding' : 'gzip :deflate, br',
             'accept-language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
         },
         localAdress: someIp,
}
request(options, function(error, response, body){}

How can I do it with the needle module?

Body:
Needle is still a wrapper around Nodes http.request like request but needle doesn't allow you to pass localAddress specifically or to pass arbitrary options through to http.request.

Needle does support adding a custom http.Agent for a request though and the agent.createConnection method supports passing localAddress as it uses a standard socket connect.

A bit more complex to setup but possible to override the default behaviour.

const http = require('http')
const https = require('https')
const needle = require('needle')

class HttpAgentLocal extends http.Agent {

  constructor(options){
    super(options)
    if (options && options.localAddress) this._localAddress = options.localAddress
  }

  createConnection(options, callback){
     if (this._localAddress) options.localAddress = this._localAddress
     return super.createConnection(options, callback)
  }
}

class HttpsAgentLocal extends https.Agent {

  constructor(options){
    this._localAddress = options.localAddress
  }

  createConnection(options, callback){
     options.localAddress = this._localAddress
     return super.createConnection(options, callback)
  }
}

let server = http.createServer((req, res) => {
  console.log('request: %s - %s', req.method,req.url, req.connection.remoteAddress)
  res.end('hello\n')
})

server.listen(3121, async ()=> {
  console.log('listening')
  const agent = new HttpAgentLocal({ localAddress: '10.8.8.8' })
  let res = await needle('get','http://localhost:3121/', null, { agent: agent })
  console.log(res.body.toString())
  server.close()
})


问:
Distribution certificate / private key not installed
Using Xcode 9.1, after building an iOS app, I want to archive it and upload it to the appStore for beta-testing.
But I get the following issue after clicking the button Upload to the App Store... and choosing Automatically manage signing:

"My Name" has one iOS Distribution certificate but its private key is
not installed. Contact the creator of this certificate to get a copy of the private key.

I do not know why this "private key is not installed", but the Distribution certificate may have been created on a different computer or something. In any case:

What is the simplest way to retrieve the missing private key and install it? In order to make things work.

答:
EDIT: I thought that the other computer is dead so I'm fixing my answer:

You should export the certificate from the first computer with it's private key and import it in the new computer.

I prefer the iCloud way, backup to iCloud and get it in the new computer.

If you can't do it with some reason, you can revoke the certificate in Apple developers site, then let Xcode to create a new one for you, it'll also create a fresh new private key and store it in your Keychain, just be sure to back it up in your preferred way


问:
How to add android target / API android-26 in android studio?
I am new in android development tools and I'm about to try cordova to develop android app using web technologies, but when i use the comand cordova requirements the result is this

```<code>Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: not installed
Please install Android target / API level: "android-26".

Hint: Open the SDK manager by running: "C:\Users\json\AppData\Local\Android\sdk\tools\android.bat"
You will require:
1. "SDK Platform" for API level android-26
2. "Android SDK Platform-tools (latest)
3. "Android SDK Build-tools" (latest)
Gradle: installed C:\Program Files\Android\Android Studio\gradle\gradle-4.1\bin\gradle
</code>```

When i installed the android studio the default API is android-27 and i dont know how to add android-26 API. Please help.

答:
Android Studio on macOS has platform settings at Preferences... > Appearance & Behavior > System Settings > Android SDK > SDK Platform tab.  Checking Android 8.0 (Oreo) having the API level 26 and clicking Apply installed the package and now the requirements check passes as follows:

```<code>Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-27,android-26
Gradle: installed /Applications/Android Studio.app/Contents/gradle/gradle-4.1/bin/gradle
</code>```

Hope this works on Windows as well.

Body:
I am new in android development tools and I'm about to try cordova to develop android app using web technologies, but when i use the comand cordova requirements the result is this

Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: not installed
Please install Android target / API level: "android-26".

Hint: Open the SDK manager by running: "C:\Users\json\AppData\Local\Android\sdk\tools\android.bat"
You will require:
1. "SDK Platform" for API level android-26
2. "Android SDK Platform-tools (latest)
3. "Android SDK Build-tools" (latest)
Gradle: installed C:\Program Files\Android\Android Studio\gradle\gradle-4.1\bin\gradle

When i installed the android studio the default API is android-27 and i dont know how to add android-26 API. Please help.

Body:
Android Studio on macOS has platform settings at Preferences... > Appearance & Behavior > System Settings > Android SDK > SDK Platform tab.  Checking Android 8.0 (Oreo) having the API level 26 and clicking Apply installed the package and now the requirements check passes as follows:

Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-27,android-26
Gradle: installed /Applications/Android Studio.app/Contents/gradle/gradle-4.1/bin/gradle

Hope this works on Windows as well.


问:
How do I efficiently iterate over each entry in a Java Map?
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it,  what is the most efficient way of going through the map?

Will the ordering of elements depend on the specific map implementation that I have for the interface?

答:
There are a lot of ways to do this. Below is a few simple steps:

Suppose you have one Map like:

```<code>Map<String, Integer> m = new HashMap<String, Integer>();
</code>```

Then you can do something like the below to iterate over map elements.

```<code>// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
    Entry<String, Integer> pair = me.next();
    System.out.println(pair.getKey() + ":" + pair.getValue());
}

// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
    System.out.println(me.getKey() + " : " + me.getValue());
}

// *********** Using keySet *****************************
for(String s : m.keySet()){
    System.out.println(s + " : " + m.get(s));
}

// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
    String key = me.next();
    System.out.println(key + " : " + m.get(key));
}
</code>```

OwnerDisplayName: iMack

Body:
There are a lot of ways to do this. Below is a few simple steps:

Suppose you have one Map like:

Map<String, Integer> m = new HashMap<String, Integer>();

Then you can do something like the below to iterate over map elements.

// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
    Entry<String, Integer> pair = me.next();
    System.out.println(pair.getKey() + ":" + pair.getValue());
}

// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
    System.out.println(me.getKey() + " : " + me.getValue());
}

// *********** Using keySet *****************************
for(String s : m.keySet()){
    System.out.println(s + " : " + m.get(s));
}

// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
    String key = me.next();
    System.out.println(key + " : " + m.get(key));
}


问:
Is there an easier way to use Windows ctrl+v (paste) functionality in a C# Console application?
I’ve build a console application that has a command interpreter. To make things easier I needed to add support for reading the clipboard when ctrl+v is pressed. When I press ctrl+v I see the symbol ^V in the console, so I’m replacing that character with the clipboard text. After some googling I’ve found out that the clipboard can be accessed by System.Windows.Forms.Clipboard.GetText().

My question is: Is there a better solution to add clipboard support to a console application? Possibly without using System.Windows.Forms.Clipboard? Maybe an interop call can do the trick?

One of the drawbacks of this solution is that the clipboard only works when the thread is defined as [STAThread]. It would also be a lot nicer if I could get rid of the ^V symbol.

This is the code of the current solution:

```<code>using System;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        public static readonly string ClipboardChar = Convert.ToChar(22).ToString();

        [STAThread]
        static void Main(string[] args)
        {
            Console.Write("Do some pastin': ");

            //read
            Console.ForegroundColor = ConsoleColor.White;
            string result = Console.ReadLine();
            Console.ResetColor();

            //read keyboard
            if (result.Contains(ClipboardChar))
            {
                result = result.Replace(ClipboardChar, Clipboard.GetText());
            }

            //write result
            Console.WriteLine("\nResult: ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(result);
            Console.ResetColor();

            Console.WriteLine("\nPress any key to continue...");
            Console.ReadKey();
        }
    }
}
</code>```

答: If you click the icon in the top left corner of the console application window you get a 'Edit' | 'Paste' option.</p>

Body:
I’ve build a console application that has a command interpreter. To make things easier I needed to add support for reading the clipboard when ctrl+v is pressed. When I press ctrl+v I see the symbol ^V in the console, so I’m replacing that character with the clipboard text. After some googling I’ve found out that the clipboard can be accessed by System.Windows.Forms.Clipboard.GetText().

My question is: Is there a better solution to add clipboard support to a console application? Possibly without using System.Windows.Forms.Clipboard? Maybe an interop call can do the trick?

One of the drawbacks of this solution is that the clipboard only works when the thread is defined as [STAThread]. It would also be a lot nicer if I could get rid of the ^V symbol.

This is the code of the current solution:

using System;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        public static readonly string ClipboardChar = Convert.ToChar(22).ToString();

        [STAThread]
        static void Main(string[] args)
        {
            Console.Write("Do some pastin': ");

            //read
            Console.ForegroundColor = ConsoleColor.White;
            string result = Console.ReadLine();
            Console.ResetColor();

            //read keyboard
            if (result.Contains(ClipboardChar))
            {
                result = result.Replace(ClipboardChar, Clipboard.GetText());
            }

            //write result
            Console.WriteLine("\nResult: ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(result);
            Console.ResetColor();

            Console.WriteLine("\nPress any key to continue...");
            Console.ReadKey();
        }
    }
}

ContentLicense: CC BY-SA 2.5


问:
ROC curve error
I have dataset like this

```<code>train <- sample(1:nrow(df), nrow(df)*0.80)
train <- df[train, ]
test <- df[-train, ]

NaiveBayes1 <-naiveBayes(purchased ~ .,data=train)
pre1 <- predict(NaiveBayes1,test,probability = TRUE)

library(pROC)
roc1 <- roc(test$purchased, pre1$posterior[,1])
</code>```

And I get this error:

Error in pre1$posterior : $ operator is invalid for atomic vectors

I have done in the class using LDA and it worked but for naivebays, it doesn't work. Any help will be appreciated.

答:
Change your last two lines from:

```<code>pre1 <- predict(NaiveBayes1, test, probability = TRUE)
roc1 <- roc(test$purchased, pre1$posterior[,1])
</code>```

To:

```<code>pre1 <- predict(NaiveBayes1, test, type = "raw")
roc1 <- roc(test$purchased, pre1[,1])
</code>```

Title: ROC curve error

Body:
I have dataset like this

train <- sample(1:nrow(df), nrow(df)*0.80)
train <- df[train, ]
test <- df[-train, ]

NaiveBayes1 <-naiveBayes(purchased ~ .,data=train)
pre1 <- predict(NaiveBayes1,test,probability = TRUE)

library(pROC)
roc1 <- roc(test$purchased, pre1$posterior[,1])

And I get this error:

Error in pre1$posterior : $ operator is invalid for atomic vectors

I have done in the class using LDA and it worked but for naivebays, it doesn't work. Any help will be appreciated.

Body:
Change your last two lines from:

pre1 <- predict(NaiveBayes1, test, probability = TRUE)
roc1 <- roc(test$purchased, pre1$posterior[,1])

To:

pre1 <- predict(NaiveBayes1, test, type = "raw")
roc1 <- roc(test$purchased, pre1[,1])


问:
Error CS0029 Cannot implicity convert System.Collections.Generic.List, return not working
My return is not working, error CS0029 is implying this:

System.Collections.Generic.List<namesolution> to namesolution
How can I make my return work?

This is my code:

```<code>    [Route("/getVeiculos")]
    public VeiculoModel getVeiculos()
    {
        List<VeiculoModel> list = new List<VeiculoModel>();
        list.Add( new VeiculoModel {
            idVeiculo = 1,
            corVeiculo = "Verde",
            marcaVeiculo = "Volks",
            modeloVeiculo = "UP!",
            placaVeiculo = "AAA-8754"

        });

        list.Add(new VeiculoModel
        {
            idVeiculo = 2,
            corVeiculo = "Azul",
            marcaVeiculo = "Volks",
            modeloVeiculo = "Fusca",
            placaVeiculo = "CDV-8754"
        });

        return list;
    }
enter code here
</code>```

答:
Your method getVeiculos() signature indicates you are trying to return a single instance of type VeiculoModel but the implementation is returning a list of VeiculoModel. Assuming the implementation is correct, update your method signature to:</p>

```<code>public List<VeiculoModel> getVeiculos()
{
    // implementation...
}
</code>```

Body:
My return is not working, error CS0029 is implying this:

System.Collections.Generic.List<namesolution> to namesolution
How can I make my return work?

This is my code:

    [Route("/getVeiculos")]
    public VeiculoModel getVeiculos()
    {
        List<VeiculoModel> list = new List<VeiculoModel>();
        list.Add( new VeiculoModel {
            idVeiculo = 1,
            corVeiculo = "Verde",
            marcaVeiculo = "Volks",
            modeloVeiculo = "UP!",
            placaVeiculo = "AAA-8754"

        });

        list.Add(new VeiculoModel
        {
            idVeiculo = 2,
            corVeiculo = "Azul",
            marcaVeiculo = "Volks",
            modeloVeiculo = "Fusca",
            placaVeiculo = "CDV-8754"
        });

        return list;
    }
enter code here

Body:
Your method getVeiculos() signature indicates you are trying to return a single instance of type VeiculoModel but the implementation is returning a list of VeiculoModel. Assuming the implementation is correct, update your method signature to:

public List<VeiculoModel> getVeiculos()
{
    // implementation...
}


问:
How to create signed APK for Android, Cordova, Mac OS, Upload Certificate?
All the instructions I can find for creating a signed APK with Cordova for Android seem to have been created before Google's new app signing protocol.

I've created an app signing certificate in the Play Console and have an upload certificate.

I can create a signed APK in Android Studio, but I need to do it in Terminal (Mac OS).

I can't find any instructions that are current.

Can somebody provide such instructions?

答:
I think I figured this out.

I created a build.json file and dropped it into my /www folder (I initially tried it in my /platforms/android folder but that file path didn't work).

{
  "android": {
    "debug": {
     "keystore": "/path to jks file",
      "storePassword": "PW",
      "alias": "youralias",
      "password" : "pw",
      "keystoreType": "jks"
  },
   "release": {
    "keystore": "/path to jks file",
      "storePassword": "PW",
      "alias": "youralias",
      "password" : "pw",
      "keystoreType": "jks"
        }
    }
}

Command line: cordova build android --release --buildConfig build.json

Since I'm not ready to increment a new version of my app, new version number, as required by the Play Console, I haven't tried uploading this new build, but I do have a signed APK.

Terminal provides you with a path to the new APK after Built the following apk(s):


问:
Array gives me 'Cannot read property of undefined' but console.logs show otherwhise
I'm trying to do a method in which i process an array of messages, every message haves an id of the user sending the message and the content of the meesage itself.

Once i get the array, i try to separate the messages by the user who send it (In order to style the messages according to the users later on).

I attempt to do this with a for loop to read the array, and an if to check if the logged user send such message or not.

The problem pops up when i want to read who send the message.

At first i thought "i may be writing the sentence wrong", so i used some consol.logs to see what was wrong. And i got an interesting situation going on: The variable shows correctly on the console, but i get an error once i want to evaluate on the if.

Here's the JavaScript code i'm running

```<code>function processMeesages(allMessages) {

  for (var i = 0; i <= allMessages.length; i++) {

    console.log('allMessages[' + i + '].userMsg', allMessages[i].userMsg)

    //Message from the logged user
    if (allMessages[i].userMsg == user.id) {
      chatMessages += '<div class="row ">' +
              '            <div class="col col-10 "></div>' +
              '            <div class="col card owner-container">' +
              '                <div class="item item-text-wrap owner">' +
                                  allMessages[i].contenido +
              '                </div>' +
              '            </div>' +
              '        </div>';
    }

    //Messages from the other user
    else {
      chatMessages += '<div class="row ">' +
              '            <div class="col card message-container">' +
              '                <div class="item item-text-wrap message">' +
                                  allMessages[i].contenido +
              '                </div>' +
              '            </div>' +
              '            <div class="col col-10 "></div>' +
              '        </div>';
    }
  }

  //Once the for loop ends (What's down didn't show up on the console)
  $rootScope.chatMessages = chatMessages;
  console.log('chatMessages', chatMessages)
  console.log('rootscopeChatMessages', $rootScope.chatMessages)
}
</code>```

Here's an image with what i get in the console and what the array haves inside (I put some labels on the picture)

答:
Seems like you are looping more than required. Your array only has two elements but your for loop tries to loop over 3 times, hence giving that access error because allMessages[2] is undefined.

```<code>function processMeesages(allMessages) {

  for (var i = 0; i < allMessages.length; i++) {

    console.log('allMessages[' + i + '].userMsg', allMessages[i].userMsg)

    .
    .
    .
    .
}
</code>```

Body:
I'm trying to do a method in which i process an array of messages, every message haves an id of the user sending the message and the content of the meesage itself.

Once i get the array, i try to separate the messages by the user who send it (In order to style the messages according to the users later on).

I attempt to do this with a for loop to read the array, and an if to check if the logged user send such message or not.

The problem pops up when i want to read who send the message.

At first i thought "i may be writing the sentence wrong", so i used some consol.logs to see what was wrong. And i got an interesting situation going on: The variable shows correctly on the console, but i get an error once i want to evaluate on the if.

Here's the JavaScript code i'm running

function processMeesages(allMessages) {

  for (var i = 0; i <= allMessages.length; i++) {

    console.log('allMessages[' + i + '].userMsg', allMessages[i].userMsg)

    //Message from the logged user
    if (allMessages[i].userMsg == user.id) {
      chatMessages += '
' +
              '

' +
              '
' +
              '
' +
                                  allMessages[i].contenido +
              '
' +
              '
' +
              '
';
    }

    //Messages from the other user
    else {
      chatMessages += '
' +
              '
' +
              '
' +
                                  allMessages[i].contenido +
              '
' +
              '
' +
              '

' +
              '
';
    }
  }

  //Once the for loop ends (What's down didn't show up on the console)
  $rootScope.chatMessages = chatMessages;
  console.log('chatMessages', chatMessages)
  console.log('rootscopeChatMessages', $rootScope.chatMessages)
}

Here's an image with what i get in the console and what the array haves inside (I put some labels on the picture)

Body:
Seems like you are looping more than required. Your array only has two elements but your for loop tries to loop over 3 times, hence giving that access error because allMessages[2] is undefined.

function processMeesages(allMessages) {

  for (var i = 0; i < allMessages.length; i++) {

    console.log('allMessages[' + i + '].userMsg', allMessages[i].userMsg)

    .
    .
    .
    .
}


问:
JMeter - can not assign password variable correctly
I set username and password from CSV file user:sysadmin, pass:"Pass@123456" but password is encrypted wrong upon request

```<code>User=sysadmin&Pass=Pass%40123456
</code>```

答:
@ is encoded when sending HTTP request.

You need to add HTTP Header Manager  with variable name Content-Type with value application/x-www-form-urlencoded,
This will tell the server that the values need to be decoded

Body:
I set username and password from CSV file user:sysadmin, pass:"Pass@123456" but password is encrypted wrong upon request

User=sysadmin&Pass=Pass%40123456


问:
Designing multiple types of payment schema in SQL?
I've payment system where I can do two types of payment for an order.

Online -  Mobile payment

Offline - Cash/ Cheque

I've credited 4 tables, I'm outlining only important columns not everything for simplicity.

```<code>List of table Names

Payment
CashPaymentDetails
ChequePaymentDetails
MobilePaymentDetails

Schema Details

CashPaymentDetails
cash_id int
cash_amount decimal(18,2)

ChequePaymentDetails
cheque_id int
cheque_amount decimal(18,2)
cheque_type

MobilePaymentDetails
mobile_id int
mobile_amount decimal(18,2)

Payment
payment_id int
payment_amount  decimal(18,2)
fk_cash_id int (foreign key reference to CashPaymentDetails table)
fk_cheque_id (foreign key reference to ChequePaymentDetails table)
fk_mobile_id (foreign key reference to MoblePaymentDetails table)
</code>```

User can do either cash/cheque/mobile, only one payment mode, this makes my two foreign keys NULL which i feel is overhead because if going forward I've 10 different types of payment method, 9 Fk references will be NULL.

Payment

```<code>Payment_id payment_amount fk_cash_id fk_cheque_id fk_mobile_id
1 300 1 NULL NULL
2 200 NULL 1 NULL
3 400 NULL NULL 1
</code>```

what should be an optimal design to create this schema?

答:
My advice is this.
On the Payment table, remove all those foreign keys and add these 2 fields.

```<code>processor_type enum['bank', 'cheque', 'card']
transaction_id fk to the processor table.
</code>```

With this, each time you update/add a new processor, you just need to update the enum such that it takes the new set of payment processors. The transaction_id is a foreign key to the appropriate table depending on the processor_type.

If you are using laravel, you can make use of polymorphic relationships
That's my suggestion.

Body:
I've payment system where I can do two types of payment for an order.

Online -  Mobile payment

Offline - Cash/ Cheque

I've credited 4 tables, I'm outlining only important columns not everything for simplicity.

List of table Names

Payment
CashPaymentDetails
ChequePaymentDetails
MobilePaymentDetails

Schema Details

CashPaymentDetails
cash_id int
cash_amount decimal(18,2)

ChequePaymentDetails
cheque_id int
cheque_amount decimal(18,2)
cheque_type

MobilePaymentDetails
mobile_id int
mobile_amount decimal(18,2)

Payment
payment_id int
payment_amount  decimal(18,2)
fk_cash_id int (foreign key reference to CashPaymentDetails table)
fk_cheque_id (foreign key reference to ChequePaymentDetails table)
fk_mobile_id (foreign key reference to MoblePaymentDetails table)

User can do either cash/cheque/mobile, only one payment mode, this makes my two foreign keys NULL which i feel is overhead because if going forward I've 10 different types of payment method, 9 Fk references will be NULL.

Payment

Payment_id payment_amount fk_cash_id fk_cheque_id fk_mobile_id
1 300 1 NULL NULL
2 200 NULL 1 NULL
3 400 NULL NULL 1

what should be an optimal design to create this schema?

Body:
My advice is this.
On the Payment table, remove all those foreign keys and add these 2 fields.

processor_type enum['bank', 'cheque', 'card']
transaction_id fk to the processor table.

With this, each time you update/add a new processor, you just need to update the enum such that it takes the new set of payment processors. The transaction_id is a foreign key to the appropriate table depending on the processor_type.

If you are using laravel, you can make use of polymorphic relationships
That's my suggestion.


问:
curly braces in es6 arrow function for each
We create presentational component or stateless component like this

```<code>const MyComponent = () => {
   return(<div>my component</div>)
}
</code>```

but I'd seen this

```<code>const MyComponent = () =>
   <div>
     <h1>head</h1>
     my component
   </div>
</code>```

so now I'm confused when the braces is needed when using es6's arrow function.

This confused me on when rendering a list using map

shorter version

```<code><div>
{map(o =>
   <div>{o.name}</div>
)}
</div>
</code>```

longer version

```<code><div>
    {map(o => {
     return(<div>{o.name}</div>)
     })}
</div>
</code>```

Both are correct, but why write longer?

答:
```<code>{map(o => // without curly brackets
   <div>{o.name}</div> // this will be returned implicitly
)}

{map(o => { // with curly brackets
    return <div>{o.name}</div> // you need to return explicitly
    }
)}
</code>```

If you do curly brackets ,
You have to explicilty return the data ,

When to use which one?

When you have mutliple line of execution you need to do curly brackets and return from it

But if you have single line of execution, that you need to return , then there is no need of curly brackets and return , it will return implicitly.

Same as If condition

```<code>if(true)
    // do this for single line
else
    // do this for single line

if() {
    // do this for multiple line
} else {
    // do this for multiple line
}
</code>```

Body:
We create presentational component or stateless component like this

const MyComponent = () => {
   return(
my component
)
}

but I'd seen this

const MyComponent = () =>

head

     my component

so now I'm confused when the braces is needed when using es6's arrow function.

This confused me on when rendering a list using map

shorter version

{map(o =>

{o.name}

)}

longer version

    {map(o => {
     return(
{o.name}
)
     })}

Both are correct, but why write longer?

Body:
{map(o => // without curly brackets
   <div>{o.name}</div> // this will be returned implicitly
)}

{map(o => { // with curly brackets
    return <div>{o.name}</div> // you need to return explicitly
    }
)}

If you do curly brackets ,
You have to explicilty return the data ,

When to use which one?

When you have mutliple line of execution you need to do curly brackets and return from it

But if you have single line of execution, that you need to return , then there is no need of curly brackets and return , it will return implicitly.

Same as If condition

if(true)
    // do this for single line
else
    // do this for single line

if() {
    // do this for multiple line
} else {
    // do this for multiple line
}


问:
C# How to sort int when value is too large
```<code>8
723
77715926535897932384626433832795
</code>```

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

答: If you don't have a requirement that the values need to be an integer, you can use a double instead of Int64 for all of the values. The max value for a double is  1.7976931348623157E+308, so it's much bigger than the example one you showed. That will probably be an easy code change too. BigInteger will require some other code changes as people have mentioned.

Body:
8
723
77715926535897932384626433832795

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?


问:
Receptive Field Arithmetic on the TF CNN example
Below is the code tensorflow provides. I will describe my current understanding of the receptive field size changes and would greatly appreciate if someone could let me know where my misunderstanding is.

Overview:
[28,28] -> 32 [24,24] -> 32 [12,12] -> 2048 [8,8]

Long version:

Start off with the [28,28] array

The first convolution layer has 32 filters with a kernel size of [5,5] so the output is 32 [24,24]s.

Pooling layer with a kernel of [2,2] and stride of 2 maintains the number of arrays but reduces the size so the output is 32 [12,12]s.

The next convolution layer has 64 filters of size [5,5] so we end up with 2048 [8,8]s

2048 [8,8]s is not what is represented in the subsequent code. What is my error here? All guidance is appreciated.

```<code>  # Input Layer
  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)
</code>```

答: The conv2d layers are using padding="same", which means the input is padded with zeros so that the output is the same size.  To get the result you expect we would use padding="valid", which means no padding.

Body:
Below is the code tensorflow provides. I will describe my current understanding of the receptive field size changes and would greatly appreciate if someone could let me know where my misunderstanding is.

Overview:
[28,28] -> 32 [24,24] -> 32 [12,12] -> 2048 [8,8]

Long version:

Start off with the [28,28] array

The first convolution layer has 32 filters with a kernel size of [5,5] so the output is 32 [24,24]s.

Pooling layer with a kernel of [2,2] and stride of 2 maintains the number of arrays but reduces the size so the output is 32 [12,12]s.

The next convolution layer has 64 filters of size [5,5] so we end up with 2048 [8,8]s

2048 [8,8]s is not what is represented in the subsequent code. What is my error here? All guidance is appreciated.

  # Input Layer
  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)


问:
cumsum for unique value using dplyr mutate
The dummy dataset is:

```<code>data <- data.frame(
  id = c(1,1,2,2,3,4,5,6),
  value = c(10,10,20,20,10,30,40,50),
  other = c(1,2,3,4,5,6,7,8)
)
</code>```

The data was output of group_by(id) operation in dplyr pipe. Each id is associated with at most one value and two different id can have same value. I need to find cumulative sum across ids by adding new column:
cum_col = c(10,10,30,30,40,70,110,160)
The cumsum in mutate will find cumulative sum across whole column of values and doesn't pick only one value per group. summarise is not useful as there are other columns I need to keep intact.

Is there a way out without using summarise and then join-ing it backward? Or please point me to link if it has been answered before.

Edit: Just for info the actual data has ~2 million rows and 100 columns.

答:
We could also do with duplicated

```<code>library(dplyr)
data %>%
     mutate(cum_col = cumsum(value*!duplicated(id)))
#  id value other cum_col
#1  1    10     1      10
#2  1    10     2      10
#3  2    20     3      30
#4  2    20     4      30
#5  3    10     5      40
#6  4    30     6      70
#7  5    40     7     110
#8  6    50     8     160
</code>```

Body:
The dummy dataset is:

data <- data.frame(
  id = c(1,1,2,2,3,4,5,6),
  value = c(10,10,20,20,10,30,40,50),
  other = c(1,2,3,4,5,6,7,8)
)

The data was output of group_by(id) operation in dplyr pipe. Each id is associated with at most one value and two different id can have same value. I need to find cumulative sum across ids by adding new column:
cum_col = c(10,10,30,30,40,70,110,160)
The cumsum in mutate will find cumulative sum across whole column of values and doesn't pick only one value per group. summarise is not useful as there are other columns I need to keep intact.

Is there a way out without using summarise and then join-ing it backward? Or please point me to link if it has been answered before.

Edit: Just for info the actual data has ~2 million rows and 100 columns.

Body:
We could also do with duplicated

library(dplyr)
data %>%
     mutate(cum_col = cumsum(value*!duplicated(id)))
#  id value other cum_col
#1  1    10     1      10
#2  1    10     2      10
#3  2    20     3      30
#4  2    20     4      30
#5  3    10     5      40
#6  4    30     6      70
#7  5    40     7     110
#8  6    50     8     160