问:
Window.scroll within an iframe
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

```<code><div class="container">
        <header class="header-wrapper">
            <div class="sticky-header">
                <div class="row">
                        <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Customer Name: </label>
                            <label>Person!! </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">Address: </label>
                            <label>101 Main Street </label>
                        </div>

                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Email:</label>
                            <label>something@email.com </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">City, State:</label>
                            <label>Tavierner, FL </label>
                        </div>

                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Phone:</label>
                            <label>555-555-5555 </label>
                        </div>

                        <div class="form-group">
                            <label class="bold">Club Code:</label>
                            <label>456 </label>
                            <label class="bold">Associate#:</label>
                            <label>45 </label>
                        </div>
                    </div>
                </div>
            </div>
        </header>
  <section>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>

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

and my jquery

```<code> if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }
</code>```

A screenshot of what the menu looks like when it's not working:

答:
The question here is where the scroll apply.

If the scroll apply on the document, the JS is in this document, and the iframe have the scroll, then it should work just like the jQuery doc : see the last demo here.

Maybe try to replace the iframe's content with the demo to see if it work.

A straight possible solution is to get the scroll back in the page, to do that just create some parent element in it (or use an existing one), with a width and height of the size of the iframe plus the overflow, and use a

```<code>$('#myparent').scroll(function () {
</code>```

instead of targeting the document.
Beware that you'll need for #myparent to exist when the JS will execute this line, so think of using a .ready or putting the JS at the bottom of the page.

At last, if you want solution without scroll, you could try for something like this post here or this one maybe more like it for some css-only solutions (quite a different way of going around it). But it's not certain that the iframe won't cause issues there too.

Edit : since the full css is a no-go, here's two others work-around i can think of.

1- The mousewheel event.

On Chrome, try to replace the .scroll(... by .on('mousewheel',...
If it work, you can use this plugin here for a cross browser solution.

2- The Bad and Dirty

Well, my last bullet isn't the nicest. You can detect the scroll event on the iframe page (make the iframe go all the way to the bottom of your document, and detect the scroll of the iframe's window for example). From here, you can then do your work in the iframe page, for example :

```<code>$('#myiframe').ready(function () {
  $(window).scroll(function () {
        var header = $(document).scrollTop();
        var headerHeight = $('#myiframe').contents().find('.header-wrapper').height();
        var sticky = $('#myiframe').contents().find('.sticky-header');
        if (header > headerHeight) {
            sticky.addClass('sticky');
            sticky.fadeIn();
        } else {
            sticky.removeClass('sticky');
        }
  });
});
</code>```

I tested it, it should work if you juste replace #myiframe. But as i said, it's not that clean (not sure what your team will think of it ^^').

Title: Window.scroll within an iframe

Body:
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

                            Customer Name:
                            Person!!

                            Address:
                            101 Main Street

                            Email:
                            something@email.com

                            City, State:
                            Tavierner, FL

                            Phone:
                            555-555-5555

                            Club Code:
                            456
                            Associate#:
                            45

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

and my jquery

 if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }

A screenshot of what the menu looks like when it's not working:

Body:
The question here is where the scroll apply.

If the scroll apply on the document, the JS is in this document, and the iframe have the scroll, then it should work just like the jQuery doc : see the last demo here.

Maybe try to replace the iframe's content with the demo to see if it work.

A straight possible solution is to get the scroll back in the page, to do that just create some parent element in it (or use an existing one), with a width and height of the size of the iframe plus the overflow, and use a

$('#myparent').scroll(function () {

instead of targeting the document.
Beware that you'll need for #myparent to exist when the JS will execute this line, so think of using a .ready or putting the JS at the bottom of the page.

At last, if you want solution without scroll, you could try for something like this post here or this one maybe more like it for some css-only solutions (quite a different way of going around it). But it's not certain that the iframe won't cause issues there too.

Edit : since the full css is a no-go, here's two others work-around i can think of.

1- The mousewheel event.

On Chrome, try to replace the .scroll(... by .on('mousewheel',...
If it work, you can use this plugin here for a cross browser solution.

2- The Bad and Dirty

Well, my last bullet isn't the nicest. You can detect the scroll event on the iframe page (make the iframe go all the way to the bottom of your document, and detect the scroll of the iframe's window for example). From here, you can then do your work in the iframe page, for example :

$('#myiframe').ready(function () {
  $(window).scroll(function () {
        var header = $(document).scrollTop();
        var headerHeight = $('#myiframe').contents().find('.header-wrapper').height();
        var sticky = $('#myiframe').contents().find('.sticky-header');
        if (header > headerHeight) {
            sticky.addClass('sticky');
            sticky.fadeIn();
        } else {
            sticky.removeClass('sticky');
        }
  });
});

I tested it, it should work if you juste replace #myiframe. But as i said, it's not that clean (not sure what your team will think of it ^^').


来源: stackexchange

问:
Elasticsearch join-like query on multiple types and different fields
I have an Elasticsearch index called my_index which contains documents of two types, Type1 and Type2.

The two document types contain different data about the same type of entity.

The two document types both contain the ID of the related entity.

I've been trying to construct a join-like query which would return entities which match conditions on both document types, but I can't get it to work, and I also can't find any citation in the Elasticsearch multi-type or query documentation that says it's not possible.

The problem I'm trying to solve is avoiding having to manually join two result sets by getting all Type1 hits and all Type2 hits and doing the join outside of Elasticsearch, since the index has millions of documents.

The equivalent in SQL would be

```<code>select * from
  Type1 inner join Type2
    on Type2.EntityId = Type1.EntityId
where
  Type1.Field = Condition AND
  Type2.Field = Condition [...]
</code>```

The URL I'm using to query against is http://elastic/my_index/Type1,Type2/_search to include both document types.

If I perform a blank query against this URL, I get hits of both Type1 and Type2.

If I add a criterion for Type1, it works as expected:

```<code>{ "query": {
  "bool": {
    "must": [{
      "term": {
        "FieldOnType1": "lorem" } } ] } } }
</code>```

Somehow Elasticsearch can infer that FieldOnType1 is indeed a field on Type1.

When I add a criterion for Type2, I don't get any hits:

```<code>{ "query": {
  "bool": {
    "must": [{
      "term": {
        "FieldOnType1": "lorem" } }, {
      "term": {
        "FieldOnType2": "ipsum" } } ] } } }
</code>```

In reality, there are sometimes more than 2 term queries, or range queries and term queries.

I'm guessing the problem with the above query is that no single document can match both criteria at once.

I've tried

using should instead of must, and I've tried

qualifying the field names with type names, and I've tried

many variations of the query (including using filters instead of queries)

but everything gives me 0 hits.

Similar questions here suggest to use the Elasticsearch multi-search API instead of the search API, but that won't solve my "manual join" problem.

Is there a way to make an elaborate "OR" query that would allow queries on both types? Or something else?

答:
Try multi_match query (I use ES 6, so have index p/type):

```<code>GET index1,index2/_search
{
  "query":{
    "multi_match": {
      "query": "1",
      "fields": ["FieldOnType1", "FieldOnType2"]
    }
  }
}
</code>```

If you need to use different fields, should should work:

```<code>GET test,test1/_search
{
   "query":{
     "bool": {
       "should": [
         {
           "term": {"firstName": "john"}
         },
         {
           "term": {"firstName1": "jerry1"}
         }
      ]
    }
   }
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an Elasticsearch index called my_index which contains documents of two types, Type1 and Type2.

The two document types contain different data about the same type of entity.

The two document types both contain the ID of the related entity.

I've been trying to construct a join-like query which would return entities which match conditions on both document types, but I can't get it to work, and I also can't find any citation in the Elasticsearch multi-type or query documentation that says it's not possible.

The problem I'm trying to solve is avoiding having to manually join two result sets by getting all Type1 hits and all Type2 hits and doing the join outside of Elasticsearch, since the index has millions of documents.

The equivalent in SQL would be

select * from
  Type1 inner join Type2
    on Type2.EntityId = Type1.EntityId
where
  Type1.Field = Condition AND
  Type2.Field = Condition [...]

The URL I'm using to query against is http://elastic/my_index/Type1,Type2/_search to include both document types.

If I perform a blank query against this URL, I get hits of both Type1 and Type2.

If I add a criterion for Type1, it works as expected:

{ "query": {
  "bool": {
    "must": [{
      "term": {
        "FieldOnType1": "lorem" } } ] } } }

Somehow Elasticsearch can infer that FieldOnType1 is indeed a field on Type1.

When I add a criterion for Type2, I don't get any hits:

{ "query": {
  "bool": {
    "must": [{
      "term": {
        "FieldOnType1": "lorem" } }, {
      "term": {
        "FieldOnType2": "ipsum" } } ] } } }

In reality, there are sometimes more than 2 term queries, or range queries and term queries.

I'm guessing the problem with the above query is that no single document can match both criteria at once.

I've tried

using should instead of must, and I've tried

qualifying the field names with type names, and I've tried

many variations of the query (including using filters instead of queries)

but everything gives me 0 hits.

Similar questions here suggest to use the Elasticsearch multi-search API instead of the search API, but that won't solve my "manual join" problem.

Is there a way to make an elaborate "OR" query that would allow queries on both types? Or something else?

Body:
Try multi_match query (I use ES 6, so have index p/type):

GET index1,index2/_search
{
  "query":{
    "multi_match": {
      "query": "1",
      "fields": ["FieldOnType1", "FieldOnType2"]
    }
  }
}

If you need to use different fields, should should work:

GET test,test1/_search
{
   "query":{
     "bool": {
       "should": [
         {
           "term": {"firstName": "john"}
         },
         {
           "term": {"firstName1": "jerry1"}
         }
      ]
    }
   }
 }


问:
This move constructor of Microsoft example appears to have redundant code
The MSDN page for developers has this code snippet:

```<code>// Move constructor.
MemoryBlock(MemoryBlock&& other) : _data(nullptr), _length(0)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "
             << other._length << ". Moving resource." << std::endl;

   // Copy the data pointer and its length from source object.
   _data = other._data;      // Assginment 1
   _length = other._length;  // Assignment 2

   // Release the data pointer from the source object so that
   // the destructor does not free the memory multiple times.
   other._data = nullptr;
   other._length = 0;
}
</code>```

What's the use of _data(nullptr), _length(0), when the instructions labelled Assignment 1 and Assignment 2 over-write the values of _data and _length?

答:
Surely it should be</p>

```<code>// Move constructor.
MemoryBlock(MemoryBlock&& other) : _data(other._data), _length(other._length)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "
             << other._length << ". Moving resource." << std::endl;

   // Release the data pointer from the source object so that
   // the destructor does not free the memory multiple times.
   other._data = nullptr;
   other._length = 0;
}
</code>```

Body:
The MSDN page for developers has this code snippet:

// Move constructor.
MemoryBlock(MemoryBlock&& other) : _data(nullptr), _length(0)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "
             << other._length << ". Moving resource." << std::endl;

   // Copy the data pointer and its length from source object.
   _data = other._data;      // Assginment 1
   _length = other._length;  // Assignment 2

   // Release the data pointer from the source object so that
   // the destructor does not free the memory multiple times.
   other._data = nullptr;
   other._length = 0;
}

What's the use of _data(nullptr), _length(0), when the instructions labelled Assignment 1 and Assignment 2 over-write the values of _data and _length?

Body:
Surely it should be

// Move constructor.
MemoryBlock(MemoryBlock&& other) : _data(other._data), _length(other._length)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "
             << other._length << ". Moving resource." << std::endl;

   // Release the data pointer from the source object so that
   // the destructor does not free the memory multiple times.
   other._data = nullptr;
   other._length = 0;
}


问:
GODI installation issue
I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.

```<code>$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!
</code>```

I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being:

```<code> /home/nlucaroni/godi/etc
</code>```

(...and the directory exists, with the godi.conf file present). So, I can't figure out why ./bootstrap_stage2 isn't working.

答:
What is the output of which godi_confdir?

P.S. I remember having this exact same problem, but I don't remember precisely how I fixed it.

OwnerDisplayName: nlucaroni

ContentLicense: CC BY-SA 2.5

Title: GODI installation issue

Body:
I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.

$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!

I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being:

 /home/nlucaroni/godi/etc

(...and the directory exists, with the godi.conf file present). So, I can't figure out why ./bootstrap_stage2 isn't working.

LastEditorDisplayName: nlucaroni

OwnerDisplayName: Chris Conway


问:
What are some good sql databases for home Vista computer?
I have been trying for a long time to get SQL Server Express on my computer to practice my C#/SQL with and I still haven't gotten it to work.

Are there other programs I can use to setup an SQL database to practice with?  If so, which are the best ones for Vista?

EDIT:
To be clear I am not new to SQL programming, I just haven't done any in a while and want to stay fresh.  So I would like something that has most of the features of forms of SQL I would use professionally.

答:
SQLite is good if you need something fast, small and powerful... its a fast download also.

SQLite

SQLite with C#

OwnerDisplayName: GordonG

LastEditorDisplayName: GordonG


问:
Brother printer Esc/P
I am wanting to print pricing labels for a list of products.  I cannot use the csv as the prices change and am doing this through an in house application. How do I send like an array of data to the printer.  I can print one label at a time, however this is slow.  Through the P Template software it prints really quick.  Any help would be much appreciated.

I am sending the commands to the printer in Hex and they work ok.  Can print with Esc/P mode and with P Template mode.  P Template mode is better as the layout can be set and stored on the printer, then all I need to do is send the object data.

Any help on how to send an array of sorts would be much appreciated.

答:
We are using a Mac computer (any Unix machine will do the same) and send the data to the printer from a simple bash script. If using a Windows computer, it will work the same way, just find a way to send binary data to the serial/USB port.

(The reason a Unix machine is preferred by us, because we also communicate to an external server database via Internet, an easy task in Unix scripting).

All Unix machines have 'lp' command, which can send binary data to printer. I wrote a script in bash terminal, which parces its arguments, copies them to 'data' variable, then sends this 'data' variable to the printer.

In short, a small label can be printed like this:

```<code>data="\x1Bia\x00"       # set esc_p mode
data="${data}\x1B@"     # initialize printer (resets many variables)
data="${data}\x1BX\x32" # set font height
data="${data}Hello"     # the actual data to be printed
data="${data}\x0C"      # advances the page (basically prints the label)

# Check your binary on the screen (for debugging):
echo -ne $data | hexdump -C

# Send the data to the printer
echo -ne $data | lp -d Brother_PT_P900W
</code>```

Of course, you must replace the 'Brother_PT_P900W' with your own printer name.

Title: Brother printer Esc/P

Body:
We are using a Mac computer (any Unix machine will do the same) and send the data to the printer from a simple bash script. If using a Windows computer, it will work the same way, just find a way to send binary data to the serial/USB port.

(The reason a Unix machine is preferred by us, because we also communicate to an external server database via Internet, an easy task in Unix scripting).

All Unix machines have 'lp' command, which can send binary data to printer. I wrote a script in bash terminal, which parces its arguments, copies them to 'data' variable, then sends this 'data' variable to the printer.

In short, a small label can be printed like this:

data="\x1Bia\x00"       # set esc_p mode
data="${data}\x1B@"     # initialize printer (resets many variables)
data="${data}\x1BX\x32" # set font height
data="${data}Hello"     # the actual data to be printed
data="${data}\x0C"      # advances the page (basically prints the label)

# Check your binary on the screen (for debugging):
echo -ne $data | hexdump -C

# Send the data to the printer
echo -ne $data | lp -d Brother_PT_P900W

Of course, you must replace the 'Brother_PT_P900W' with your own printer name.


问:
How to set the google analytics opt-out cookie for sub-domains
I am setting the google opt-out cookie as described here and the ga-disable cookie is set.
https://developers.google.com/analytics/devguides/collection/gajs/#disable

Unfortunately the cookie is set for /example.com only and on any subdomains like xy.example.com the ga-disable cookie is not recognized.

I would like the opt-out of the cookie to be valid on all the subdomains.

How to I accomplish this ?

The code that is running and setting the Google opt-out cookie:

// Set to the same value as the web property used on the site
var gaProperty = 'UA-yyyyyy';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
}

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
    window[disableStr] = true;
}
</script>```

thanks a lot!

答:
The domain needed to be set as domain=.example.com;
Important is the leading dot that makes the opt-out cookie work on all subdomains.

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; domain=.example.com; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
  window[disableStr] = true;
}```

