问:
Convert UTC datetime string to local datetime
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

```<code>datetime.utcfromtimestamp(timestamp)
</code>```

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

```<code>"2011-01-21 02:37:21"
</code>```

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

答:
I traditionally defer this to the frontend -- send times from the backend as timestamps or some other datetime format in UTC, then let the client figure out the timezone offset and render this data in the proper timezone.

For a webapp, this is pretty easy to do in javascript -- you can figure out the browser's timezone offset pretty easily using builtin methods and then render the data from the backend properly.

Body:
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

datetime.utcfromtimestamp(timestamp)

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

"2011-01-21 02:37:21"

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.


来源: stackexchange

问:
AWS Sign In Loop - Can't Access the Portal
Issue: I am trying to sign in as a root user for my account from the AWS portal, but now, after I adding my password I keep getting redirected to:
https://portal.aws.amazon.com/billing/signup?redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start, no matter what.

It was working fine till today, first time I've encountered this redirect.

Main Browser : Chrome - Version 62.0.3202.94

Based on what on similar cases found on google I tried the following and still did not manage to sort out the issue:

-Chrome: deleted all the cookies and cache data

-Chrome: restarted the device and also the browser

-Chrome: used incognito mode

-Firefox (an aws member said is the most suitable browser): tried normal and private mode

-Firefox: deleted all the cookies and cache data

-Edge: tried normal and private mode

Someone suggested already to make use of S3Browser, it does not seem as a efficient solution just to access the AWS Portal a few times a week so I am keeping it as the last resort.

If anyone experienced the same issue or has any more suggestions/ideas would greatly appreciate some help.

Thanks in advance.

答:
I contacted AWS regarding the issue and they suggested to reset my password by going through https://signin.aws.amazon.com because they saw I have two accounts under the same email address. I did reset my password but this did not help and I was keep getting sent to the same screen to finish my registration.

Due to the fact that I reset my password for my AWS account, when I tried to do some Christmas shopping through the normal  https://www.amazon.co.uk it was prompting me with a message saying that I have another account active (the one from AWS I presume). I just reset my password for my https://www.amazon.co.uk account and it seems that the AWS account start working normally again.

Based on this experience if you encounter the same issue, I would recommend to try and reset the password for both AWS and the online shop https://www.amazon.com.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Postion absolute effecting padding of parent div
I am trying to fix a button to the right edge of a div.

HTML:

```<code><div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
</div>
</code>```

CSS:

```<code> #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }
</code>```

After applying position: absolute:

You can see in the image above that original padding: 20px on the parent div is ignored.

While removing position: absolute:

Brings the original padding back but as you can see the button is then not to the right. Applying float: right has the same effect.

Can somebody help me fix this issues and more importantly explain whats causing this so I can better learn. Apologies if this is a very basic question.

答:
It is not ignored, absolute position will not take the padding of parent div. Just set the height of div and center the absolute element. The 20px padding is probabbly the entire height of parent div, if the child element is absolute. To clarify better: Your header is taking the height of 40px (20px padding top, 20px padding bottom), and your absolute button is not going to change the height, however if you don't set the position to absolute, the parent div will take the height of button + 40px of padding.

#header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
</div></code>```

Body:
I am trying to fix a button to the right edge of a div.

HTML:

  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>

CSS:

 #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }

After applying position: absolute:

You can see in the image above that original padding: 20px on the parent div is ignored.

While removing position: absolute:

Brings the original padding back but as you can see the button is then not to the right. Applying float: right has the same effect.

Can somebody help me fix this issues and more importantly explain whats causing this so I can better learn. Apologies if this is a very basic question.

Body:
It is not ignored, absolute position will not take the padding of parent div. Just set the height of div and center the absolute element. The 20px padding is probabbly the entire height of parent div, if the child element is absolute. To clarify better: Your header is taking the height of 40px (20px padding top, 20px padding bottom), and your absolute button is not going to change the height, however if you don't set the position to absolute, the parent div will take the height of button + 40px of padding.

#header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }

<div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
</div>


问:
Wrap every 4 divs - wrong behavior
I'm using the code below to wrap every 4 divs with class .wrap4 inside a div with class .wrapList

Js code:

```<code>function Wrap(){
        var $children = $('.wrap4');
        for(var i = 0, l = $children.length; i < l; i += 4) {
            $children.slice(i, i+4).wrapAll('<div class="wrapList"></div>');
        }
};
</code>```

for example:

```<code><div class="row">
  <div class="wrap4">1</div>
  <div class="wrap4">2</div>
  <div class="wrap4">3</div>
  <div class="wrap4">4</div>
  <div class="wrap4">5</div>
  <div class="wrap4">6</div>
  <div class="wrap4">7</div>
</div>
</code>```

Result:

```<code><div class="row">
  <div class="wrapList">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
    <div class="wrap4">4</div>
   </div>
   <div class="wrapList">
    <div class="wrap4">5</div>
    <div class="wrap4">6</div>
    <div class="wrap4">7</div>
  </div>
</div>
</code>```

It works great, but if the divs before the wrapping are in two rows instead of one, for example:

```<code><div class="row">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
</div>
<div class="row">
  <div class="wrap4">4</div>
  <div class="wrap4">5</div>
  <div class="wrap4">6</div>
  <div class="wrap4">7</div>
</div>
</code>```

The result will not respect the rows and it will move the 4 to the top row to complete a line of 4 divs, for example:

```<code><div class="row">
  <div class="wrapList">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
    <div class="wrap4">4</div> (this div belong to the row below)
  </div>
</div>
<div class="row">
  <div class="wrapList">
    <div class="wrap4">5</div>
    <div class="wrap4">6</div>
    <div class="wrap4">7</div>
  </div>
</div>
</code>```

How can I make the code respect the rows?

Thank you very much!!!

答:
You can select each row and then iterate through each row and look for wrap4 class and use wrapAll().

function Wrap(){
  $('.row').each(function(){
    var $children = $(this).find('.wrap4');
    for(var i = 0, l = $children.length; i < l; i += 4) {
        $children.slice(i, i+4).wrapAll('

');
    }
   });
};
Wrap();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
</div>
<div class="row">
  <div class="wrap4">4</div>
  <div class="wrap4">5</div>
  <div class="wrap4">6</div>
  <div class="wrap4">7</div>
</div></code>```

Title: Wrap every 4 divs - wrong behavior

Body:
I'm using the code below to wrap every 4 divs with class .wrap4 inside a div with class .wrapList

Js code:

function Wrap(){
        var $children = $('.wrap4');
        for(var i = 0, l = $children.length; i < l; i += 4) {
            $children.slice(i, i+4).wrapAll('

');
        }
};

for example:

1

2

3

4

5

6

7

Result:

1

2

3

4

5

6

7

It works great, but if the divs before the wrapping are in two rows instead of one, for example:

1

2

3

4

5

6

7

The result will not respect the rows and it will move the 4 to the top row to complete a line of 4 divs, for example:

1

2

3

4
 (this div belong to the row below)

5

6

7

How can I make the code respect the rows?

Thank you very much!!!

Body:
You can select each row and then iterate through each row and look for wrap4 class and use wrapAll().

function Wrap(){
  $('.row').each(function(){
    var $children = $(this).find('.wrap4');
    for(var i = 0, l = $children.length; i < l; i += 4) {
        $children.slice(i, i+4).wrapAll('<div class="wrapList"></div>');
    }
   });
};
Wrap();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
</div>
<div class="row">
  <div class="wrap4">4</div>
  <div class="wrap4">5</div>
  <div class="wrap4">6</div>
  <div class="wrap4">7</div>
</div>


问:
Show model layout / design (with all connections) in Keras
I have major differences when testing a Keras LSTM model after I've trained it compared to when I load that trained model from a .h5 file (Accuracy of the first is always > 0.85 but of the later is always below < 0.2 i.e. a random guess).

However I checked the weights, they are identical and also the sparse layout Keras give me via plot_model is the same, but since this only retrieves a rough overview:

Is there away to show the full layout of a Keras model (especially node connections)?

答:
If you're using tensorflow backend, apart from plot_model, you can also use keras.callbacks.TensorBoard callback to visualize the whole graph in tensorboard. Example:

callback = keras.callbacks.TensorBoard(log_dir='./graph',
                                       histogram_freq=0,
                                       write_graph=True,
                                       write_images=True)
model.fit(..., callbacks=[callback])
```

<p>Then run <code>tensorboard --logdir ./graph</code> from the same directory.</p>

<p>This is a quick shortcut, but you can go even further with that.
For example, add tensorflow code to define (load) the model within custom <code>tf.Graph</code> instance, like this:</p>

<pre class="lang-py prettyprint-override"><code>from keras.layers import LSTM
import tensorflow as tf

my_graph = tf.Graph()
with my_graph.as_default():
  # All ops / variables in the LSTM layer are created as part of our graph
  x = tf.placeholder(tf.float32, shape=(None, 20, 64))
  y = LSTM(32)(x)
</code>```

.. after which you can list all graph nodes with dependencies, evaluate any variable, display the graph topology and so on, to compare the models.

I personally think, the simplest way is to setup your own session. It works in all cases with minimal patching:

import tensorflow as tf
from keras import backend as K

sess = tf.Session()
K.set_session(sess)
...
# Now can evaluate / access any node in this session, e.g. `sess.graph`
```

Body:
If you're using tensorflow backend, apart from plot_model, you can also use keras.callbacks.TensorBoard callback to visualize the whole graph in tensorboard. Example:

callback = keras.callbacks.TensorBoard(log_dir='./graph',
                                       histogram_freq=0,
                                       write_graph=True,
                                       write_images=True)
model.fit(..., callbacks=[callback])

Then run tensorboard --logdir ./graph from the same directory.

This is a quick shortcut, but you can go even further with that.
For example, add tensorflow code to define (load) the model within custom tf.Graph instance, like this:

from keras.layers import LSTM
import tensorflow as tf

my_graph = tf.Graph()
with my_graph.as_default():
  # All ops / variables in the LSTM layer are created as part of our graph
  x = tf.placeholder(tf.float32, shape=(None, 20, 64))
  y = LSTM(32)(x)

.. after which you can list all graph nodes with dependencies, evaluate any variable, display the graph topology and so on, to compare the models.

I personally think, the simplest way is to setup your own session. It works in all cases with minimal patching:

import tensorflow as tf
from keras import backend as K

sess = tf.Session()
K.set_session(sess)
...
# Now can evaluate / access any node in this session, e.g. `sess.graph`


问:
Lightweight AJAX objects recommendations?
I'm building a custom widget and i'm not supposed to use any framework such as jQuery, i need a lightweight cross browser object that supports POST & GET with callback, i've seen some solutions online but they include a lot of useless stuffs.

Thanks

答:
If you can't use JQuery, you can write one from scratch without using any library:-</p>

```<code>var xmlhttp;

if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
}
else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    document.getElementById("yourdiv").innerHTML=xmlhttp.responseText;
  }
}