Body:
I am setting the google opt-out cookie as described here and the ga-disable cookie is set.
https://developers.google.com/analytics/devguides/collection/gajs/#disable

Unfortunately the cookie is set for /example.com only and on any subdomains like xy.example.com the ga-disable cookie is not recognized.

I would like the opt-out of the cookie to be valid on all the subdomains.

How to I accomplish this ?

The code that is running and setting the Google opt-out cookie:

// Set to the same value as the web property used on the site
var gaProperty = 'UA-yyyyyy';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
}

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
    window[disableStr] = true;
}
</script>

thanks a lot!

ContentLicense: CC BY-SA 4.0


问:
JavaScript: Get parent element values on click event
I'm completely new to JavaScript and struggling to get this working. I'm trying to display contact details in an alert box when a button is clicked.

The information is displayed in nested DIVs outlined below:

```<code><div class="info-and-actions">
<div class="info">
  <div class="name-container">
    <h4 class="name"><a href="#" title="Name" class="name-link">Trader 1</a></h4>
  </div>
<div class="details-container">
  <p class="tele">###############</p>
  <p class="email">hello@url.com</p>
</div>
  <div class="actions">
    <button class="displayContactDetails">Display contact details</button>
  </div>
</div>
</div>

<div class="info-and-actions">
<div class="info">
  <div class="name-container">
    <h4 class="name"><a href="#" title="Name" class="name-link">Trader 2</a></h4>
  </div>
<div class="details-container">
  <p class="tele">###############</p>
  <p class="email">hello@url.com</p>
</div>
  <div class="actions">
    <button class="displayContactDetails">Display contact details</button>
  </div>
</code>```

I am using this JavaScript with an event listener on the displayContactDetails button to display the contact details in the alert box.

```<code>function displayContactDetails() {
var contactName = document.querySelector("a.name-link.profile-link").textContent;
var contactTele = document.querySelector("p.tele").textContent;
alert("Contact " + contactName + " on " + contactTele);
}
</code>```

This currently displays the first trader's contact details when any displayContactDetails button is clicked.

What I want to do is select the relevant contact information from the parent elements of the button (.name-container and .details-container) - so when the second button is clicked, Trader 2's details are displayed.

How do I traverse the DOM to achieve this?

答:
Your event will have the necessary info to locate the corresponding telephone element.

```<code>function displayContactDetails(e) {
    var contactName = e. currentTarget  // this is the element that has the click listener
        .parentNode  // this would be .actions div
        .parentNode  // this would be .info div
        .querySelector('.name a')  // the link with the name
        .innerHTML; // the inner contents of the link, in this case the name

    // repeat but change querySelector to grab the telephone

    alert("Contact " + contactName + " on " + contactTele);
}
</code>```

or easier with jquery

```<code>$('.displayContactDetails').on('click', function(e){
    var name = $(this)
              .closest('.info') // goes up in the tree until .info
              .find('.name').html(); // then back to .name and get content

    alert(name);
});
</code>```

With jquery it is not only easier, but it is also more resilient to changes in the html structure. Jquery will go up the DOM tree until it finds the .info div. With plain js you have to hardcode the number of times to jump to the parent element, or make a loop for it.

You can also try the other answers suggested but you also have to maintain the additional id's and markup required for it to work.

Body:
I'm completely new to JavaScript and struggling to get this working. I'm trying to display contact details in an alert box when a button is clicked.

The information is displayed in nested DIVs outlined below:

Trader 1

###############

hello@url.com

    <button class="displayContactDetails">Display contact details</button>

Trader 2

###############

hello@url.com

    <button class="displayContactDetails">Display contact details</button>

I am using this JavaScript with an event listener on the displayContactDetails button to display the contact details in the alert box.

function displayContactDetails() {
var contactName = document.querySelector("a.name-link.profile-link").textContent;
var contactTele = document.querySelector("p.tele").textContent;
alert("Contact " + contactName + " on " + contactTele);
}

This currently displays the first trader's contact details when any displayContactDetails button is clicked.

What I want to do is select the relevant contact information from the parent elements of the button (.name-container and .details-container) - so when the second button is clicked, Trader 2's details are displayed.

How do I traverse the DOM to achieve this?

Body:
Your event will have the necessary info to locate the corresponding telephone element.

function displayContactDetails(e) {
    var contactName = e. currentTarget  // this is the element that has the click listener
        .parentNode  // this would be .actions div
        .parentNode  // this would be .info div
        .querySelector('.name a')  // the link with the name
        .innerHTML; // the inner contents of the link, in this case the name

    // repeat but change querySelector to grab the telephone

    alert("Contact " + contactName + " on " + contactTele);
}

or easier with jquery

$('.displayContactDetails').on('click', function(e){
    var name = $(this)
              .closest('.info') // goes up in the tree until .info
              .find('.name').html(); // then back to .name and get content

    alert(name);
});

With jquery it is not only easier, but it is also more resilient to changes in the html structure. Jquery will go up the DOM tree until it finds the .info div. With plain js you have to hardcode the number of times to jump to the parent element, or make a loop for it.

You can also try the other answers suggested but you also have to maintain the additional id's and markup required for it to work.


问:
storing and retrieving images in dictionary - python
Can anyone tell me how to store images in python dictionary (dict), and how to retrieve images from the dictionary based on the key value ?

答:
Personally, if I had to go down that road, I would load the image into a variable and then add it to dictionary as a value {key:value} as you would with any other variable. If you are using Pygame you don't need to load it as a file and can already load the image using pygame.image.load(file) .

Just a note : Loading image files, especially JPEGs in binary as suggested is tricky. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

As with images in dictionaries, you could even nest a list of images in the dictionary (along with a key), Having a list is one way to easily animate by looping the list within each key. {'key1' : ['value1', 'value2','value2']}

Remember however that once you pack a variable inside a dictionary, the value of the variable would not change and remain constant inside the dictionary, unless you specifically update the dictionary. Just updating the value outside of the dictionary, would not affect it's original value that it was given when it was placed inside the dictionary.

Example: (using pygame, load images into a list, and nest it into a dictionary for recall)

```<code>def load_image(file):
    """loads and prepares image from data directory"""
    file = os.path.join(main_dir, 'data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error()))
    return surface.convert()

def load_images(*files):
    """ function to load a list of images through an *arg and return a list
    of images"""
    images = []
    for file in files:
        images.append(load_image(file))
    return images

bomb_images = load_images('bomb.gif', 'bomb2.gif','bomb3.gif')
explosion_images = load_images('ex1.gif', 'ex2.gif', 'ex3.gif')
# now all the images are inside a list and you can pack them in a dictionary

image_dict = {'bomb' : bomb_images, 'explode' :explosion_images}
# to call the image would be the same as you call any value from the dict
bombs = image_dict['bomb']

image_ready_for_blit = bombs[0]
# changing the slice position allows animation loops [0]
</code>```

Body:
Personally, if I had to go down that road, I would load the image into a variable and then add it to dictionary as a value {key:value} as you would with any other variable. If you are using Pygame you don't need to load it as a file and can already load the image using pygame.image.load(file) .

Just a note : Loading image files, especially JPEGs in binary as suggested is tricky. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

As with images in dictionaries, you could even nest a list of images in the dictionary (along with a key), Having a list is one way to easily animate by looping the list within each key. {'key1' : ['value1', 'value2','value2']}

Remember however that once you pack a variable inside a dictionary, the value of the variable would not change and remain constant inside the dictionary, unless you specifically update the dictionary. Just updating the value outside of the dictionary, would not affect it's original value that it was given when it was placed inside the dictionary.

Example: (using pygame, load images into a list, and nest it into a dictionary for recall)