// change "GET" to "POST" if you want to POST
xmlhttp.open("GET","/yourlink",true);
xmlhttp.send();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you can't use JQuery, you can write one from scratch without using any library:-

var xmlhttp;

if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
}
else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    document.getElementById("yourdiv").innerHTML=xmlhttp.responseText;
  }
}

// change "GET" to "POST" if you want to POST
xmlhttp.open("GET","/yourlink",true);
xmlhttp.send();


问:
Font not set to Arial in outgoing email (by SendGrid) from my .NET windows app
The text in the outgoing emails from my app is plain non-proportional text.

I tried to make it Arial.  But it is still not Arial.

Here is what I send to SendGrid, which sends the email:

```<code><p><font face="Arial">```Message```</font></p>
</code>```

答:
The problem is using these two:

```</code></li>
</ul>

<p>Replace it with the following:</p>

<pre class="lang-html prettyprint-override"><code><p style="font-family: Arial; white-space: pre-wrap;">Message</p>
</code>```

The ```</code> changes the font family here. And the <code><font></code> is deprecated.</p>

<p>The <code>style</code> attribute will be a replacement for the following:</p>

<ul>
<li><code><font></code> => <code>font-family: Arial;</code></li>
<li><code>``` => white-space: pre-wrap;

Body:
The text in the outgoing emails from my app is plain non-proportional text.

I tried to make it Arial.  But it is still not Arial.

Here is what I send to SendGrid, which sends the email:

Message

Body:
The problem is using these two:

<font>

<pre>

Replace it with the following:

<p style="font-family: Arial; white-space: pre-wrap;">Message</p>

The <pre> changes the font family here. And the <font> is deprecated.

The style attribute will be a replacement for the following:

<font> => font-family: Arial;

<pre> => white-space: pre-wrap;


问:
HTML.EditorFor renders nested class properties without id
This is an ASP.Net web application, a hybrid of webforms and MVC v5.2.3.  When I call Html.EditorFor on properties of the nested class the inputs render without an "id" attribute.  How come? And is there anything I can change in the model to force asp.net to render an "id" attribute?

My model, "Parent", contains a nested class, "Child":

```<code>public class Parent
{
    public string ParentName {get;set;}

    public class _Child
    {
        public string ChildName {get;set;}
    }

    public Child _Child {get;set;}
}
</code>```

On the view, when I render Parent.ParentName using Html.EditorFor(), it renders with both the "Name" and "Id" attributes.  In other words, when I put this in the *.cshtml file:

```<code>@Html.EditorFor(m => m.ParentName)
</code>```

It renders the following HTML:

```<code><input id="ParentName" name="ParentName" type="text" value="" />
</code>```

However, when I render Parent._Child.ChildName, it renders without the "Id" attribute.  In other words, when I put this in the *.cshtml file:

```<code>@Html.EditorFor(m => m._Child.ChildName)
</code>```

It renders the following HTML, without the "id" attribute:

```<code><input name="_Child.ChildName" type="text" value="" />
</code>```

How come? And can I do anything I the model to force generation of "id"?  I realize I can add it myself using new HtmlAttributes and so on.

答:
This uses the HTML 4 specification https://www.w3.org/TR/html401/types.html#case-sensitive which says that is must start with a letter, change the underscore to a letter and it should be OK.

Purely opinion but I would not use an underscore here anyway simply because it is harder to type.

Body:
This is an ASP.Net web application, a hybrid of webforms and MVC v5.2.3.  When I call Html.EditorFor on properties of the nested class the inputs render without an "id" attribute.  How come? And is there anything I can change in the model to force asp.net to render an "id" attribute?

My model, "Parent", contains a nested class, "Child":

public class Parent
{
    public string ParentName {get;set;}

    public class _Child
    {
        public string ChildName {get;set;}
    }

    public Child _Child {get;set;}
}

On the view, when I render Parent.ParentName using Html.EditorFor(), it renders with both the "Name" and "Id" attributes.  In other words, when I put this in the *.cshtml file:

@Html.EditorFor(m => m.ParentName)

It renders the following HTML:

<input id="ParentName" name="ParentName" type="text" value="" />

However, when I render Parent._Child.ChildName, it renders without the "Id" attribute.  In other words, when I put this in the *.cshtml file:

@Html.EditorFor(m => m._Child.ChildName)

It renders the following HTML, without the "id" attribute:

<input name="_Child.ChildName" type="text" value="" />

How come? And can I do anything I the model to force generation of "id"?  I realize I can add it myself using new HtmlAttributes and so on.


问:
error trying to make sandbox paypal to work with rails?
I am having problems integrating paypal payment gateway with rails. I will explain below the steps i did.

I first went to developer.paypal.com

I created two sandbox accounts one for buyer and one for business account.

I changed business account to Business-Pro

I then installed activemerchant gem in rails.

In config/environments/development.rb i pasted the following chunk

```<code>  config.after_initialize do
    ActiveMerchant::Billing::Base.mode = :test
    paypal_options = {
      login: "aGthYkgkYXVA_api1.gmail.com",
      password: "DH2RB21WR2EWNSTM",
      signature: "ApBHX2qbpxJW-Ll3oP22LSao0WeuAT.A.uNyDDqIArQeMLYzMTqsZnCW"
    }
    ::GATEWAY = ActiveMerchant::Billing::PaypalGateway.new(paypal_options)
end
</code>```

Then in controller i created a test method and pasted code to do checkout

```<code> # ActiveMerchant accepts all amounts as Integer values in cents
        amount = 1000  # $10.00

        # The card verification value is also known as CVV2, CVC2, or CID
        credit_card = ActiveMerchant::Billing::CreditCard.new(
                        :brand => 'visa',
                        :first_name         => 'Bob',
                        :last_name          => 'Bobsen',
                        :number             => '4132033791119477',
                        :month              => 3,
                        :year               => 2022,
                        :verification_value => '123')

        # Validating the card automatically detects the card type
        if credit_card.validate.empty?
          # Capture $10 from the credit card
          response = GATEWAY.purchase(amount, credit_card, :ip => '128.1.1.1')

          if response.success?
            puts "Successfully charged $#{sprintf("%.2f", amount / 100)} to the credit card #{credit_card.display_number}"
          else
            raise StandardError, response.message
          end
        end
</code>```

when i execute the controller method i get the following error

This transaction cannot be processed. The merchant's account is not
  able to process transactions.

I am wondering the reason for this error.

I used credit card number and exp date from the buyer sandbox account i created above.

I appreciate any help!

答:
It's in their docs:

10548  This transaction cannot be processed. The merchant's account is not able to process transactions.   The merchant account attempting the transaction is not a business account at PayPal. Check your account settings.

-

10549  This transaction cannot be processed. The merchant's account is not able to process transactions.   The merchant account attempting the transaction is not able to process Direct Payment transactions. Contact PayPal for more information.

I'd check the status of your account and ensure it's definitely switched to business. Have a poke around it there and let me know how you get on!

Body:
I am having problems integrating paypal payment gateway with rails. I will explain below the steps i did.

I first went to developer.paypal.com

I created two sandbox accounts one for buyer and one for business account.

I changed business account to Business-Pro

I then installed activemerchant gem in rails.