def load_image(file):
    """loads and prepares image from data directory"""
    file = os.path.join(main_dir, 'data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error()))
    return surface.convert()

def load_images(*files):
    """ function to load a list of images through an *arg and return a list
    of images"""
    images = []
    for file in files:
        images.append(load_image(file))
    return images

bomb_images = load_images('bomb.gif', 'bomb2.gif','bomb3.gif')
explosion_images = load_images('ex1.gif', 'ex2.gif', 'ex3.gif')
# now all the images are inside a list and you can pack them in a dictionary

image_dict = {'bomb' : bomb_images, 'explode' :explosion_images}
# to call the image would be the same as you call any value from the dict
bombs = image_dict['bomb']

image_ready_for_blit = bombs[0]
# changing the slice position allows animation loops [0]


问:
Keeping the same background across multiple activities in Android and excluding them from activity transitions
I'm working on an Android application at the moment. Basically, I have multiple ViewFlippers which will be used to create sets of 'panels'. For example, I have a ViewFlipper to simulate a home screen environment (multiple panels that can be accessed by swiping left or right), as well as a different ViewFlipper to simulate an application launcher (panels for favorite apps, all apps, settings etc). I've done this by creating each set of panels, or each ViewFlipper in it's own activity, to preserve memory when a set of panels aren't being used.

Basically, I want to keep the same background image across all the activities. Now, I know this can be done by creating a style, and applying it in the  tags in the manifest, but my issue is that the background image is included in the activity transition animation (my own custom animation has been set, but regardless, using stock transition animations or not, the background image is included).

So, what I am asking is, is there a way to keep a common background image across multiple activities that is NOT animated when switching between activities?

At the moment, my style xml file looks like this:

```<code><style name="Theme" parent="android:Theme">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@drawable/background_port</item>
</style>
</code>```

So as you can see, the same drawable is being set as the background for all activities, but it is included in the transition animations between activities, which I don't want. I also have tried android:detachWallpaper="true", but that seems useless in this case.

I'm fairly experienced in Android code, so no need to explain things in simple manners. If I don't understand something, I'll ask.

Thanks for all your help, it's really appreciated.

答:
I don't think there's an easy solution for this, but something I've done in the past to get something similar happening is this; I've removed the activity transition by calling something like overridePendingTransition(0,0) just after the startActivity.

Then when the activities are about to change I've manually animated the view elements off screen, and then animated the new view elements on screen in the new activity.

Also, on a side note, if you're after a nice easy panels type view component, have a look at SwipeView https://github.com/fry15/uk.co.jasonfry.android.tools

Body:
I'm working on an Android application at the moment. Basically, I have multiple ViewFlippers which will be used to create sets of 'panels'. For example, I have a ViewFlipper to simulate a home screen environment (multiple panels that can be accessed by swiping left or right), as well as a different ViewFlipper to simulate an application launcher (panels for favorite apps, all apps, settings etc). I've done this by creating each set of panels, or each ViewFlipper in it's own activity, to preserve memory when a set of panels aren't being used.

Basically, I want to keep the same background image across all the activities. Now, I know this can be done by creating a style, and applying it in the  tags in the manifest, but my issue is that the background image is included in the activity transition animation (my own custom animation has been set, but regardless, using stock transition animations or not, the background image is included).

So, what I am asking is, is there a way to keep a common background image across multiple activities that is NOT animated when switching between activities?

At the moment, my style xml file looks like this:

So as you can see, the same drawable is being set as the background for all activities, but it is included in the transition animations between activities, which I don't want. I also have tried android:detachWallpaper="true", but that seems useless in this case.

I'm fairly experienced in Android code, so no need to explain things in simple manners. If I don't understand something, I'll ask.

Thanks for all your help, it's really appreciated.


问:
Racket function passing empty list instead of actual list
I'm pretty new to racket and I'm trying to make a finite state machine for a project. here's what I have so far.

```<code>#lang racket

(define (test rules cs pass lst)
  (if (eq? (length lst) 0)
      (if (member cs pass)
          (write 'passed)
          (write 'failed))
      (test rules (next rules cs (car lst)) (cdr lst))))

(define (next rules cs input)
  (if (eq? cs (car (car rules)))
      (if (eq? input (car(cdr(car rules))))
          (car(cdr(cdr(car rules))))
          ((next (cdr rules) cs input)))
      (next (cdr rules) cs input)))
</code>```

then I input

```<code>(define rules '('(0 a 0) '(0 b 1) '(1 a 0) '(1 b 1)))
(define pass '(1))
(test rules 0 pass '(a b a b))
</code>```

and for a reason that I cannot figure out, I get
this error on the next function. It acts as though rules is an empty list, which I'm pretty sure it's not. Anyway if anyone could tell me why it's doing that it would really help.

Thanks!

EDIT1

Thanks so much for the help guys. It's really helping. The code is working entirely until the end, but now it throws an error at the end of my code if I test multiple lists with testmany.

```<code>(define (testmany rules cs pass lst)(if (eq? (length lst) 0)
                                        (write 'done)
        ((test rules cs pass (car lst))
         (testmany rules cs pass (cdr lst)))))

(define (test rules cs pass lst) (if (eq? (length lst) 0)
        (if (member cs pass)
            (write 'accepted.....)
            (write 'rejected.....))
        (test rules (next rules cs (car lst)) pass (cdr lst))))

(define (next rules cs input) (if (eq? cs (car (car rules)))
         (if (eq? input (car(cdr(car rules))))
             (car(cdr(cdr(car rules))))
             (next (cdr rules) cs input))
         (next (cdr rules) cs input)))
</code>```

The code doesn't seem to know when to stop the recursion of the testmany function. When the list is empty, it prints done, but then continues the next part as if the list still had elements, throwing this error.  If anyone knows why it is throwing this error please let me know.
Thanks!

答:
You forgot the begin:

```<code>(define (testmany rules cs pass lst) (if (eq? (length lst) 0)
                                         (write 'done)
        (begin
       ; ^^^^^ here
         (test rules cs pass (car lst))
         (testmany rules cs pass (cdr lst)))))
</code>```

Without it, the return value of (test rules cs pass (car lst)) is attempted to be used as a function; but it is #<void>, the result of (write ....) form, which is the last one evaluated (more like, executed) by your test function.

By the way, #<void> is not an empty list; it's more like a non-value.

edit: the reason it does recurse to the end (without the begin) is that to apply a function foo in (foo val) to a value val, both expressions are evaluated first.

It is only after the evaluation of val, i.e. (testmany ...), finishes fully that the error is discovered that the value of foo, i.e. (test ...) expression, is not in fact a function, and can not be applied.

Body:
I'm pretty new to racket and I'm trying to make a finite state machine for a project. here's what I have so far.

#lang racket

(define (test rules cs pass lst)
  (if (eq? (length lst) 0)
      (if (member cs pass)
          (write 'passed)
          (write 'failed))
      (test rules (next rules cs (car lst)) (cdr lst))))

(define (next rules cs input)
  (if (eq? cs (car (car rules)))
      (if (eq? input (car(cdr(car rules))))
          (car(cdr(cdr(car rules))))
          ((next (cdr rules) cs input)))
      (next (cdr rules) cs input)))

then I input

(define rules '('(0 a 0) '(0 b 1) '(1 a 0) '(1 b 1)))
(define pass '(1))
(test rules 0 pass '(a b a b))

and for a reason that I cannot figure out, I get
this error on the next function. It acts as though rules is an empty list, which I'm pretty sure it's not. Anyway if anyone could tell me why it's doing that it would really help.

Thanks!

EDIT1

Thanks so much for the help guys. It's really helping. The code is working entirely until the end, but now it throws an error at the end of my code if I test multiple lists with testmany.

(define (testmany rules cs pass lst)(if (eq? (length lst) 0)
                                        (write 'done)
        ((test rules cs pass (car lst))
         (testmany rules cs pass (cdr lst)))))

(define (test rules cs pass lst) (if (eq? (length lst) 0)
        (if (member cs pass)
            (write 'accepted.....)
            (write 'rejected.....))
        (test rules (next rules cs (car lst)) pass (cdr lst))))

(define (next rules cs input) (if (eq? cs (car (car rules)))
         (if (eq? input (car(cdr(car rules))))
             (car(cdr(cdr(car rules))))
             (next (cdr rules) cs input))
         (next (cdr rules) cs input)))

The code doesn't seem to know when to stop the recursion of the testmany function. When the list is empty, it prints done, but then continues the next part as if the list still had elements, throwing this error.  If anyone knows why it is throwing this error please let me know.
Thanks!

Body:
You forgot the begin:

(define (testmany rules cs pass lst) (if (eq? (length lst) 0)
                                         (write 'done)
        (begin
       ; ^^^^^ here
         (test rules cs pass (car lst))
         (testmany rules cs pass (cdr lst)))))

Without it, the return value of (test rules cs pass (car lst)) is attempted to be used as a function; but it is #<void>, the result of (write ....) form, which is the last one evaluated (more like, executed) by your test function.

By the way, #<void> is not an empty list; it's more like a non-value.

edit: the reason it does recurse to the end (without the begin) is that to apply a function foo in (foo val) to a value val, both expressions are evaluated first.

It is only after the evaluation of val, i.e. (testmany ...), finishes fully that the error is discovered that the value of foo, i.e. (test ...) expression, is not in fact a function, and can not be applied.


问:
Retrieving ALSA playback delay
I am trying to play sound on a Raspberry Pi 3 retrieved from a library. I need to provide an accurate time for when the samples will hit the speaker. The library will then provide the samples synchronized to the time. I am using ALSA to play the sound. However I do not seem to be able to get the time accurately. I have tried several combinations of snd_pcm_htimestamp(), snd_pcm_delay(), snd_pcm_status_get_delay() and snd_pcm_status_get_audio_htstamp(). I have also tried with both writei and mmap.

Can anyone give me a hint to how I can retrieve an accurate time for when the samples will be played?

答:
Now I am going to answer my own question. It turns out that using snd_pcm_status() is actually the way to go. I just had a bug in my first attempt. The following code calculates the time the next sample added will be played in nanoseconds since boot:</p>

```<code>snd_pcm_status_t *pcm_status;
snd_pcm_status_alloca(&pcm_status); //Allocate space on the stack
snd_pcm_status(handle, pcm_status);
int delay = snd_pcm_status_get_delay(pcm_status);
snd_htimestamp_t tstamp;
snd_pcm_status_get_audio_htstamp(pcm_status, &tstamp);

uint64_t Time = tstamp.tv_sec * (uint64_t)1000000000 + tstamp.tv_nsec;
Time += (delay * (uint64_t)1000000000) / 44100;
</code>```

Title: Retrieving ALSA playback delay

Body:
Now I am going to answer my own question. It turns out that using snd_pcm_status() is actually the way to go. I just had a bug in my first attempt. The following code calculates the time the next sample added will be played in nanoseconds since boot:

snd_pcm_status_t *pcm_status;
snd_pcm_status_alloca(&pcm_status); //Allocate space on the stack
snd_pcm_status(handle, pcm_status);
int delay = snd_pcm_status_get_delay(pcm_status);
snd_htimestamp_t tstamp;
snd_pcm_status_get_audio_htstamp(pcm_status, &tstamp);

uint64_t Time = tstamp.tv_sec * (uint64_t)1000000000 + tstamp.tv_nsec;
Time += (delay * (uint64_t)1000000000) / 44100;


问:
ASP.NET Core with mobile application
I'm working on a project that needs a web site and mobile application. User can interact with our system through website or mobile application. Now the real problem I'm facing is how should I structure it?
Options I considered:

ASP.NET Core website + Mobile application --> ASP.NET Core REST API

ASP.NET Core as website + rest endpoints <-- Mobile application

答:
You should always expose your backend functionality through rest endpoints. This way any consumer like ASP.NET website or Mobile application can consume it using their rest client.

Exposing it through rest will enable client written in any technology to consume.

So your first option seems to be the suitable one.

Title: ASP.NET Core with mobile application


问:
apduToolTask cannot be found
i am new to java card platform and presently i am using java card classic edition v 3.0.1 and when i am using Apache ANT command - ant all to build the build.xml file, i am getting the following error:

c:\java\java_card_kit-2_2_2\samples\build.xml:17: taskdef class com.sun.javacard.ant.tasks.APDUToolTask cannot be found

I've already followed the instructions to the point where it asks me to setup the System path of ANT as well. I'm using ANT 1.8.1.

can someone please help.

Regards,

答: Continue by following instructions from next sections "Installing the Ant Tasks" and "Library Dependencies" from java_card_kit-2_2_2-windows.zip\java_card_kit-2_2_2\java_card_kit-2_2_2-rr-ant-tasks.zip\ant-tasks\docs\pdf\ant-user-guide.pdf, pages 4-5.</p>

Title: apduToolTask cannot be found


问:
Laravel authentication with Ardent, Entrust & Confide
I had a Laravel 4.2 app with custom authentication through Confide. I have upgraded to Laravel 5.5 and Confide has no support for it.

Now I wanted to make use of Laravels native authentication, however I can't run Auth::attempt() because it is expecting

```<code>class User extends Authenticatable
</code>```

but I already have

```<code>class User extends Ardent
</code>```

Is there some simple solution without needing to do something extreme like push all validation to validation request classes and getting rid of Ardent? (it is a large scale app, so it would require significant refactor)

答:
I have solved my issue with interfaces and traits, so now I have User model like this:

```<code>use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class User extends Ardent implements AuthenticatableContract
{
    use Authenticatable;
    ...
}
</code>```

Body:
I had a Laravel 4.2 app with custom authentication through Confide. I have upgraded to Laravel 5.5 and Confide has no support for it.

Now I wanted to make use of Laravels native authentication, however I can't run Auth::attempt() because it is expecting

class User extends Authenticatable

but I already have

class User extends Ardent

Is there some simple solution without needing to do something extreme like push all validation to validation request classes and getting rid of Ardent? (it is a large scale app, so it would require significant refactor)

Body:
I have solved my issue with interfaces and traits, so now I have User model like this:

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class User extends Ardent implements AuthenticatableContract
{
    use Authenticatable;
    ...
}


问:
How to implement a limited feature rollout (language agnostic) to your users?

I would like to know some common or best practices of rolling out a new website feature to a select group of the userbase.

The users could be, for example, based solely on a percentage of your overall user base (10%). The rollout should be customizable (configurable) and support any number of features.  It would also be useful to associate rollouts to specific user roles or privileges (ACL).

So, in essence, what is an architecture that would scale reasonably well?

As for the language agnostic portion, you can either provide pseudo-code, general concepts or ideas, or snippets from your preferred language to get your point across.

Links to any examples or tutorials are welcome.

答:
At my last job we accomplished this using the load balancer and a current revision cookie.

The load balancer set a cookie identifying the revision number of the instance that the user was using. If that cookie was already present, the load balancer would just send that request to a running instance with the corresponding revision. When we deployed a new revision, the load balancer continued to send traffic with an existing revision cookie to their original revision until that revision was no longer running or the user closed their browser. New traffic would get sent to the newly deployed revision. This allowed us to test out changes for a bit while our existing users were continuing to run on the old revision. We could also manually set that cookie to test out the new rev internally on the production environment before turning new traffic onto it. When we were comfortable that the new revision had no major problems we could bring down the old revision and all traffic would start going to the latest revision.

That setup does not support backwards incompatible database changes though. There's pretty much no way to do it where you can have part of your users on one db schema and part on another, and be able to take writes to both and then somehow merge those writes together after you've decided the new rev is ok. I mean, it's possible but it really depends on what the schema changes are exactly and how they effect your app, so you can't do it in a reliable, agnostic way on deployment. For us, we just generally tried not to do backwards incompatible schema changes. If we really did need to, we'd try to postpone the destructive part (dropping a column or table) to a later revision where we could migrate the schema and have both versions running with no adverse effect on current users.


问:
ASP.NET MVC - How to set default value in View
I have a field in MS SQL that has bit as data type as show below.

MS SQL Overview

In ASP.NET MVC, I want to set a value for it and make it hidden.

```<code>public bool EmailConfirmed { get; set; }
</code>```

View

```<code>@Html.HiddenFor(model => model.EmailConfirmed, new { htmlAttributes = new { @class = "form-control", @Value = "True" } })
</code>```

However, it is not working.

I have these questions:

How do I write bit data type in ASP.NET MVC

How do I write the default value in the View

答:
You have a couple of option here

● It seems you're using SMSS, so in the Column Properties, you can use Default Value

and set it to 1.

● You can set the value in the constructor.

```<code>//C# 5 or earlier
public YourConstructor()
{
    EmailConfirmed = true;
}

// or (C# 6 and +)
public bool EmailConfirmed { get; set; } = true;
</code>```

So you don't need to force any @Value in your htmlAttributes.

But be careful : As mentioned in comments, you shouldn't use these solutions because any malicious user may alter your view. If you want to post true systematically, just don't do anything in your view and add true to your property directly in your HttpPost action.

Body:
I have a field in MS SQL that has bit as data type as show below.

MS SQL Overview

In ASP.NET MVC, I want to set a value for it and make it hidden.

public bool EmailConfirmed { get; set; }

View

@Html.HiddenFor(model => model.EmailConfirmed, new { htmlAttributes = new { @class = "form-control", @Value = "True" } })

However, it is not working.

I have these questions:

How do I write bit data type in ASP.NET MVC

How do I write the default value in the View

Body:
You have a couple of option here

● It seems you're using SMSS, so in the Column Properties, you can use Default Value

and set it to 1.

● You can set the value in the constructor.

//C# 5 or earlier
public YourConstructor()
{
    EmailConfirmed = true;
}

// or (C# 6 and +)
public bool EmailConfirmed { get; set; } = true;

So you don't need to force any @Value in your htmlAttributes.

But be careful : As mentioned in comments, you shouldn't use these solutions because any malicious user may alter your view. If you want to post true systematically, just don't do anything in your view and add true to your property directly in your HttpPost action.


问:
C++ using derived class variable in base class
```<code>The below is my code design
class D;
class A {
   D *d;
   class B:public C {
   somefunctions();
   }
}

class C {
    //I need to use class D variables inside Class C
}
</code>```

Whatever I do inside the Class C for bringing Class D variables,
it is throwing Invalid use of Incomplete 'Class D' and Forward declaration of 'class D'. The thing is we can't move the class positions.
Need your help, Please give suggestions with examples.
Thanks in advance for your help

答:
The long and short of your problem revolves around your design being a bit like spaghetti.  It goes all over the place, and one can not simply work through 1 class at a time and understand what it should do.

To be able to use any function of class D, or create one, the compiler must know what functions are available to that class and how large it is.  For that reason, to be able to get this to compile, the simplest thing to do is migrate the implementation of class C into its own cpp file, and then include the D header at the top of that.  If that's not an option, then I think you should just save yourself a load of heartache and redesign sooner rather than later.

Body:
The below is my code design
class D;
class A {
   D *d;
   class B:public C {
   somefunctions();
   }
}

class C {
    //I need to use class D variables inside Class C
}

Whatever I do inside the Class C for bringing Class D variables,
it is throwing Invalid use of Incomplete 'Class D' and Forward declaration of 'class D'. The thing is we can't move the class positions.
Need your help, Please give suggestions with examples.
Thanks in advance for your help


问:
Round Display Picture
Im creating an application which includes the home screen. This will have a biography of the client. Im trying to create a header, which will include the title and a round display image. From the code i used 3 divs, which will hold the wrapper, title and picture. I done the display:flex which will have them in 1 line, and flex:1 to move the image to the right. When doing the radius 50% its squishing the photo . Can you help me out?

Thanks. Heres the code.

.headerOfBio {
  display: flex
}

.displayPic {
  flex: 1 background-image: url("../images/displayPicture.jpg") border-radius: 50%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="quote titleBio">
  <div class="headerOfBio">
    <h3>
      MEET THE <span class="diffColor">FOUNDER</span>
    </h3>

    <div class="displayPic">

    </div>
  </div>

</div></code>```

After adding height and width it becomes like this:

答:
Instead of adding a background image to a div, adding a img tag will give a better result.

.headerOfBio {
  display: flex;
}

.displayPic img {
  flex: 1;
  width:50%;
  border-radius:100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="quote titleBio">
  <div class="headerOfBio">
    <h3>
      MEET THE <span class="diffColor">FOUNDER</span>
    </h3>

    <div class="displayPic">
      <img src="https://placeimg.com/250/250/nature" />
    </div>
  </div>

</div></code>```

Title: Round Display Picture

Body:
Im creating an application which includes the home screen. This will have a biography of the client. Im trying to create a header, which will include the title and a round display image. From the code i used 3 divs, which will hold the wrapper, title and picture. I done the display:flex which will have them in 1 line, and flex:1 to move the image to the right. When doing the radius 50% its squishing the photo . Can you help me out?

Thanks. Heres the code.

.headerOfBio {
  display: flex
}

.displayPic {
  flex: 1 background-image: url("../images/displayPicture.jpg") border-radius: 50%
}

      MEET THE FOUNDER

After adding height and width it becomes like this:

Body:
Instead of adding a background image to a div, adding a img tag will give a better result.

.headerOfBio {
  display: flex;
}

.displayPic img {
  flex: 1;
  width:50%;
  border-radius:100%
}

<div class="quote titleBio">
  <div class="headerOfBio">
    <h3>
      MEET THE <span class="diffColor">FOUNDER</span>
    </h3>

    <div class="displayPic">
      <img src="https://placeimg.com/250/250/nature" />
    </div>
  </div>

</div>


问:
Ruby's `lazy` less performant than allocating huge lists?
I'm trying to process a large list of numbers:

```<code>require 'benchmark'

N = 999999

Benchmark.bm 10 do |bm|
   bm.report 'Eager:' do
 (0..N).select(&:even?).map{|x| x * x}.reduce(&:+)
   end
   bm.report 'Lazy:' do
 (0..N).lazy.select(&:even?).map{|x| x * x}.reduce(&:+)
   end
 end;
</code>```

To my understanding, the lazy version should be much faster, because the eager version needs to allocate two lists of half a million items each(one for select and one for map) while the lazy version is streaming everything.

However, when I run it, the lazy version takes more than twice as long as the eager one! (http://rextester.com/OTEX7399)

```<code>         user     system      total        real
Eager:       0.210000   0.010000   0.220000 (  0.216572)
Lazy:        0.580000   0.000000   0.580000 (  0.635091)
</code>```

How can it be?

答:
I'd say an Enumerator is a far slower middle man than memory is.

This was also reported a while back and Ruby core team member Yusuke Endoh said:

Enumerator::Lazy is not a silver bullet; it removes the overhead for
  creating an intermediate array, but brings the drawback for calling
  a block. Unfortunately, the latter is much bigger than the former.
  Thus, in general, Lazy does bring performance drawback.

An analogy I just thought of: Imagine you're building some furniture for a friend.

Non-lazy: You build the whole thing, rent a truck, and drive it to your friend.

Lazy: You build a little piece and drive it to your friend with your car. You build the next little piece and drive it to your friend with your car. You build the next little piece and drive it to your friend with your car. And so on.

Yes, renting that truck is extra overhead, but it's nothing compared to driving over and over again with your car.

The real reason that being lazy can save time is that after the first few pieces your friend finds out that you slept with his wife so now you're no longer friends and he doesn't want your stupid furniture anymore and you're not building the remaining pieces at all.

Body:
I'm trying to process a large list of numbers:

require 'benchmark'

N = 999999

Benchmark.bm 10 do |bm|
   bm.report 'Eager:' do
 (0..N).select(&:even?).map{|x| x * x}.reduce(&:+)
   end
   bm.report 'Lazy:' do
 (0..N).lazy.select(&:even?).map{|x| x * x}.reduce(&:+)
   end
 end;

To my understanding, the lazy version should be much faster, because the eager version needs to allocate two lists of half a million items each(one for select and one for map) while the lazy version is streaming everything.

However, when I run it, the lazy version takes more than twice as long as the eager one! (http://rextester.com/OTEX7399)

         user     system      total        real
Eager:       0.210000   0.010000   0.220000 (  0.216572)
Lazy:        0.580000   0.000000   0.580000 (  0.635091)

How can it be?


问:
Type of generic abstract react component
This is my first question, please be gentle ;)

I have several components which share behavior, so I would like to have them all extend the same class, so I don't have to duplicate my functionality:

export abstract class FooComponent
 extends React.Component
 {
    foobar: Foobar = new Foobar();
}
```

<p>Other classes inherit this component like:</p>

<pre class="lang-js prettyprint-override"><code>export class BarComponent extends FooComponent<{baz?: boolean}> {
    //dostuff
}
</code>```

I try to pass these classes as a type into a function, like so:

setFoo (foo: typeof FooComponent) {
    let obj = { foo: foo };
    this.foo = <obj.foo />;
}

this.setFoo(BarComponent);
```

<p>but my compiler throws the following error:</p>

<p><code>Type 'BarComponent' is not assignable to type 'FooComponent<any>'.
  Property 'foobar' is missing in type 'BarComponent'.</code></p>

<p>It works if I don't extend the props, making FooComponent non-generic, but the FooComponents all have different props, which would not be type-safe if I were to set them as any.</p>

<p>Is there a way I can pass the type of my derived classes, and use them as my base class?</p>

<h2>Edit</h2>

<hr>

<p>I found a way to remove all the different props in my FooComponents, so I could make it a base class without a generic type as shown below.</p>

<pre class="lang-js prettyprint-override"><code>export abstract class FooComponent extends React.Component<{baz?: boolean}, {}> {
    foobar: Foobar = new Foobar();
}
</code>```

This way, the setFoo function as shown in the original question works, and no longer throws an error.

Thanks for the provided answers though, They gave me some new insights.

答:
You're almost there :

```<code>React.createElement(foo, whateverProps);
</code>```

should do the trick. whateverProps is an object that contains, well, props for the foo class. Be aware that by doing this, you lose some of the TypeScript advantages because the compiler won't be able to check the props against the class' props interface.

Body:
This is my first question, please be gentle ;)

I have several components which share behavior, so I would like to have them all extend the same class, so I don't have to duplicate my functionality:

export abstract class FooComponent
 extends React.Component
 {
    foobar: Foobar = new Foobar();
}

Other classes inherit this component like:

export class BarComponent extends FooComponent<{baz?: boolean}> {
    //dostuff
}

I try to pass these classes as a type into a function, like so:

setFoo (foo: typeof FooComponent) {
    let obj = { foo: foo };
    this.foo = <obj.foo />;
}

this.setFoo(BarComponent);

but my compiler throws the following error:

Type 'BarComponent' is not assignable to type 'FooComponent<any>'.
  Property 'foobar' is missing in type 'BarComponent'.

It works if I don't extend the props, making FooComponent non-generic, but the FooComponents all have different props, which would not be type-safe if I were to set them as any.

Is there a way I can pass the type of my derived classes, and use them as my base class?

Edit

I found a way to remove all the different props in my FooComponents, so I could make it a base class without a generic type as shown below.

export abstract class FooComponent extends React.Component<{baz?: boolean}, {}> {
    foobar: Foobar = new Foobar();
}

This way, the setFoo function as shown in the original question works, and no longer throws an error.

Thanks for the provided answers though, They gave me some new insights.

Body:
You're almost there :

React.createElement(foo, whateverProps);

should do the trick. whateverProps is an object that contains, well, props for the foo class. Be aware that by doing this, you lose some of the TypeScript advantages because the compiler won't be able to check the props against the class' props interface.


问:
Can't run rails server after installing custom-err-msg
After I install the custom-err-msg plugin, I get an error when I try to run rails server:

```<code>$ rails server
=> Booting WEBrick
=> Rails 3.0.3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/home/jason/rails/snip/vendor/plugins/custom-err-msg/init.rb:3: uninitialized constant ActiveRecord::Errors (NameError)
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/plugin.rb:81
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `instance_exec'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `run'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:50:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `each'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:134:in `initialize!'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `send'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `method_missing'
    from /home/jason/rails/snip/config/environment.rb:5
    from /home/jason/rails/snip/config.ru:3:in `require'
    from /home/jason/rails/snip/config.ru:3
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `instance_eval'
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `initialize'
    from /home/jason/rails/snip/config.ru:1:in `new'
    from /home/jason/rails/snip/config.ru:1
</code>```

Any idea why this is happening?

答:
Here's an updated version that will work with Rails 3.

https://github.com/seansawyer/custom-err-msg

To fix the undefined method keys for nil:NilClass error, a method in lib/custom_error_message.rb needs to be changed to this:

```<code>def starts_with_humanized_column_followed_by_circumflex?(message)
  keys.any? do |column|
    humanized = @base.class.human_attribute_name column.to_s.split('.').last.to_s
    message.match(/^#{humanized} \^/)
  end
end
</code>```

Someone, please send him a pull request!

Body:
After I install the custom-err-msg plugin, I get an error when I try to run rails server:

$ rails server
=> Booting WEBrick
=> Rails 3.0.3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/home/jason/rails/snip/vendor/plugins/custom-err-msg/init.rb:3: uninitialized constant ActiveRecord::Errors (NameError)
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/plugin.rb:81
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `instance_exec'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `run'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:50:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `each'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:134:in `initialize!'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `send'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `method_missing'
    from /home/jason/rails/snip/config/environment.rb:5
    from /home/jason/rails/snip/config.ru:3:in `require'
    from /home/jason/rails/snip/config.ru:3
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `instance_eval'
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `initialize'
    from /home/jason/rails/snip/config.ru:1:in `new'
    from /home/jason/rails/snip/config.ru:1

Any idea why this is happening?

Body:
Here's an updated version that will work with Rails 3.

https://github.com/seansawyer/custom-err-msg

To fix the undefined method keys for nil:NilClass error, a method in lib/custom_error_message.rb needs to be changed to this:

def starts_with_humanized_column_followed_by_circumflex?(message)
  keys.any? do |column|
    humanized = @base.class.human_attribute_name column.to_s.split('.').last.to_s
    message.match(/^#{humanized} \^/)
  end
end

Someone, please send him a pull request!


问:
Python - how to replace the same char in a string with random integer for each occurence
i have the following string for Example

```<code>str = "TESTXXXXX"
</code>```

and i want to replace each X with a number, so the output should be something like this:

```<code>TEST98965
</code>```

not :

```<code>TEST66666
</code>```

i made the following python script to do the job.

```<code>from sys import argv
from random import randint

bincode = argv[1].lower()
replaced = bincode.replace('x',str(randint(0,9)))
print replaced
</code>```

it takes a input from a user, and replaces each 'x' with a random number, the problem here is that the script replaces all the 'x' with the same number, i want each 'x' to be replaced with a different number, for example if user input is:

xxx

the output would be something like this:

986

Any suggestions on how to do that?

答:
you have to generate a new random integer every time</p>

```<code>from sys import argv
from random import randint

bincode = argv[1].lower()
bc = ''
tgchar= 'x'

for c in bincode:
    #print(c) not sure why I put this
    if c != tgchar:
        bc = bc + (c)
    else:
        bc = bc + (str(randint(0,9)))

print(bc)
</code>```

Body:
i have the following string for Example

str = "TESTXXXXX"

and i want to replace each X with a number, so the output should be something like this:

TEST98965

not :

TEST66666

i made the following python script to do the job.

from sys import argv
from random import randint

bincode = argv[1].lower()
replaced = bincode.replace('x',str(randint(0,9)))
print replaced

it takes a input from a user, and replaces each 'x' with a random number, the problem here is that the script replaces all the 'x' with the same number, i want each 'x' to be replaced with a different number, for example if user input is:

xxx

the output would be something like this:

986

Any suggestions on how to do that?

Body:
you have to generate a new random integer every time

from sys import argv
from random import randint

bincode = argv[1].lower()
bc = ''
tgchar= 'x'

for c in bincode:
    #print(c) not sure why I put this
    if c != tgchar:
        bc = bc + (c)
    else:
        bc = bc + (str(randint(0,9)))

print(bc)


问:
How do I avoid a media player crash when the back button is clicked on the device?
I have a media player in an Android Studio project. It crashes when the back button is clicked on the connected phone. This is what I gathered from the Logcat as the fault: "Unable to destroy activity {com.example.proj/com.example.proj.RadioActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference"

Here's the relevant snippet:

```<code>@Override
public void onDestroy() {
    super.onDestroy();
    stop();
}

public void onCompletion(MediaPlayer mp) {
    stop();
}
</code>```

I've found that if I click "Play" and then the back button, the app does not crash, suggesting that play is not a null object reference even if no media is playing).

How do I write a condition that if the back button is clicked and the MediaPlayer is not playing, do not destroy the player/app? I have no reference to the button in the code.

答:
Override onBackPressed() in your activity and add your stop() method in it. Add the following code:

```<code>@Override
public void onBackPressed(){
   super.onBackPressed();
}
</code>```

Body:
I have a media player in an Android Studio project. It crashes when the back button is clicked on the connected phone. This is what I gathered from the Logcat as the fault: "Unable to destroy activity {com.example.proj/com.example.proj.RadioActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference"

Here's the relevant snippet:

@Override
public void onDestroy() {
    super.onDestroy();
    stop();
}

public void onCompletion(MediaPlayer mp) {
    stop();
}

I've found that if I click "Play" and then the back button, the app does not crash, suggesting that play is not a null object reference even if no media is playing).

How do I write a condition that if the back button is clicked and the MediaPlayer is not playing, do not destroy the player/app? I have no reference to the button in the code.

Body:
Override onBackPressed() in your activity and add your stop() method in it. Add the following code:

@Override
public void onBackPressed(){
   super.onBackPressed();
}


答:
Use this code in on back press :</p>

```<code>   @Override
    public void onBackPressed() {
    if (videoView.isPlaying()) {
        videoView.pause();
    }
    super.onBackPressed();
}
</code>```

Title: How do I avoid a media player crash when the back button is clicked on the device?

Body:
Use this code in on back press :

   @Override
    public void onBackPressed() {
    if (videoView.isPlaying()) {
        videoView.pause();
    }
    super.onBackPressed();
}


问:
How to get the pure color filling for 'tripcolor' in matplotlib
The class 'tripcolor' in matplotlib gives a very powerful tool to create a contour-style plot for those 2D-triangles just like:

```<code>plt.tripcolor(x,y,triangles,vars,cmap='PuOr')
</code>```

Though there are many types of defined colormaps for usage, but now I cannot find a proper method just for pure color filling for these triangles. Does anybody know how to do it? Thanks for telling me.

答:
It feels rather strange, but it seems the easiest solution to have a tripcolor plot filled with a single color is to create a colormap which only has a single color in it and supply it to the tripcolor.

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors

xy = np.asarray([ [-0.01, 0.9], [-0.1, 0.8], [-0.05, 0.6], [-0.08, 0.9]])
triangles = np.asarray([[3, 2, 0]  , [3, 1, 2],   [ 0, 2, 1] , [0, 1, 2]])

# generate some array of length same as xy
c = np.ones(len(xy))
# create a colormap with a single color
cmap = matplotlib.colors.ListedColormap("limegreen")
# tripcolorplot with a single color filling:
plt.tripcolor(xy[:,0],xy[:,1],triangles, c, edgecolor="k", lw=2, cmap=cmap)
plt.show()
</code>```

Body:
The class 'tripcolor' in matplotlib gives a very powerful tool to create a contour-style plot for those 2D-triangles just like:

plt.tripcolor(x,y,triangles,vars,cmap='PuOr')

Though there are many types of defined colormaps for usage, but now I cannot find a proper method just for pure color filling for these triangles. Does anybody know how to do it? Thanks for telling me.

Body:
It feels rather strange, but it seems the easiest solution to have a tripcolor plot filled with a single color is to create a colormap which only has a single color in it and supply it to the tripcolor.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors

xy = np.asarray([ [-0.01, 0.9], [-0.1, 0.8], [-0.05, 0.6], [-0.08, 0.9]])
triangles = np.asarray([[3, 2, 0]  , [3, 1, 2],   [ 0, 2, 1] , [0, 1, 2]])

# generate some array of length same as xy
c = np.ones(len(xy))
# create a colormap with a single color
cmap = matplotlib.colors.ListedColormap("limegreen")
# tripcolorplot with a single color filling:
plt.tripcolor(xy[:,0],xy[:,1],triangles, c, edgecolor="k", lw=2, cmap=cmap)
plt.show()


问:
Android Architecture Components: bind to ViewModel
I'm a bit confused about how data binding should work when using the new Architecture Components.

let's say I have a simple Activity with a list, a ProgressBar and a TextView. the Activity should be responsible for controlling the state of all the views, but the ViewModel should hold the data and the logic.
For example, my Activity now looks like this:

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

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);

    binding.setViewModel(listViewModel);

    list = findViewById(R.id.games_list);

    listViewModel.getList().observeForever(new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });

    listViewModel.loadGames();
}

private void setUpList(List<Game> items){
    list.setLayoutManager(new LinearLayoutManager(this));
    GameAdapter adapter = new GameAdapter();
    adapter.setList(items);
    list.setAdapter(adapter);
}
</code>```

and the ViewModel it's only responsible for loading the data and notify the Activity when the list is ready so it can prepare the Adapter and show the data:

```<code>public int progressVisibility = View.VISIBLE;

private MutableLiveData<List<Game>> list;

public void loadGames(){

    Retrofit retrofit = GamesAPI.create();

    GameService service = retrofit.create(GameService.class);

    Call<GamesResponse> call = service.fetchGames();

    call.enqueue(this);
}

@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        setList(response.body().data);

    }
}

@Override
public void onFailure(Call<GamesResponse> call, Throwable t) {

}

public MutableLiveData<List<Game>> getList() {
    if(list == null)
        list = new MutableLiveData<>();
    if(list.getValue() == null)
        list.setValue(new ArrayList<Game>());
    return list;
}

public void setList(List<Game> list) {
    this.list.postValue(list);
}
</code>```

My question is: which is the correct way to show/hide the list, progressbar and error text?

should I add an Integer for each View in the ViewModel making it control the views and using it like:

```<code><TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibility}" />
</code>```

or should the ViewModel instantiate a LiveData object for each property:

```<code>private MutableLiveData<Integer> progressVisibility = new MutableLiveData<>();
private MutableLiveData<Integer> listVisibility = new MutableLiveData<>();
    private MutableLiveData<Integer> errorVisibility = new MutableLiveData<>();
</code>```

update their value when needed and make the Activity observe their value?

```<code>viewModel.getProgressVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        progress.setVisibility(visibility);
    }
});

viewModel.getListVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        list.setVisibility(visibility);
    }
});

viewModel.getErrorVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        error.setVisibility(visibility);
    }
});
</code>```

I'm really struggling to understand that. If someone can clarify that, it would be great.

Thanks

答:
Here are simple steps to achieve your point.

First, have your ViewModel expose a LiveData object, and you can start the LiveData with an empty value.

```<code>private MutableLiveData<List<Game>> list = new MutableLiveData<>();

public MutableLiveData<List<Game>> getList() {
    return list;
}
</code>```

Second, have your view (activity/fragment) observe that LiveData and change UI accordingly.

```<code>listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);
listViewModel.data.observe(this, new Observer<List<Game>>() {
    @Override
    public void onChanged(@Nullable final List<Game> games) {
        setUpList(games);
    }
});
</code>```

Here it is important that you use the observe(LifecycleOwner, Observer) variant so that your observer do NOT receive events after that LifecycleOwner is no longer active, basically, that means that when your activity of fragment is no longer active, you won't leak that listener.

Third, as a result of data becoming available you need to update your LiveData object.

```<code>@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        List<Game> newGames = response.body().data; // Assuming this is a list
        list.setValue(newGames); // Update your LiveData object by calling setValue
    }
}
</code>```

By calling setValue() on your LiveData, this will cause onChanged on your view's listener to be called and your UI should be updated automatically.

Body:
I'm a bit confused about how data binding should work when using the new Architecture Components.

let's say I have a simple Activity with a list, a ProgressBar and a TextView. the Activity should be responsible for controlling the state of all the views, but the ViewModel should hold the data and the logic.
For example, my Activity now looks like this:

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

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);

    binding.setViewModel(listViewModel);

    list = findViewById(R.id.games_list);

    listViewModel.getList().observeForever(new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });

    listViewModel.loadGames();
}

private void setUpList(List<Game> items){
    list.setLayoutManager(new LinearLayoutManager(this));
    GameAdapter adapter = new GameAdapter();
    adapter.setList(items);
    list.setAdapter(adapter);
}

and the ViewModel it's only responsible for loading the data and notify the Activity when the list is ready so it can prepare the Adapter and show the data:

public int progressVisibility = View.VISIBLE;

private MutableLiveData<List<Game>> list;

public void loadGames(){

    Retrofit retrofit = GamesAPI.create();

    GameService service = retrofit.create(GameService.class);

    Call<GamesResponse> call = service.fetchGames();

    call.enqueue(this);
}

@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        setList(response.body().data);

    }
}

@Override
public void onFailure(Call<GamesResponse> call, Throwable t) {

}

public MutableLiveData<List<Game>> getList() {
    if(list == null)
        list = new MutableLiveData<>();
    if(list.getValue() == null)
        list.setValue(new ArrayList<Game>());
    return list;
}

public void setList(List<Game> list) {
    this.list.postValue(list);
}

My question is: which is the correct way to show/hide the list, progressbar and error text?

should I add an Integer for each View in the ViewModel making it control the views and using it like:

<TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibility}" />

or should the ViewModel instantiate a LiveData object for each property:

private MutableLiveData<Integer> progressVisibility = new MutableLiveData<>();
private MutableLiveData<Integer> listVisibility = new MutableLiveData<>();
    private MutableLiveData<Integer> errorVisibility = new MutableLiveData<>();

update their value when needed and make the Activity observe their value?

viewModel.getProgressVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        progress.setVisibility(visibility);
    }
});

viewModel.getListVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        list.setVisibility(visibility);
    }
});

viewModel.getErrorVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        error.setVisibility(visibility);
    }
});