In config/environments/development.rb i pasted the following chunk

  config.after_initialize do
    ActiveMerchant::Billing::Base.mode = :test
    paypal_options = {
      login: "aGthYkgkYXVA_api1.gmail.com",
      password: "DH2RB21WR2EWNSTM",
      signature: "ApBHX2qbpxJW-Ll3oP22LSao0WeuAT.A.uNyDDqIArQeMLYzMTqsZnCW"
    }
    ::GATEWAY = ActiveMerchant::Billing::PaypalGateway.new(paypal_options)
end

Then in controller i created a test method and pasted code to do checkout

 # ActiveMerchant accepts all amounts as Integer values in cents
        amount = 1000  # $10.00

        # The card verification value is also known as CVV2, CVC2, or CID
        credit_card = ActiveMerchant::Billing::CreditCard.new(
                        :brand => 'visa',
                        :first_name         => 'Bob',
                        :last_name          => 'Bobsen',
                        :number             => '4132033791119477',
                        :month              => 3,
                        :year               => 2022,
                        :verification_value => '123')

        # Validating the card automatically detects the card type
        if credit_card.validate.empty?
          # Capture $10 from the credit card
          response = GATEWAY.purchase(amount, credit_card, :ip => '128.1.1.1')

          if response.success?
            puts "Successfully charged $#{sprintf("%.2f", amount / 100)} to the credit card #{credit_card.display_number}"
          else
            raise StandardError, response.message
          end
        end

when i execute the controller method i get the following error

This transaction cannot be processed. The merchant's account is not
  able to process transactions.

I am wondering the reason for this error.

I used credit card number and exp date from the buyer sandbox account i created above.

I appreciate any help!


问:
Unable to receive response using RestEase
The response received is the following:</p>

```<code>'UTF8' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.
</code>```

答:
I think the problem is that the server returns the wrong charset name in header. Instead charset=utf-8 it set charset=utf8.

And in the point of deserialization, the HttpClient (RestEase use it) does not understand what encoding to use.

To solve the problem, you need to add a new provider that will point to the usual UTF8 encoding.

You should add code at "global" level (e.g. Main method):

```<code>EncodingProvider provider = new CustomUtf8EncodingProvider();
Encoding.RegisterProvider(provider);
</code>```

And class, witch return UTF8 encoding for wrong charset name:

```<code>public class CustomUtf8EncodingProvider : EncodingProvider
{
    public override Encoding GetEncoding(string name)
    {
        return name == "utf8" ? Encoding.UTF8 : null;
    }

    public override Encoding GetEncoding(int codepage)
    {
        return null;
    }
}
</code>```

I check it like this

```<code>EncodingProvider provider = new CustomUtf8EncodingProvider();
Encoding.RegisterProvider(provider); //If comment this row - you get exception "'UTF8' is not a supported encoding name...", if uncomment - it works good
Console.WriteLine(Encoding.GetEncoding("utf8").GetString(new byte[]{0x31,0x32,0x33}));
</code>```

Note

It works in .net 4.6 or higher only

Body:
The response received is the following:

'UTF8' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.

Body:
I think the problem is that the server returns the wrong charset name in header. Instead charset=utf-8 it set charset=utf8.

And in the point of deserialization, the HttpClient (RestEase use it) does not understand what encoding to use.

To solve the problem, you need to add a new provider that will point to the usual UTF8 encoding.

You should add code at "global" level (e.g. Main method):

EncodingProvider provider = new CustomUtf8EncodingProvider();
Encoding.RegisterProvider(provider);

And class, witch return UTF8 encoding for wrong charset name:

public class CustomUtf8EncodingProvider : EncodingProvider
{
    public override Encoding GetEncoding(string name)
    {
        return name == "utf8" ? Encoding.UTF8 : null;
    }

    public override Encoding GetEncoding(int codepage)
    {
        return null;
    }
}

I check it like this

EncodingProvider provider = new CustomUtf8EncodingProvider();
Encoding.RegisterProvider(provider); //If comment this row - you get exception "'UTF8' is not a supported encoding name...", if uncomment - it works good
Console.WriteLine(Encoding.GetEncoding("utf8").GetString(new byte[]{0x31,0x32,0x33}));

Note

It works in .net 4.6 or higher only


问:
ResultSet closed (prior to insert into)
Have an issue with a closed ResultSet prior to a SQL insert (Java / Netbeans)

```<code>Connection var2 = DBConnPool.getInstance().getConnection();
Statement var3 = null;
String var5;
ResultSet var8 = null;

try {
    var3 = var2.createStatement();

    var5 = "insert into triggers (ts, nodeip, trapname) values (now(), '"+ipaddress+"', '"+trapname+"')";
    var3.execute(var5);

    var5 = "select asset.id as assetid, node.id as nodeid \n" +
        "from asset, node\n" +
        "where asset.name LIKE 'Trigger%'\n" +
        "and node.ipaddress=\'"+ipaddress+"'";
    var8 = var3.executeQuery(var5);

    while(var8.next()){
        int var31 = var8.getInt("assetid");
        int var32 = var8.getInt("nodeid");

        var5 = "insert into alerts (ts, assetid, alerttypeid, nodeid, ack) values (now(), " + var31 + ", 15, " + var32 + ", 0)";
        var3.execute(var5);
        var5 ="insert into logs (ts, rssi, nodeid, assetid) values (now(), 1000, " + var32 + ", " + var31 + ")";
        var3.execute(var5);
    }
}
</code>```

The select asset.id query seems to be running ok, but at the point of

```<code>while(var8.next()) {
    int var31 = var8.getInt("assetid");
    int var32 = var8.getInt("nodeid");
</code>```

Operation not allowed after ResultSet closed.

Do I have to do the inserts outside of the  while(var8.next())  and, if so, how do I recover / refer to the variables var31 and var32?

Apologies, I know the var names are not very helpful, but the insert commands should be straightforward (or so I thought)

Thoughts appreciated

Regards
Active

答:
Try to separate the responsability for every statement:

```<code>Connection var2 = DBConnPool.getInstance().getConnection();
Statement var3 = null;
Statement stmQuery = null;
String var5;
ResultSet var8 = null;

try {
    var3 = var2.createStatement();
    stmQuery = var2.createStatement();

    var5 = "insert into triggers (ts, nodeip, trapname) values (now(), '"+ipaddress+"', '"+trapname+"')";
    var3.execute(var5);

    var5 = "select asset.id as assetid, node.id as nodeid \n" +
        "from asset, node\n" +
        "where asset.name LIKE 'Trigger%'\n" +
        "and node.ipaddress=\'"+ipaddress+"'";
    var8 = stmQuery.executeQuery(var5);

    while(var8.next()){
        int var31 = var8.getInt("assetid");
        int var32 = var8.getInt("nodeid");

        var5 = "insert into alerts (ts, assetid, alerttypeid, nodeid, ack) values (now(), " + var31 + ", 15, " + var32 + ", 0)";
        var3.execute(var5);
        var5 ="insert into logs (ts, rssi, nodeid, assetid) values (now(), 1000, " + var32 + ", " + var31 + ")";
        var3.execute(var5);
    }
} catch (Exception e) {
    //Somthing went wrong!
} finally {
    var3.close();
    stmQuery.close();
    var8.close();
    var2.close();
}
</code>```

TIP: As you can see, it's very important to close resources within finally block.

Hope this helps!

Title: ResultSet closed (prior to insert into)

Body:
Have an issue with a closed ResultSet prior to a SQL insert (Java / Netbeans)

Connection var2 = DBConnPool.getInstance().getConnection();
Statement var3 = null;
String var5;
ResultSet var8 = null;

try {
    var3 = var2.createStatement();

    var5 = "insert into triggers (ts, nodeip, trapname) values (now(), '"+ipaddress+"', '"+trapname+"')";
    var3.execute(var5);

    var5 = "select asset.id as assetid, node.id as nodeid \n" +
        "from asset, node\n" +
        "where asset.name LIKE 'Trigger%'\n" +
        "and node.ipaddress=\'"+ipaddress+"'";
    var8 = var3.executeQuery(var5);

    while(var8.next()){
        int var31 = var8.getInt("assetid");
        int var32 = var8.getInt("nodeid");

        var5 = "insert into alerts (ts, assetid, alerttypeid, nodeid, ack) values (now(), " + var31 + ", 15, " + var32 + ", 0)";
        var3.execute(var5);
        var5 ="insert into logs (ts, rssi, nodeid, assetid) values (now(), 1000, " + var32 + ", " + var31 + ")";
        var3.execute(var5);
    }
}

The select asset.id query seems to be running ok, but at the point of

while(var8.next()) {
    int var31 = var8.getInt("assetid");
    int var32 = var8.getInt("nodeid");

Operation not allowed after ResultSet closed.

Do I have to do the inserts outside of the  while(var8.next())  and, if so, how do I recover / refer to the variables var31 and var32?

Apologies, I know the var names are not very helpful, but the insert commands should be straightforward (or so I thought)

Thoughts appreciated

Regards
Active

Body:
Try to separate the responsability for every statement:

Connection var2 = DBConnPool.getInstance().getConnection();
Statement var3 = null;
Statement stmQuery = null;
String var5;
ResultSet var8 = null;

try {
    var3 = var2.createStatement();
    stmQuery = var2.createStatement();

    var5 = "insert into triggers (ts, nodeip, trapname) values (now(), '"+ipaddress+"', '"+trapname+"')";
    var3.execute(var5);

    var5 = "select asset.id as assetid, node.id as nodeid \n" +
        "from asset, node\n" +
        "where asset.name LIKE 'Trigger%'\n" +
        "and node.ipaddress=\'"+ipaddress+"'";
    var8 = stmQuery.executeQuery(var5);

    while(var8.next()){
        int var31 = var8.getInt("assetid");
        int var32 = var8.getInt("nodeid");

        var5 = "insert into alerts (ts, assetid, alerttypeid, nodeid, ack) values (now(), " + var31 + ", 15, " + var32 + ", 0)";
        var3.execute(var5);
        var5 ="insert into logs (ts, rssi, nodeid, assetid) values (now(), 1000, " + var32 + ", " + var31 + ")";
        var3.execute(var5);
    }
} catch (Exception e) {
    //Somthing went wrong!
} finally {
    var3.close();
    stmQuery.close();
    var8.close();
    var2.close();
}

TIP: As you can see, it's very important to close resources within finally block.

Hope this helps!


问:
How to mock the webservice response of RestTemplate?
I'd like to write an integration test on my whole application, and want to mock only one specific method: the RestTemplate that I use to send some data to an external webservice and receive the response.

I want to read the response instead from a local file (to mock and mimic the external server response, so it is always the same).

My local file should just contain thejson/xml response that in production the external webserver would respond with.

Question: how can I mock an external xml response?

```<code>@Service
public class MyBusinessClient {
      @Autowired
      private RestTemplate template;

      public ResponseEntity<ProductsResponse> send(Req req) {
               //sends request to external webservice api
               return template.postForEntity(host, req, ProductsResponse.class);
      }
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

   @Test
   public void test() {
        String xml = loadFromFile("productsResponse.xml");
        //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable?
   }
}
</code>```

答:
Spring is so great:</p>

```<code>    @Autowired
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @Before
    public void createServer() throws Exception {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void test() {
        String xml = loadFromFile("productsResponse.xml");
        mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML));
    }
</code>```

Body:
I'd like to write an integration test on my whole application, and want to mock only one specific method: the RestTemplate that I use to send some data to an external webservice and receive the response.

I want to read the response instead from a local file (to mock and mimic the external server response, so it is always the same).

My local file should just contain thejson/xml response that in production the external webserver would respond with.

Question: how can I mock an external xml response?

@Service
public class MyBusinessClient {
      @Autowired
      private RestTemplate template;

      public ResponseEntity<ProductsResponse> send(Req req) {
               //sends request to external webservice api
               return template.postForEntity(host, req, ProductsResponse.class);
      }
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

   @Test
   public void test() {
        String xml = loadFromFile("productsResponse.xml");
        //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable?
   }
}

Body:
Spring is so great:

    @Autowired
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @Before
    public void createServer() throws Exception {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void test() {
        String xml = loadFromFile("productsResponse.xml");
        mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML));
    }


问:
Docker 1.10 access a container by its hostname from a host machine
I have the Docker version 1.10 with embedded DNS service.

I have created two service containers in my docker-compose file. They are reachable each other by hostname and by IP, but when I would like reach one of them from the host machine, it doesn't work, it works only with IP but not with hostname.

So, is it possible to access a docker container from the host machine by it's hostname in the Docker 1.10, please?

Update:

docker-compose.yml

```<code>version: '2'
services:
    service_a:
        image: nginx
        container_name: docker_a
        ports:
           - 8080:80
    service_b:
        image: nginx
        container_name: docker_b
        ports:
            - 8081:80
</code>```

then I start it by command: docker-compose up --force-recreate

when I run:

docker exec -i -t docker_a ping -c4 docker_b - it works

docker exec -i -t docker_b ping -c4 docker_a - it works

ping 172.19.0.2 - it works (172.19.0.2 is docker_b's ip)

ping docker_a - fails

The result of the docker network inspect test_default is

```<code>[
    {
        "Name": "test_default",
        "Id":   "f6436ef4a2cd4c09ffdee82b0d0b47f96dd5aee3e1bde068376dd26f81e79712",
        "Scope": "local",
        "Driver": "bridge",
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.19.0.0/16",
                    "Gateway": "172.19.0.1/16"
                }
            ]
        },
        "Containers": {
             "a9f13f023761123115fcb2b454d3fd21666b8e1e0637f134026c44a7a84f1b0b": {
                "Name": "docker_a",
                "EndpointID":     "a5c8e08feda96d0de8f7c6203f2707dd3f9f6c3a64666126055b16a3908fafed",
                "MacAddress": "02:42:ac:13:00:03",
                "IPv4Address": "172.19.0.3/16",
                "IPv6Address": ""
            },
                "c6532af99f691659b452c1cbf1693731a75cdfab9ea50428d9c99dd09c3e9a40": {
                "Name": "docker_b",
                "EndpointID":     "28a1877a0fdbaeb8d33a290e5a5768edc737d069d23ef9bbcc1d64cfe5fbe312",
                "MacAddress": "02:42:ac:13:00:02",
                "IPv4Address": "172.19.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {}
    }
]
</code>```

答:
Similar to @larsks, I wrote a Python script too but implemented it as service. Here it is: https://github.com/nicolai-budico/dockerhosts

It launches dnsmasq with parameter --hostsdir=/var/run/docker-hosts and updates file /var/run/docker-hosts/hosts each time a list of running containers was changed.
Once file /var/run/docker-hosts/hosts is changed, dnsmasq automatically updates its mapping and container become available by hostname in a second.

```<code>$ docker run -d --hostname=myapp.local.com --rm -it ubuntu:17.10
9af0b6a89feee747151007214b4e24b8ec7c9b2858badff6d584110bed45b740

$ nslookup myapp.local.com
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
Name:   myapp.local.com
Address: 172.17.0.2
</code>```

There are install and uninstall scripts. Only you need is to allow your system to interact with this dnsmasq instance. I registered in in systemd-resolved:

```<code>$ cat /etc/systemd/resolved.conf

[Resolve]
DNS=127.0.0.54
#FallbackDNS=
#Domains=
#LLMNR=yes
#MulticastDNS=yes
#DNSSEC=no
#Cache=yes
#DNSStubListener=udp
</code>```

Body:
I have the Docker version 1.10 with embedded DNS service.

I have created two service containers in my docker-compose file. They are reachable each other by hostname and by IP, but when I would like reach one of them from the host machine, it doesn't work, it works only with IP but not with hostname.

So, is it possible to access a docker container from the host machine by it's hostname in the Docker 1.10, please?

Update:

docker-compose.yml

version: '2'
services:
    service_a:
        image: nginx
        container_name: docker_a
        ports:
           - 8080:80
    service_b:
        image: nginx
        container_name: docker_b
        ports:
            - 8081:80

then I start it by command: docker-compose up --force-recreate

when I run:

docker exec -i -t docker_a ping -c4 docker_b - it works

docker exec -i -t docker_b ping -c4 docker_a - it works

ping 172.19.0.2 - it works (172.19.0.2 is docker_b's ip)

ping docker_a - fails

The result of the docker network inspect test_default is

[
    {
        "Name": "test_default",
        "Id":   "f6436ef4a2cd4c09ffdee82b0d0b47f96dd5aee3e1bde068376dd26f81e79712",
        "Scope": "local",
        "Driver": "bridge",
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.19.0.0/16",
                    "Gateway": "172.19.0.1/16"
                }
            ]
        },
        "Containers": {
             "a9f13f023761123115fcb2b454d3fd21666b8e1e0637f134026c44a7a84f1b0b": {
                "Name": "docker_a",
                "EndpointID":     "a5c8e08feda96d0de8f7c6203f2707dd3f9f6c3a64666126055b16a3908fafed",
                "MacAddress": "02:42:ac:13:00:03",
                "IPv4Address": "172.19.0.3/16",
                "IPv6Address": ""
            },
                "c6532af99f691659b452c1cbf1693731a75cdfab9ea50428d9c99dd09c3e9a40": {
                "Name": "docker_b",
                "EndpointID":     "28a1877a0fdbaeb8d33a290e5a5768edc737d069d23ef9bbcc1d64cfe5fbe312",
                "MacAddress": "02:42:ac:13:00:02",
                "IPv4Address": "172.19.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {}
    }
]

Body:
Similar to @larsks, I wrote a Python script too but implemented it as service. Here it is: https://github.com/nicolai-budico/dockerhosts

It launches dnsmasq with parameter --hostsdir=/var/run/docker-hosts and updates file /var/run/docker-hosts/hosts each time a list of running containers was changed.
Once file /var/run/docker-hosts/hosts is changed, dnsmasq automatically updates its mapping and container become available by hostname in a second.

$ docker run -d --hostname=myapp.local.com --rm -it ubuntu:17.10
9af0b6a89feee747151007214b4e24b8ec7c9b2858badff6d584110bed45b740

$ nslookup myapp.local.com
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
Name:   myapp.local.com
Address: 172.17.0.2

There are install and uninstall scripts. Only you need is to allow your system to interact with this dnsmasq instance. I registered in in systemd-resolved:

$ cat /etc/systemd/resolved.conf

[Resolve]
DNS=127.0.0.54
#FallbackDNS=
#Domains=
#LLMNR=yes
#MulticastDNS=yes
#DNSSEC=no
#Cache=yes
#DNSStubListener=udp


问:
VideoView Looping displays black screen after the first loop
I'm using VideoView to loop a small video, all works fine on the emulators, but when I deploy that to TV, after the first loop video turns black, but sound keeps going. This is the code:

```<code>    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout);

    VideoView videoview = (VideoView) findViewById(R.id.videoview1);
    Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.video);
    videoview.setVideoURI(uri);

    videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.setLooping(true);
            videoview.start();
        }
    });
}
</code>```

The Emulator is using Android 6.0, the TV is Sony Bravia with Android 6.0.1.
I tested using SurfaceView, instead of VideoView - the same thing happens.

Any idea how to get rid of that black screen?

PS: There is a workaround that works - make OnCompletionListener and do videoview.start() there - this way it loops, but there's an ugly gap between the loops.

答:
I have looked into the source code of VideoView and the first thing that I would like to point out is that inside the setVideoURI() method the MediaPlayer object will be created, and the OnPreparedListener will be set.

Your mistake is that you set the OnPreparedListener after the MediaPlayer may already have prepared the video, thus never call the onPrepared in the listener you have set after that, which means the setLooping(true) was maybe never set on the MediaPlayer.

TL;DR:

Put videoview.setVideoURI(uri); after videoview.setOnPreparedListener().

videoview.start() should be after setVideoURI(). On finish it should start again without additional input because this time mp.setLooping(true); was correctly set and will be executed. No videoview.start() is necessary after the initial one.

Body:
I'm using VideoView to loop a small video, all works fine on the emulators, but when I deploy that to TV, after the first loop video turns black, but sound keeps going. This is the code:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout);

    VideoView videoview = (VideoView) findViewById(R.id.videoview1);
    Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.video);
    videoview.setVideoURI(uri);

    videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.setLooping(true);
            videoview.start();
        }
    });
}