I'm really struggling to understand that. If someone can clarify that, it would be great.

Thanks

Body:
Here are simple steps to achieve your point.

First, have your ViewModel expose a LiveData object, and you can start the LiveData with an empty value.

private MutableLiveData<List<Game>> list = new MutableLiveData<>();

public MutableLiveData<List<Game>> getList() {
    return list;
}

Second, have your view (activity/fragment) observe that LiveData and change UI accordingly.

listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);
listViewModel.data.observe(this, new Observer<List<Game>>() {
    @Override
    public void onChanged(@Nullable final List<Game> games) {
        setUpList(games);
    }
});

Here it is important that you use the observe(LifecycleOwner, Observer) variant so that your observer do NOT receive events after that LifecycleOwner is no longer active, basically, that means that when your activity of fragment is no longer active, you won't leak that listener.

Third, as a result of data becoming available you need to update your LiveData object.

@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        List<Game> newGames = response.body().data; // Assuming this is a list
        list.setValue(newGames); // Update your LiveData object by calling setValue
    }
}

By calling setValue() on your LiveData, this will cause onChanged on your view's listener to be called and your UI should be updated automatically.


问:
Angular 5 + Typescript - Return array of newly created typed objects
I have a service where i am retrieving "moments" from my backend. I have 2 functions. A get() method which returns 1 object and a search() method which returns an array of objects.