The Emulator is using Android 6.0, the TV is Sony Bravia with Android 6.0.1.
I tested using SurfaceView, instead of VideoView - the same thing happens.

Any idea how to get rid of that black screen?

PS: There is a workaround that works - make OnCompletionListener and do videoview.start() there - this way it loops, but there's an ugly gap between the loops.


问:
How to youtube video using fragment
"I trying to play youtube video on select movie fragment below my code in Main activity but when I click on movie app close directly "

```<code>if (id == R.id.movie) {
    Video video=new Video();
    FragmentManager manager=getSupportFragmentManager();
    manager.beginTransaction().replace(R.id.content_main, video,
    video.getTag()).commit();
}
</code>```

"Below my code In video.java In here error shown in "this"

```<code>public class Video extends Fragment {

    public Video() {
        // Required empty public constructor
    }

    //Recyecle view fifld
    RecyclerView recyclerView;
    //Vector for video url
    Vector<Youtubevideo> youtubevideos;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view= inflater.inflate(R.layout.fragment_video, container, false);
        recyclerView=(RecyclerView) view.findViewById(R.id.recyview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //Load video list
        youtubevideos.add(new Youtubevideo("My video link here"));
        VideoAdapter videoAdapter=new VideoAdapter(youtubevideos);
        recyclerView.setAdapter(videoAdapter);
        return view;
    }

}
</code>```

"Please help how to solve??"

答:
You are missing the initialization part for youtubevideos. Initialize it before adding any data to it.

```<code>youtubevideos = new Vector<>();
//Load video list
youtubevideos.add(new Youtubevideo("My video link here"));
</code>```

Title: How to youtube video using fragment

Body:
"I trying to play youtube video on select movie fragment below my code in Main activity but when I click on movie app close directly "

if (id == R.id.movie) {
    Video video=new Video();
    FragmentManager manager=getSupportFragmentManager();
    manager.beginTransaction().replace(R.id.content_main, video,
    video.getTag()).commit();
}

"Below my code In video.java In here error shown in "this"

public class Video extends Fragment {

    public Video() {
        // Required empty public constructor
    }

    //Recyecle view fifld
    RecyclerView recyclerView;
    //Vector for video url
    Vector<Youtubevideo> youtubevideos;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view= inflater.inflate(R.layout.fragment_video, container, false);
        recyclerView=(RecyclerView) view.findViewById(R.id.recyview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //Load video list
        youtubevideos.add(new Youtubevideo("My video link here"));
        VideoAdapter videoAdapter=new VideoAdapter(youtubevideos);
        recyclerView.setAdapter(videoAdapter);
        return view;
    }

}

"Please help how to solve??"

Body:
You are missing the initialization part for youtubevideos. Initialize it before adding any data to it.

youtubevideos = new Vector<>();
//Load video list
youtubevideos.add(new Youtubevideo("My video link here"));


问:
JavaFX: Get bounds of Stage before maximizing
I want to get/remember the bounds of a Stage before it gets maximized by the user. I noticed that i can add event handlers to the maximized property of the stage, but it does not help me. The stage is already maximized at this point in time and getX() or getWidth() already report the location or size after the Stage has been maximized.

myStage.maximizedProperty().addListener((observable, oldValue, newValue) -> {
    double x = myStage.getX(); // already too late, x has changed
    ...
```

How can i get the bounds of the stage before it has already changed in size? Is that even possible with the current API?

PS: The bigger goal is it to remember the Stage location, state, and screen. If the user positions the Stage, maximizes it, exits the application, and restarts it again, then i want the Stage to be positioned like it was before the user exited the application. That means i would need to position the new Stage first at the previous unmaximized location and then maximize it, to restore the previous state. But without knowing the size before maximizing this seams impossible to do.

答:
Well, Alastair isn't that wrong.

The javaFX Stage has a widthProperty and a heightProperty (inherited from Window with getters and Setters.
You can register a ChangeListener to both properties and safe their state when the Listener catches an Event.

ChangeListener Doc

height- and widthproperty docs in Window.

Body:
I want to get/remember the bounds of a Stage before it gets maximized by the user. I noticed that i can add event handlers to the maximized property of the stage, but it does not help me. The stage is already maximized at this point in time and getX() or getWidth() already report the location or size after the Stage has been maximized.

myStage.maximizedProperty().addListener((observable, oldValue, newValue) -> {
    double x = myStage.getX(); // already too late, x has changed
    ...

How can i get the bounds of the stage before it has already changed in size? Is that even possible with the current API?

PS: The bigger goal is it to remember the Stage location, state, and screen. If the user positions the Stage, maximizes it, exits the application, and restarts it again, then i want the Stage to be positioned like it was before the user exited the application. That means i would need to position the new Stage first at the previous unmaximized location and then maximize it, to restore the previous state. But without knowing the size before maximizing this seams impossible to do.


问:
How can we fill a html text area on pharo
For a login through pharo using the html form there is a method of Znclient which is formAt:add: followed by a post. So I was wondering how to I fill a textArea of html form and make post. Is there a method for such action?

<textarea id="technique" name="technique" class="technique">jumping</textarea>
Résultats :

<textarea id="resultat" name="resultat" class="resultat">Higher score</textarea>
Conclusion :

<textarea id="conclusion" name="conclusion" class="conclusion">Best jumper of the school</textarea>
```

答:
Looking into ZnClient class in the System Browser you can see the comments for following methods:

formAt:add: - "Add key equals value to the application/x-www-form-urlencoded entity of the current request. This is for multi-values form fields."

formAt:put: - "Set key equal to value in the application/x-www-form-urlencoded entity of the current request."

formAdd: - "Add the key->value association to the application/x-www-form-urlencoded entity of the current request."

formAddAll: - "Add all key->value associations of keyedCollection to
    the application/x-www-form-urlencoded entity of the current request."

We haven't used formAt:add: in any of our previous q&a on this and we should avoid it here. Use one of the last 3 methods:

| client |
client := ZnClient new url: 'http://server/some-script.cgi'.
```

<p>then...</p>

<pre class="lang-smalltalk prettyprint-override"><code>client formAt: 'technique'  put: 'foo';
       formAt: 'resultat'   put: 'bar';
       formAt: 'conclusion' put: 'baz';
       post.
</code>```

or...

client formAdd: 'technique'  -> 'foo';
       formAdd: 'resultat'   -> 'bar';
       formAdd: 'conclusion' -> 'baz';
       post.
```

<p>or this...</p>

<pre class="lang-smalltalk prettyprint-override"><code>client formAddAll: {
    'technique'  -> 'foo'.
    'resultat'   -> 'bar'.
    'conclusion' -> 'baz'.
} asDictionary; post.
</code>```

Body:
Looking into ZnClient class in the System Browser you can see the comments for following methods:

formAt:add: - "Add key equals value to the application/x-www-form-urlencoded entity of the current request. This is for multi-values form fields."

formAt:put: - "Set key equal to value in the application/x-www-form-urlencoded entity of the current request."

formAdd: - "Add the key->value association to the application/x-www-form-urlencoded entity of the current request."

formAddAll: - "Add all key->value associations of keyedCollection to
    the application/x-www-form-urlencoded entity of the current request."

We haven't used formAt:add: in any of our previous q&a on this and we should avoid it here. Use one of the last 3 methods:

| client |
client := ZnClient new url: 'http://server/some-script.cgi'.

then...

client formAt: 'technique'  put: 'foo';
       formAt: 'resultat'   put: 'bar';
       formAt: 'conclusion' put: 'baz';
       post.

or...

client formAdd: 'technique'  -> 'foo';
       formAdd: 'resultat'   -> 'bar';
       formAdd: 'conclusion' -> 'baz';
       post.

or this...

client formAddAll: {
    'technique'  -> 'foo'.
    'resultat'   -> 'bar'.
    'conclusion' -> 'baz'.
} asDictionary; post.


问:
One sided jQuery UI slider
I am using jQuery UI range slider to allow the user to define a range. Based on the user's selection I will then show/hide different divs.

In order to achieve that I use data-price="" that allow me to check if the value is bigger or smaller than that.

What I would like to achieve is:

Have only one selection for the price rather than selection from left
and right.

I would like to keep the functionality where the bar is filling with colour based on selection. (in the example in grey)

I have tried changing range: true to range: false but I could not achieve the desired effect.

My JSFIDDLE example is here: https://jsfiddle.net/L47mo8bm/

I have tried the following but not sure why the logic is not working: https://jsfiddle.net/57axLd53/1/

答:
I have solved the following using this code: https://jsfiddle.net/57axLd53/4/

$(function() {
  $("#slider-container").slider({
    range: 'min',
    min: 4,
    max: 10,
    value: 8,
    step: 2,
    slide: function(event, ui) {
      var curValue = ui.value;
      var tooltip_Date = '

' + curValue + ' years

';
      $(this).find('.ui-slider-handle').html(tooltip_Date);
      $("#number_repayments").html(curValue);

      if (ui.value < 5) {
        $('.system1').css('display', 'block');
        $('.system2, .system3, .system4').css('display', 'none');
      } else if (ui.value < 7) {
        $('.system2').css('display', 'block');
        $('.system3, .system1, .system4').css('display', 'none');
      } else if (ui.value < 9) {
        $('.system3').css('display', 'block');
        $('.system2, .system1, .system4').css('display', 'none');
      } else if (ui.value > 9) {
        $('.system4').css('display', 'block');
        $('.system2, .system1, .system3').css('display', 'none');
      }

    },
    create: function(event, ui) {
      var curValue = ui.value || 8;
      var tooltip_Date = '

' + curValue + ' years

';
      $(this).find('.ui-slider-handle').html(tooltip_Date);
      $("#number_repayments").html(curValue);
    }
  });
});

f```

Title: One sided jQuery UI slider

Body:
I have solved the following using this code: https://jsfiddle.net/57axLd53/4/

$(function() {
  $("#slider-container").slider({
    range: 'min',
    min: 4,
    max: 10,
    value: 8,
    step: 2,
    slide: function(event, ui) {
      var curValue = ui.value;
      var tooltip_Date = '<div class="tooltip_Date"><div class="tooltip_Date-inner">' + curValue + ' years</div><div class="tooltip_Date-arrow"></div></div>';
      $(this).find('.ui-slider-handle').html(tooltip_Date);
      $("#number_repayments").html(curValue);

      if (ui.value < 5) {
        $('.system1').css('display', 'block');
        $('.system2, .system3, .system4').css('display', 'none');
      } else if (ui.value < 7) {
        $('.system2').css('display', 'block');
        $('.system3, .system1, .system4').css('display', 'none');
      } else if (ui.value < 9) {
        $('.system3').css('display', 'block');
        $('.system2, .system1, .system4').css('display', 'none');
      } else if (ui.value > 9) {
        $('.system4').css('display', 'block');
        $('.system2, .system1, .system3').css('display', 'none');
      }

    },
    create: function(event, ui) {
      var curValue = ui.value || 8;
      var tooltip_Date = '<div class="tooltip_Date"><div class="tooltip_Date-inner">' + curValue + ' years</div><div class="tooltip_Date-arrow"></div></div>';
      $(this).find('.ui-slider-handle').html(tooltip_Date);
      $("#number_repayments").html(curValue);
    }
  });
});

f


问:
Mysql alias the chain of inner joins issue
I have the following query

```<code>select *
from
    reservation r,
    (
        assignment a
        INNER JOIN class_ c ON a.class_id = c.uniqueid
        INNER JOIN scheduling_subpart ss ON c.subpart_id = ss.uniqueid
        INNER JOIN instr_offering_config ioc ON ss.config_id = ioc.uniqueid
    ) as io
where
    io.solution_id in (32931842) and
    io = r.offering_id
</code>```

Note: solution_id is column on the assignment table.

I want the who inner joins in parenthesis to be aliased with io but I'm getting a syntax error:

Check the manual that corresponds to your MySQL server version for the right syntax to use near 'as io where io.solution_id in (32931842) and io = r.offering_id'

答:
It look like you mean to do this:</p>

```<code>select *
from
reservation r,
(
    select * from assignment a ///  You missed the  select * from
    INNER JOIN class_ c ON a.class_id = c.uniqueid
    INNER JOIN scheduling_subpart ss ON c.subpart_id = ss.uniqueid
    INNER JOIN instr_offering_config ioc ON ss.config_id = ioc.uniqueid
) as io
where
io.solution_id in (32931842) and
io = r.offering_id
</code>```

Body:
I have the following query

select *
from
    reservation r,
    (
        assignment a
        INNER JOIN class_ c ON a.class_id = c.uniqueid
        INNER JOIN scheduling_subpart ss ON c.subpart_id = ss.uniqueid
        INNER JOIN instr_offering_config ioc ON ss.config_id = ioc.uniqueid
    ) as io
where
    io.solution_id in (32931842) and
    io = r.offering_id

Note: solution_id is column on the assignment table.

I want the who inner joins in parenthesis to be aliased with io but I'm getting a syntax error:

Check the manual that corresponds to your MySQL server version for the right syntax to use near 'as io where io.solution_id in (32931842) and io = r.offering_id'

Body:
It look like you mean to do this:

select *
from
reservation r,
(
    select * from assignment a ///  You missed the  select * from
    INNER JOIN class_ c ON a.class_id = c.uniqueid
    INNER JOIN scheduling_subpart ss ON c.subpart_id = ss.uniqueid
    INNER JOIN instr_offering_config ioc ON ss.config_id = ioc.uniqueid
) as io
where
io.solution_id in (32931842) and
io = r.offering_id


问:
HTML form in while loop, how to transfer data from each item?
I have tried to solve it and look around but not even sure what I should be searching for.

I have made a product grid through a while loop, in the loop with each product and input-tag has been used for users to mark how many items of each product is wanted.

The product grid

However I have trouble distinguishing the value of each input field and what "name" it should be stored under to be able to retrieve it when running the second script of processing the order? I also need to be able to connect an id with each value.

The code for the grid:
I know I need to make a unique name in the input name, however how and which makes sense?

```<code><div id="content">
    <h1>Products</h1>

    <form action="processorder.php" method="post">
    <table align="center">
        <?php

        $db = include "connect2db.php";

        mysqli_set_charset($db,"utf8");

        $query = 'SELECT * FROM products_josie';

        $result = $db->query($query);

        $count = 0;
        while($res=$result->fetch_assoc())
        {
            if($count==3)
            {
               echo '</tr>';
               $count = 0;
            }
            if($count==0)
               echo '<tr>';
               echo '<td>';
               ?>

               <a href="productsdetails.php?clickedid=<?php echo $res['product_id']?>">
               <img src="products/<?php echo $res['photo']; ?>" width="200" height="150"/>
               </a>
               <br/>
            <?php
            echo '<p>';
            echo $res['product_name'];
            echo '</br>';
            echo 'DKK ';
            echo $res['price'];
            echo '</p>';
            echo '<p>';
            echo '<input type="number" name="amount" min="0"';
            echo '</p>';
            $count++;
            print '</td>';
        }
        if($count>0)
            print '</tr>';
        ?>
    </table>

    <input type="submit" value="Submit Order">
    </form>
</div>
</code>```

答:
I think what you are looking for is how to get the amounts for different products. If so, something like this might do it:</p>

```<code>$prod = $res['product_name'];
echo '<input type="number" name="amount[$prod]" min="0"';
</code>```

Body:
I have tried to solve it and look around but not even sure what I should be searching for.

I have made a product grid through a while loop, in the loop with each product and input-tag has been used for users to mark how many items of each product is wanted.

The product grid

However I have trouble distinguishing the value of each input field and what "name" it should be stored under to be able to retrieve it when running the second script of processing the order? I also need to be able to connect an id with each value.

The code for the grid:
I know I need to make a unique name in the input name, however how and which makes sense?

Products

    <form action="processorder.php" method="post">

        <?php

        $db = include "connect2db.php";

        mysqli_set_charset($db,"utf8");

        $query = 'SELECT * FROM products_josie';

        $result = $db->query($query);

        $count = 0;
        while($res=$result->fetch_assoc())
        {
            if($count==3)
            {
               echo '
';
               $count = 0;
            }
            if($count==0)
               echo '
';
               echo '';
               ?>

               <a href="productsdetails.php?clickedid=<?php echo $res['product_id']?>">
               <img src="products/<?php echo $res['photo']; ?>" width="200" height="150"/>

            <?php
            echo '
';
            echo $res['product_name'];
            echo '
';
            echo 'DKK ';
            echo $res['price'];
            echo '
';
            echo '
';
            echo '<input type="number" name="amount" min="0"';
            echo '
';
            $count++;
            print '	';
        }
        if($count>0)
            print '
';
        ?>

    <input type="submit" value="Submit Order">
    </form>

Body:
I think what you are looking for is how to get the amounts for different products. If so, something like this might do it:

$prod = $res['product_name'];
echo '<input type="number" name="amount[$prod]" min="0"';


问:
Using cURL with a username and password?
I want to access a URL which requires a username/password. I'd like to try accessing it with curl. Right now I'm doing something like:

```<code>curl http://api.somesite.com/test/blah?something=123
</code>```

I get an error. I guess I need to specify a username and password along with the above command.

How can I do that?

答:
```<code>curl -X GET -u username:password  {{ http://www.example.com/filename.txt }} -O
</code>```

Body:
I want to access a URL which requires a username/password. I'd like to try accessing it with curl. Right now I'm doing something like:

curl http://api.somesite.com/test/blah?something=123

I get an error. I guess I need to specify a username and password along with the above command.

How can I do that?


问:
Doctrine onDelete Foreign key constraints
Quick sketch

I want to delete a parent entity without removing it's children, instead set the referenced column to NULL

My programming

I added onDelete="SET NULL" to the joinColumn of my child entity like this:

```<code>/**
 * @ORM\ManyToOne(targetEntity="Backend\Modules\Ads\Domain\Ad\Ad", inversedBy="rewarded")
 * @ORM\JoinColumn(name="ad_id", referencedColumnName="id", onDelete="SET NULL")
 */
private $ad;
</code>```

This is the parent entity association:

```<code>/**
 * @ORM\OneToMany(targetEntity="Backend\Modules\Ads\Domain\Rewarded\Rewarded", mappedBy="ad")
 */
private $rewarded;
</code>```

The problem

On delete of the parent it throws me this error:

```<code>Cannot delete or update a parent row: a foreign key constraint fails
</code>```

I already tried adding "remove", "persist" without much success. Using persist it will still cause the error and with remove enabled it will just remove the row.

I have found none working solution for this so far, thanks already!

答:
I've found the solution. My entity I wanted to set NULL was dependent on another entity which was depending on the one I'm removing also. The method I used above is fully working when implemented everywhere where needed.

Thanks.

Body:
Quick sketch

I want to delete a parent entity without removing it's children, instead set the referenced column to NULL

My programming

I added onDelete="SET NULL" to the joinColumn of my child entity like this:

/**
 * @ORM\ManyToOne(targetEntity="Backend\Modules\Ads\Domain\Ad\Ad", inversedBy="rewarded")
 * @ORM\JoinColumn(name="ad_id", referencedColumnName="id", onDelete="SET NULL")
 */
private $ad;

This is the parent entity association:

/**
 * @ORM\OneToMany(targetEntity="Backend\Modules\Ads\Domain\Rewarded\Rewarded", mappedBy="ad")
 */
private $rewarded;

The problem

On delete of the parent it throws me this error:

Cannot delete or update a parent row: a foreign key constraint fails

I already tried adding "remove", "persist" without much success. Using persist it will still cause the error and with remove enabled it will just remove the row.

I have found none working solution for this so far, thanks already!


问:
Querying specific object from a jpa datamodel
I have a question about querying with an orm mapper like hibernate. Suppose you have a database model like this

```<code>class A {
    int i;
    B b;
}

class B {
    int j;
}
</code>```

If I want to save an object the hibernate engine can add all class instances at once by cascading queries. This will also work if I fetch an object from the database by value from class A.

But what if i want to have all entries of Class A with holds the objects of B with value j = 10?

In SQL i would have something like this:

```<code>SELECT * FROM A a, B b WHERE a.ref = b.ref AND b.j = 10;
</code>```

But with an ORM the ref is modeled with the object references. How am i supposed to create a query like this? First of all: Do I have to write a query? And secondly: How will hibernate resolve these references a.ref = b.ref

答:
You should be able to use:

```<code>A findByBJ(int j);
</code>```

If your tables are properly saved with some OneToOne relation.

Body:
I have a question about querying with an orm mapper like hibernate. Suppose you have a database model like this

class A {
    int i;
    B b;
}

class B {
    int j;
}

If I want to save an object the hibernate engine can add all class instances at once by cascading queries. This will also work if I fetch an object from the database by value from class A.

But what if i want to have all entries of Class A with holds the objects of B with value j = 10?

In SQL i would have something like this:

SELECT * FROM A a, B b WHERE a.ref = b.ref AND b.j = 10;

But with an ORM the ref is modeled with the object references. How am i supposed to create a query like this? First of all: Do I have to write a query? And secondly: How will hibernate resolve these references a.ref = b.ref

Body:
You should be able to use:

A findByBJ(int j);

If your tables are properly saved with some OneToOne relation.


问:
Lightweight AJAX objects recommendations?
I'm building a custom widget and i'm not supposed to use any framework such as jQuery, i need a lightweight cross browser object that supports POST & GET with callback, i've seen some solutions online but they include a lot of useless stuffs.

Thanks

答:
Just use the XMLHttpRequest object yourself.

I tend to like looking at the Mozilla site to see examples, and they have a nice explanation on this subject.

Using XMLHttpRequest

It isn't hard to do, and it supports any HTTP request, and is as simple or complicated as you want to make it, depending on how easy you want to make it to use.

jQuery has a nice API though, so copying their style may be useful.

UPDATE:

You should reference the link above, but to see how POST can be done, mainly you put the parameters into the send function you can look at this.  Don't just copy this code, I put it here for just a simple example.

```<code>var xhr = new XMLHttpRequest();
xhr.open("POST", "http://foo.com/submitform.php");
xhr.send(formData);
</code>```

For GET you just put them in the URL, as you would in your address bar, and a null in the send.

Body:
Just use the XMLHttpRequest object yourself.

I tend to like looking at the Mozilla site to see examples, and they have a nice explanation on this subject.

Using XMLHttpRequest

It isn't hard to do, and it supports any HTTP request, and is as simple or complicated as you want to make it, depending on how easy you want to make it to use.

jQuery has a nice API though, so copying their style may be useful.

UPDATE:

You should reference the link above, but to see how POST can be done, mainly you put the parameters into the send function you can look at this.  Don't just copy this code, I put it here for just a simple example.

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://foo.com/submitform.php");
xhr.send(formData);

For GET you just put them in the URL, as you would in your address bar, and a null in the send.


答:
You can navigate over the references in JPQL:</p>

```<code>SELECT a FROM A a WHERE a.b.j = 10;
</code>```

Title: Querying specific object from a jpa datamodel

Body:
You can navigate over the references in JPQL:

SELECT a FROM A a WHERE a.b.j = 10;


问:
Capturing still image from camera using gpuimage2
I have a photo/gif app I made previously using AVFoundation as a base for the camera and taking photos, but I wanted to upgrade it to add some live filtering and post capture filtering too.

After some digging I found gpuimage/gpuimage2 and since my project is in swift 3 I started replacing my previous camera module with gpuimage.

I got the camera to work again but I have issues capturing a photo from the camera to store it as a uiimage until it is uploaded to a server.

```<code>do {
  self.videoCamera = try Camera(sessionPreset: AVCaptureSessionPresetPhoto, location: .frontFacing)
} catch {
  self.videoCamera = nil
  print("Couldn't initialize camera with error: \(error)")
}
</code>```

this is my init and then this is where I place the camera feed in the view

```<code>self.filterView!.frame = self.view.frame
self.filterView!.orientation = .portraitUpsideDown
self.filterView!.fillMode = .preserveAspectRatioAndFill
self.videoCamera! --> self.filterView!
self.videoCamera!.startCapture()
</code>```

as you can see for the moment I don't want to use any filters, I'm trying to first get the basic functionality back (i.e. showing a camera feed the taking 1-5 images in a row)

I noticed there was a saveNextFrameToURL but it saves the file on the device but I only want the uiimage  so this is what I put to replace the content of my takePhoto method (images is nil on first run)

```<code>func takePhoto(){
  if self.images == nil {
    self.images = []
  }
  let pictureOutput = PictureOutput()
  pictureOutput.encodedImageFormat = .jpeg
  pictureOutput.imageAvailableCallback = {image in
    self.images!.append(image)
  }
  self.videoCamera! --> pictureOutput
}
</code>```

My issue is that imageAvailableCallback is simply never called (I tried placing a breakpoint in it but nothing) whereas it goes through the rest of the method not raising any errors or warning.

what am I doing wrong ? is it even possible to capture a still image from a non filtered view ? if so how can I add a filter that would not change the image as such so I can still do some unedited photo capture in my app?

I've been going at it for over 2 weeks now and every time I search if anyone had the same issue I only find issues about editing a still image or a filtered image and when I tried filtering the image as such:

```<code>self.filterView!.frame = self.view.frame
self.filterView!.orientation = .portraitUpsideDown
self.filterView!.fillMode = .preserveAspectRatioAndFill
self.baseFilter = BrightnessAdjustment()
self.videoCamera! --> self.baseFilter --> self.filterView!
self.videoCamera!.startCapture()
</code>```

and the takePhoto method

```<code>func takePhoto(){
  if self.images == nil {
    self.images = []
  }
  let pictureOutput = PictureOutput()
  pictureOutput.encodedImageFormat = .jpeg
  pictureOutput.imageAvailableCallback = {image in
    self.images!.append(image)
  }
  self.baseFilter! --> pictureOutput
}
</code>```

I get a white screen instead of my camera feed and still no image.

Any help would be appreciated thank you

答:
I found where my problem was by looking at similar issues and the comments (found one where Brad Larson commented here

Basically it has to do with the lifespan of my pictureOutput variable, since it was enclosed inside a method is didn't last long enough for the callback to be made and to save the image, by making my pictureOutput variable a class variable I solved my issues

Body:
I have a photo/gif app I made previously using AVFoundation as a base for the camera and taking photos, but I wanted to upgrade it to add some live filtering and post capture filtering too.

After some digging I found gpuimage/gpuimage2 and since my project is in swift 3 I started replacing my previous camera module with gpuimage.

I got the camera to work again but I have issues capturing a photo from the camera to store it as a uiimage until it is uploaded to a server.

do {
  self.videoCamera = try Camera(sessionPreset: AVCaptureSessionPresetPhoto, location: .frontFacing)
} catch {
  self.videoCamera = nil
  print("Couldn't initialize camera with error: \(error)")
}

this is my init and then this is where I place the camera feed in the view

self.filterView!.frame = self.view.frame
self.filterView!.orientation = .portraitUpsideDown
self.filterView!.fillMode = .preserveAspectRatioAndFill
self.videoCamera! --> self.filterView!
self.videoCamera!.startCapture()

as you can see for the moment I don't want to use any filters, I'm trying to first get the basic functionality back (i.e. showing a camera feed the taking 1-5 images in a row)

I noticed there was a saveNextFrameToURL but it saves the file on the device but I only want the uiimage  so this is what I put to replace the content of my takePhoto method (images is nil on first run)

func takePhoto(){
  if self.images == nil {
    self.images = []
  }
  let pictureOutput = PictureOutput()
  pictureOutput.encodedImageFormat = .jpeg
  pictureOutput.imageAvailableCallback = {image in
    self.images!.append(image)
  }
  self.videoCamera! --> pictureOutput
}

My issue is that imageAvailableCallback is simply never called (I tried placing a breakpoint in it but nothing) whereas it goes through the rest of the method not raising any errors or warning.

what am I doing wrong ? is it even possible to capture a still image from a non filtered view ? if so how can I add a filter that would not change the image as such so I can still do some unedited photo capture in my app?

I've been going at it for over 2 weeks now and every time I search if anyone had the same issue I only find issues about editing a still image or a filtered image and when I tried filtering the image as such:

self.filterView!.frame = self.view.frame
self.filterView!.orientation = .portraitUpsideDown
self.filterView!.fillMode = .preserveAspectRatioAndFill
self.baseFilter = BrightnessAdjustment()
self.videoCamera! --> self.baseFilter --> self.filterView!
self.videoCamera!.startCapture()

and the takePhoto method

func takePhoto(){
  if self.images == nil {
    self.images = []
  }
  let pictureOutput = PictureOutput()
  pictureOutput.encodedImageFormat = .jpeg
  pictureOutput.imageAvailableCallback = {image in
    self.images!.append(image)
  }
  self.baseFilter! --> pictureOutput
}

I get a white screen instead of my camera feed and still no image.

Any help would be appreciated thank you


问:
Accessing Image Data Bytes in ARCore
I've created an ARCore Session and attached an OpenGL texture id through the Session#setCameraTextureName method to display my camera data. I'd like to have access to the camera image data bytes displayed on the texture.

ARKit and Tango provide access to the image bytes for each frame but there doesn't seem to be anything that easily provides that in the ARCore API.

Is there any other way I can access the image bytes when using ARCore?

答:
Maybe that could help you I wanted to obtain the camera view in a bitmap form. I have tested on Samsung s8. </p>

```<code>    int w=1080;
    int h = 2220;
    int b[]=new int[w*(0+h)];
    int bt[]=new int[w*h];
    IntBuffer ib = IntBuffer.wrap(b);
    ib.position(0);
    GLES20.glReadPixels(0, 0, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ib);

    for(int i=0, k=0; i<h; i++, k++)
    {//remember, that OpenGL bitmap is incompatible with Android bitmap
        //and so, some correction need.
        for(int j=0; j<w; j++)
        {
            int pix=b[i*w+j];
            int pb=(pix>>16)&0xff;
            int pr=(pix<<16)&0x00ff0000;
            int pix1=(pix&0xff00ff00) | pr | pb;
            bt[(h-k-1)*w+j]=pix1;
        }
    }

    sb=Bitmap.createBitmap(bt, w, h, Bitmap.Config.ARGB_8888);
</code>```

Title: Accessing Image Data Bytes in ARCore

Body:
Maybe that could help you I wanted to obtain the camera view in a bitmap form. I have tested on Samsung s8.

    int w=1080;
    int h = 2220;
    int b[]=new int[w*(0+h)];
    int bt[]=new int[w*h];
    IntBuffer ib = IntBuffer.wrap(b);
    ib.position(0);
    GLES20.glReadPixels(0, 0, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ib);

    for(int i=0, k=0; i<h; i++, k++)
    {//remember, that OpenGL bitmap is incompatible with Android bitmap
        //and so, some correction need.
        for(int j=0; j<w; j++)
        {
            int pix=b[i*w+j];
            int pb=(pix>>16)&0xff;
            int pr=(pix<<16)&0x00ff0000;
            int pix1=(pix&0xff00ff00) | pr | pb;
            bt[(h-k-1)*w+j]=pix1;
        }
    }

    sb=Bitmap.createBitmap(bt, w, h, Bitmap.Config.ARGB_8888);


问:
Postion absolute effecting padding of parent div
I am trying to fix a button to the right edge of a div.

HTML:

```<code><div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
</div>
</code>```

CSS:

```<code> #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }
</code>```

After applying position: absolute:

You can see in the image above that original padding: 20px on the parent div is ignored.

While removing position: absolute:

Brings the original padding back but as you can see the button is then not to the right. Applying float: right has the same effect.

Can somebody help me fix this issues and more importantly explain whats causing this so I can better learn. Apologies if this is a very basic question.

答:
Padding is not removed when you use absolute, but the height and width of your absolute element is not a part of your parent element anymore so therefore is loses height. Now if you want to change height of parent element you can either increase padding or give it height property.

 #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 40px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 30px;
   right: 10px;
   color: #ffffff;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus">x</button>
</div>  </code>```

Body:
I am trying to fix a button to the right edge of a div.

HTML:

  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>

CSS:

 #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }

After applying position: absolute:

You can see in the image above that original padding: 20px on the parent div is ignored.

While removing position: absolute:

Brings the original padding back but as you can see the button is then not to the right. Applying float: right has the same effect.

Can somebody help me fix this issues and more importantly explain whats causing this so I can better learn. Apologies if this is a very basic question.

Body:
Padding is not removed when you use absolute, but the height and width of your absolute element is not a part of your parent element anymore so therefore is loses height. Now if you want to change height of parent element you can either increase padding or give it height property.

 #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 40px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 30px;
   right: 10px;
   color: #ffffff;
 }

<div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus">x</button>
</div>


问:
Slickgrid - Background Polling to keep data up-to-date?
I have a small Django-based webapp used to assigning people to various accomodation rooms, workshops, lectures etc.

I'm hoping to use Slickgrid to present an editable grid for people to edit values with. There will be multiple people (around 5-10 to begin with) who will be hitting the same table with writes. In theory, they should be touching different parts of the table, but there will be some overlap (e.g. how many spare slots there are in a given room).

I'm wondering what mechanisms there are that I can use with Slickgrid in order to ensure that they are all viewing (relatively) up-to-date data?

Is there some kind of background polling that can be done? Or can an edit by one user trigger a refresh on everybody else's session? Or is something like that not really feasible across the web?

If Slickgrid isn't suitable for this, what other web-based data-tables are available that would handle heavy concurrent edits?

(I know Google Wave does cool things with operational transforms, I'm hoping for something a bit simpler/dumber...lol)

Cheers,
Victor

答: Why not record the last update time for the grid, then AJAX poll to see the time of the last update on your data, then update the grid's data object as necessary?</p>