moment.service.ts

In the get method, i map the res from the backend to create a new instance of my Moment class. Which works fine.

```<code>   get(moment_id) {

        let endpoint = this.path + moment_id;

        return this.apiService.get(endpoint)
                              .map((res) => new Moment(res.data));
    }
</code>```

I want to do the same except in the search method. It should map the array so all objects inside it are a new instance of the moment class.

```<code>search(filters) {

    let endpoint = this.path + 'search';

    let params = new HttpParams({ fromObject: filters });

    return this.apiService.get(endpoint, params)
                          .map((res) => new Array<Moment>(res));
}
</code>```

However, this does not work the array returned does not show that the objects are of type Moment.

moment.component.ts

```<code>   moments: Moment[] = [];

    this.momentService.search(filters).subscribe((res) => {
                this.moments = res;
                console.log(this.moments);
            });
</code>```

moment.model.ts

```<code>import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;

    constructor(data?: Moment) {
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {

        const keys = Object.keys(this);
        for (const key of keys) {
            if (key === 'author') {
                this[key] = new User(data['author']);
            } else if (key === 'comments') {
                this[key] = data['comments'].map(c => new Comment(c));
            } else {
                this[key] = data[key];
            }
        }
    }
}
</code>```

答:
Try instantiating moments as follows:</p>

```<code>search(filters) {

    let endpoint = this.path + 'search';

    let params = new HttpParams({ fromObject: filters });

    return this.apiService.get(endpoint, params)
                          .map((res) => new Array<Moment>(new Moment(res)));
}
</code>```

Body:
I have a service where i am retrieving "moments" from my backend. I have 2 functions. A get() method which returns 1 object and a search() method which returns an array of objects.

moment.service.ts

In the get method, i map the res from the backend to create a new instance of my Moment class. Which works fine.

   get(moment_id) {

        let endpoint = this.path + moment_id;

        return this.apiService.get(endpoint)
                              .map((res) => new Moment(res.data));
    }

I want to do the same except in the search method. It should map the array so all objects inside it are a new instance of the moment class.

search(filters) {

    let endpoint = this.path + 'search';

    let params = new HttpParams({ fromObject: filters });

    return this.apiService.get(endpoint, params)
                          .map((res) => new Array<Moment>(res));
}

However, this does not work the array returned does not show that the objects are of type Moment.

moment.component.ts

   moments: Moment[] = [];

    this.momentService.search(filters).subscribe((res) => {
                this.moments = res;
                console.log(this.moments);
            });

moment.model.ts

import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;

    constructor(data?: Moment) {
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {

        const keys = Object.keys(this);
        for (const key of keys) {
            if (key === 'author') {
                this[key] = new User(data['author']);
            } else if (key === 'comments') {
                this[key] = data['comments'].map(c => new Comment(c));
            } else {
                this[key] = data[key];
            }
        }
    }
}

Body:
Try instantiating moments as follows:

search(filters) {

    let endpoint = this.path + 'search';

    let params = new HttpParams({ fromObject: filters });

    return this.apiService.get(endpoint, params)
                          .map((res) => new Array<Moment>(new Moment(res)));
}