问:
How to unit test presenter method based on an Observable returned value?
Having the following real implementation of a function, where mTallesPreferences.isUserAuthenticated() returns an Observable<Boolean> type value:

```<code>override fun showInitialScreen() {
    mTallesPreferences.isUserAuthenticated()
            .subscribe { isAuthenticated ->
                if (isAuthenticated) mView?.showMainScreen()
                else mView?.showAccessScreen()
                mView?.closeCurrentScreen()
            }
 }
</code>```

How can I unit test if mView?.showAccessScreen() is called when subscriber gets isAuthenticated = false?

I have tried the following approach, but unfortunately NullPointerException appears on the scene.

```<code>class LaunchPresenterTest {

    @Mock
    lateinit var mView: LaunchContract.View

    @Mock
    lateinit var mTallesPreferences: TallesPreferencesApi

    private lateinit var mPresenter: LaunchPresenter

    @Before
    fun setupLaunchPresenter() {
        MockitoAnnotations.initMocks(this)
        mPresenter = LaunchPresenter(mTallesPreferences)
    }

    @Test
    fun testShowInitialScreenNotAuthenticated() {
        mPresenter.showInitialScreen()
        Mockito.`when`(mTallesPreferences.isUserAuthenticated()).thenReturn(Observable.just(false))
        Mockito.verify(mView).showAccessScreen()
    }

}
</code>```

答:
Your functions are in the wrong order. When you call showInitialScreen() the mTallesPreferences.isUserAuthenticated() is not mocked to return the value you want. Re-order your test method like:

```<code>@Test
fun testShowInitialScreenNotAuthenticated() {
    Mockito.`when`(mTallesPreferences.isUserAuthenticated()).thenReturn(Observable.just(false))
    mPresenter.showInitialScreen()
    Mockito.verify(mView).showAccessScreen()
}
</code>```

Body:
Having the following real implementation of a function, where mTallesPreferences.isUserAuthenticated() returns an Observable<Boolean> type value:

override fun showInitialScreen() {
    mTallesPreferences.isUserAuthenticated()
            .subscribe { isAuthenticated ->
                if (isAuthenticated) mView?.showMainScreen()
                else mView?.showAccessScreen()
                mView?.closeCurrentScreen()
            }
 }

How can I unit test if mView?.showAccessScreen() is called when subscriber gets isAuthenticated = false?

I have tried the following approach, but unfortunately NullPointerException appears on the scene.

class LaunchPresenterTest {

    @Mock
    lateinit var mView: LaunchContract.View

    @Mock
    lateinit var mTallesPreferences: TallesPreferencesApi

    private lateinit var mPresenter: LaunchPresenter

    @Before
    fun setupLaunchPresenter() {
        MockitoAnnotations.initMocks(this)
        mPresenter = LaunchPresenter(mTallesPreferences)
    }

    @Test
    fun testShowInitialScreenNotAuthenticated() {
        mPresenter.showInitialScreen()
        Mockito.`when`(mTallesPreferences.isUserAuthenticated()).thenReturn(Observable.just(false))
        Mockito.verify(mView).showAccessScreen()
    }

}

Body:
Your functions are in the wrong order. When you call showInitialScreen() the mTallesPreferences.isUserAuthenticated() is not mocked to return the value you want. Re-order your test method like:

@Test
fun testShowInitialScreenNotAuthenticated() {
    Mockito.`when`(mTallesPreferences.isUserAuthenticated()).thenReturn(Observable.just(false))
    mPresenter.showInitialScreen()
    Mockito.verify(mView).showAccessScreen()
}


来源: stackexchange

问:
Div is truncating words and border on wrapping
Maybe this is simple, but is making me nuts.
To understand the problem, the easy way is to look at the image.

Div width is truncating either word or the rounded border(also in case there is a space or dash between words). How can I force each "a" element to go into a new line if width is not enough to contain the element?

Here's the code

```<code><div id="post-tags">
    <span class="tag-title">Tagged:</span>
                            <a href="#">tag2</a>
                            <a href="#">tag3</a>
                            <a href="#">tag4</a>
                            <a href="#">longtag5</a>
                            <a href="#"li>longtag6</a>
                            <a href="#">longtag7</a>
                            <a href="#">longtag8</a>
                            <a href="#">longtag9</a>
                            <a href="#">longtag10</a>
                            <a href="#">longtag11</a>
                            <a href="#">longtag12</a>
                </div>
</code>```

And the CSS

```<code>   #post-tags{
     width: 560px;
     float: left;
     padding: 15px;
     font-size: 11px;
     }

  #post-tags .tag-title{
     color: #6b6b6b;
     padding:  5px 0 0 5px;
    }

 #post-tags a{
     line-height: 24px;
     padding: 3px;
     background: #a7d1e3;
     padding: 4px 10px 4px 10px;
     margin: 0 0 10px 0;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    }

 #post-tags a:hover{
     color: #a7d1e3;
     background: #205F82;

    }
</code>```

答:
I found that it doesn't work corerctly in chrome. A solution could be to float the elements. so you add float:left; for the selectors #post-tags .tag-title and #post-tags a. Of course now you will see that there is need to modify and padding and margins. A solution close to yours is applying margin: 0 2px 10px; and padding: 0 10px; for #post-tags a so your new css will seems like the following:

```<code>#post-tags {
    width: 560px;
    padding: 15px;
    font-size: 11px;
    overflow:hidden;
}
#post-tags .tag-title {
    color: #6b6b6b;
    padding:  5px 0 0 5px;
    float:left;
}
#post-tags a {
    line-height: 24px;
    padding: 3px;
    background: #a7d1e3;
    margin: 0 2px 10px;
    padding: 0 10px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    float:left
}
#post-tags a:hover {
    color: #a7d1e3;
    background: #205F82;
}
</code>```

here a live example: http://jsbin.com/adika4

ContentLicense: CC BY-SA 2.5

Body:
Maybe this is simple, but is making me nuts.
To understand the problem, the easy way is to look at the image.

Div width is truncating either word or the rounded border(also in case there is a space or dash between words). How can I force each "a" element to go into a new line if width is not enough to contain the element?

Here's the code

    Tagged:
                            tag2
                            tag3
                            tag4
                            longtag5
                            longtag6
                            longtag7
                            longtag8
                            longtag9
                            longtag10
                            longtag11
                            longtag12

And the CSS

   #post-tags{
     width: 560px;
     float: left;
     padding: 15px;
     font-size: 11px;
     }

  #post-tags .tag-title{
     color: #6b6b6b;
     padding:  5px 0 0 5px;
    }

 #post-tags a{
     line-height: 24px;
     padding: 3px;
     background: #a7d1e3;
     padding: 4px 10px 4px 10px;
     margin: 0 0 10px 0;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    }

 #post-tags a:hover{
     color: #a7d1e3;
     background: #205F82;

    }

Body:
I found that it doesn't work corerctly in chrome. A solution could be to float the elements. so you add float:left; for the selectors #post-tags .tag-title and #post-tags a. Of course now you will see that there is need to modify and padding and margins. A solution close to yours is applying margin: 0 2px 10px; and padding: 0 10px; for #post-tags a so your new css will seems like the following:

#post-tags {
    width: 560px;
    padding: 15px;
    font-size: 11px;
    overflow:hidden;
}
#post-tags .tag-title {
    color: #6b6b6b;
    padding:  5px 0 0 5px;
    float:left;
}
#post-tags a {
    line-height: 24px;
    padding: 3px;
    background: #a7d1e3;
    margin: 0 2px 10px;
    padding: 0 10px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    float:left
}
#post-tags a:hover {
    color: #a7d1e3;
    background: #205F82;
}

here a live example: http://jsbin.com/adika4


问:
Telegram Bot API Webhooks with Go, GoLang on Heroku
I use go-telegram-bot-api for building a Telegram Bot and deploying it on Heroku.

I need to set Webhooks as I used to do in Python like in this Python case.

Can't understand how to set Webhooks in go-telegram-bot-api without providing certificate files.

The main example contains such lines:

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

```<code>package main

import (
    "gopkg.in/telegram-bot-api.v4"
    "log"
    "net/http"
)

func main() {
    bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
    if err != nil {
        log.Fatal(err)
    }

    bot.Debug = true

    log.Printf("Authorized on account %s", bot.Self.UserName)

    _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
    if err != nil {
        log.Fatal(err)
    }

    updates := bot.ListenForWebhook("/" + bot.Token)
    go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

    for update := range updates {
        log.Printf("%+v\n", update)
    }
}
</code>```

But using Heroku for deploying how could I listen to Webhooks without providing pem certificate files?

答:
If you are using Heroku for your bot, You don't need certificates. Heroku provides free SSL certificates. So, You put the URL of your app with https scheme and listen with a HTTP Server on the PORT that heroku sets for your application. See the example below to understand better.

```<code>func main() {
    // Create bot instance
    u := fetchUpdates(bot)

    go http.ListenAndServe(":" + PORT, nil)
}

func fetchUpdates(bot *tgbotapi.BotAPI) tgbotapi.UpdatesChannel {
    _, err = bot.SetWebhook(tgbotapi.NewWebhook("https://dry-hamlet-60060.herokuapp.com/instagram_profile_bot/" + bot.Token))
    if err != nil {
        fmt.Fatalln("Problem in setting Webhook", err.Error())
    }

    updates := bot.ListenForWebhook("/instagram_profile_bot/" + bot.Token)

    return updates
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use go-telegram-bot-api for building a Telegram Bot and deploying it on Heroku.

I need to set Webhooks as I used to do in Python like in this Python case.

Can't understand how to set Webhooks in go-telegram-bot-api without providing certificate files.

The main example contains such lines:

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

package main

import (
    "gopkg.in/telegram-bot-api.v4"
    "log"
    "net/http"
)

func main() {
    bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
    if err != nil {
        log.Fatal(err)
    }

    bot.Debug = true

    log.Printf("Authorized on account %s", bot.Self.UserName)

    _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
    if err != nil {
        log.Fatal(err)
    }

    updates := bot.ListenForWebhook("/" + bot.Token)
    go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

    for update := range updates {
        log.Printf("%+v\n", update)
    }
}

But using Heroku for deploying how could I listen to Webhooks without providing pem certificate files?

Body:
If you are using Heroku for your bot, You don't need certificates. Heroku provides free SSL certificates. So, You put the URL of your app with https scheme and listen with a HTTP Server on the PORT that heroku sets for your application. See the example below to understand better.

func main() {
    // Create bot instance
    u := fetchUpdates(bot)

    go http.ListenAndServe(":" + PORT, nil)
}

func fetchUpdates(bot *tgbotapi.BotAPI) tgbotapi.UpdatesChannel {
    _, err = bot.SetWebhook(tgbotapi.NewWebhook("https://dry-hamlet-60060.herokuapp.com/instagram_profile_bot/" + bot.Token))
    if err != nil {
        fmt.Fatalln("Problem in setting Webhook", err.Error())
    }

    updates := bot.ListenForWebhook("/instagram_profile_bot/" + bot.Token)

    return updates
}


问:
Index not used in Postgresql read-replica. Why?
I have a relatively large table on an Amazon RDS production database (in the range of 2M records). I wish to group on a number of fields, including the month of a date (server_time) in the table. To speed things up a bit, I have created an index on the master database as follows:

```<code>create index on build_requests(group_id, artifact_id, account_id, number_of_interfaces, date_trunc('month', server_build_time));
</code>```

Then, as you would expect, the query to group the data uses the index on the master:

```<code>GroupAggregate  (cost=0.55..311308.09 rows=1633231 width=85)
  Group Key: group_id, artifact_id, account_id, number_of_interfaces, date_trunc('month'::text, server_build_time)
  ->  Index Scan using build_requests_group_id_artifact_id_account_id_number_of_in_idx on build_requests  (cost=0.55..262417.68 rows=1898335 width=85)
</code>```

However, after waiting for over an hour, the read replica still does not use the index:

```<code>GroupAggregate  (cost=434678.88..488313.41 rows=1633179 width=85)
  Group Key: group_id, artifact_id, account_id, number_of_interfaces, (date_trunc('month'::text, server_build_time))
  ->  Sort  (cost=434678.88..439424.56 rows=1898274 width=85)
        Sort Key: group_id, artifact_id, account_id, number_of_interfaces, (date_trunc('month'::text, server_build_time))
        ->  Seq Scan on build_requests  (cost=0.00..55053.43 rows=1898274 width=85)
</code>```

Logging into the read replica with pgadmin, I see the index is present however. This is a problem, since the slow speed of the query on the read replica (5 minutes vs 3 seconds), causes other queries that include this query through postgres_fdw (cross database query) to return ssl connection resets (probably timeouts?).

Any idea why the read replica does not pick up/use the index I define on the master, and how I can remedy this? The query I execute on both master and read replica is identical:

```<code>SELECT group_id, artifact_id,
       account_id, number_of_interfaces,
       date_trunc('month', server_build_time) as server_build_month,
       count(*)
FROM build_requests
GROUP BY group_id, artifact_id,
         account_id, number_of_interfaces,
         date_trunc('month', server_build_time);
</code>```

Thanks for your help!

答:
The problem appeared to be with the types of the amazon RDS instances. The original RDS was a t2-medium, whereas the read replica was only a micro instance. After scaling the read replica to medium, the replica too, used the index.

Also, even when the read replica did use the index, simply executing the above query through postgres_fdw caused connection timeouts. It wasn't until I created a view on the master using the index, that the query executed without problem.

Body:
I have a relatively large table on an Amazon RDS production database (in the range of 2M records). I wish to group on a number of fields, including the month of a date (server_time) in the table. To speed things up a bit, I have created an index on the master database as follows:

create index on build_requests(group_id, artifact_id, account_id, number_of_interfaces, date_trunc('month', server_build_time));

Then, as you would expect, the query to group the data uses the index on the master:

GroupAggregate  (cost=0.55..311308.09 rows=1633231 width=85)
  Group Key: group_id, artifact_id, account_id, number_of_interfaces, date_trunc('month'::text, server_build_time)
  ->  Index Scan using build_requests_group_id_artifact_id_account_id_number_of_in_idx on build_requests  (cost=0.55..262417.68 rows=1898335 width=85)

However, after waiting for over an hour, the read replica still does not use the index:

GroupAggregate  (cost=434678.88..488313.41 rows=1633179 width=85)
  Group Key: group_id, artifact_id, account_id, number_of_interfaces, (date_trunc('month'::text, server_build_time))
  ->  Sort  (cost=434678.88..439424.56 rows=1898274 width=85)
        Sort Key: group_id, artifact_id, account_id, number_of_interfaces, (date_trunc('month'::text, server_build_time))
        ->  Seq Scan on build_requests  (cost=0.00..55053.43 rows=1898274 width=85)

Logging into the read replica with pgadmin, I see the index is present however. This is a problem, since the slow speed of the query on the read replica (5 minutes vs 3 seconds), causes other queries that include this query through postgres_fdw (cross database query) to return ssl connection resets (probably timeouts?).

Any idea why the read replica does not pick up/use the index I define on the master, and how I can remedy this? The query I execute on both master and read replica is identical:

SELECT group_id, artifact_id,
       account_id, number_of_interfaces,
       date_trunc('month', server_build_time) as server_build_month,
       count(*)
FROM build_requests
GROUP BY group_id, artifact_id,
         account_id, number_of_interfaces,
         date_trunc('month', server_build_time);

Thanks for your help!


问:
Run docker daemon with lower 1gb ram
My VPS has only 1gb RAM. Does any way to make Docker daemon run with 512 MB setting (The lowser of setting tab of Docker Daemon program is 1GB)?</p>

答:
Although its not a good idea to use only 512 MB ram to run docker still if you want to use docker with that much ram you can make swap space here is the guide which would help you to achieve the same

how to make swap space in ubuntu

Title: Run docker daemon with lower 1gb ram


问:
Next and previous not working properly using jQuery
I am working on the next and previous section. When I clicked on next button then it's displaying the next div but it's not working properly because Next button is working infinit.

Same as the previous button. I need to hide the previous button on page load when the user clicked on next button or scroll the mouse wheel than I have to display the previous button.

I tried some code

new WOW().init();
 (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();

$('.navigation_right').click(function() {
    $('.current').removeClass('current').hide()
        .next().show().addClass('current');
    if ($('.current').hasClass('last')) {
        $('.navigation_right').attr('disabled', true);
    }
    $('.navigation_left').attr('disabled', null);
});

$('.navigation_left').click(function() {
    $('.current').removeClass('current').hide()
        .prev().show().addClass('current');
    if ($('.current').hasClass('first')) {
        $('.navigation_left').attr('disabled', true);
    }
    $('.navigation_right').attr('disabled', null);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #gentags {
position:fixed;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow: hidden;
}

#gentags > div{
    overflow: hidden;
    width:250%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 11.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}
.active_div{

display: none;
}

  /*Navigation style*/
  .horizontal_scroll_icon_pre_next {
    bottom: 50px;
    left: 0;

    position: fixed;

    width: 100%;
    height: 0;
   /* padding: 0 20px;*/
}
  .horizontal_scroll_icon_pre_next button{
  background-color: transparent;
border: none;
font-size: 0;
color: #7b7b7b;
display: none;
outline: 0;
cursor: pointer;
}
.horizontal_scroll_icon_pre_next button.navigation_left
{
 float: left;
}
.horizontal_scroll_icon_pre_next button.navigation_right
{
 float:right;
}

.horizontal_scroll_icon_pre_next button.active {
    display: block;
}
.horizontal_scroll_icon_pre_next button span {

    font-size: 30px;
}</code>```

 <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
     <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

I want to display this div when articles 7 comes on screen

01
Hover me and scroll mouse wheel

02
Hover me and scroll mouse wheel

03
Hover me and scroll mouse wheel

04
Hover me and scroll mouse wheel

05
Hover me and scroll mouse wheel

06
Hover me and scroll mouse wheel

07
Hover me and scroll mouse wheel

08
Hover me and scroll mouse wheel

        <button class="navigation_left active">Previous</button>
        <button class="navigation_right active">Next</button>

 ```

答:
There is a problem with next() function.

it will move only one box at a time it will not move multiple textboxes combined. and you are adding 'current' class to single box and removing as well at a time.

I would suggest you to take a look at it:

http://www.menucool.com/jquery-slider

There are many custom options in this plugin as you are going jquery already.

Peace.

Body:
I am working on the next and previous section. When I clicked on next button then it's displaying the next div but it's not working properly because Next button is working infinit.

Same as the previous button. I need to hide the previous button on page load when the user clicked on next button or scroll the mouse wheel than I have to display the previous button.

I tried some code

new WOW().init();
 (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();

$('.navigation_right').click(function() {
    $('.current').removeClass('current').hide()
        .next().show().addClass('current');
    if ($('.current').hasClass('last')) {
        $('.navigation_right').attr('disabled', true);
    }
    $('.navigation_left').attr('disabled', null);
});

$('.navigation_left').click(function() {
    $('.current').removeClass('current').hide()
        .prev().show().addClass('current');
    if ($('.current').hasClass('first')) {
        $('.navigation_left').attr('disabled', true);
    }
    $('.navigation_right').attr('disabled', null);
});

  #gentags {
position:fixed;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow: hidden;
}

#gentags > div{
    overflow: hidden;
    width:250%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 11.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}
.active_div{

display: none;
}

  /*Navigation style*/
  .horizontal_scroll_icon_pre_next {
    bottom: 50px;
    left: 0;

    position: fixed;

    width: 100%;
    height: 0;
   /* padding: 0 20px;*/
}
  .horizontal_scroll_icon_pre_next button{
  background-color: transparent;
border: none;
font-size: 0;
color: #7b7b7b;
display: none;
outline: 0;
cursor: pointer;
}
.horizontal_scroll_icon_pre_next button.navigation_left
{
 float: left;
}
.horizontal_scroll_icon_pre_next button.navigation_right
{
 float:right;
}

.horizontal_scroll_icon_pre_next button.active {
    display: block;
}
.horizontal_scroll_icon_pre_next button span {

    font-size: 30px;
}

 <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
     <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

I want to display this div when articles 7 comes on screen

01
Hover me and scroll mouse wheel

02
Hover me and scroll mouse wheel

03
Hover me and scroll mouse wheel

04
Hover me and scroll mouse wheel

05
Hover me and scroll mouse wheel

06
Hover me and scroll mouse wheel

07
Hover me and scroll mouse wheel

08
Hover me and scroll mouse wheel

        <button class="navigation_left active">Previous</button>
        <button class="navigation_right active">Next</button>


问:
EmberJS - How to update dateFrom Query Param with Pikaday input
I am using the following input from the ember-pikaday addon:

```<code><div class="col-sm-3"><label>Date From:</label>{{pikaday-input value=dateFrom name="dateFrom" class="form-control"}}</div>
</code>```

I cannot get the value of the input to update the query parameter in the URL. If I use a standard input it works with the following controller:

```<code>import Controller from '@ember/controller';

export default Controller.extend({

queryParams: ['dateFrom', 'dateTo', 'unitNumber'],
dateFrom: null,
dateTo: null,
unitNumber: null,

  actions: {
    selected(x){
      module = x
    },

    submitQuery(dateFrom, dateTo, unitNumber){
        switch(module) {
          case 'Option 1':
          this.transitionToRoute('option1', {queryParams: {dateFrom: this.get('dateFrom'), dateTo: this.get('dateTo'), unitNumber: this.get('unitNumber') }})
        break;
    }
   }
  }
});
</code>```

I suspect I need an action when a date is selected but I do not know how to handle the update within the action. I tried the following:

```<code>//onSelection=(action 'select') added to pikday input

select() {
    dateFrom = this.set('dateFrom')
}
</code>```

But it did not represent in the URL. I think that would be incorrect scoping anyway. I am still very new to Ember (and coding). Any help would be very appreciated.

答:
Here they mentioned how to use this package,
https://github.com/edgycircle/ember-pikaday#usage

```<code>{{pikaday-input onSelection=(action 'doSomethingWithSelectedValue')}}
</code>```

In your case, you need to update the selected value from pikaday input to dateFrom property of the controller.

```<code>{{pikaday-input value=dateFrom name="dateFrom" class="form-control" onSelection=(action 'onChangeDateFrom') }}
</code>```

define actions in the controller actions hash,

```<code>onChangeDateFrom(selectedValue)
{
 this.set('dateFrom',selectedValue);
}
</code>```

Body:
I am using the following input from the ember-pikaday addon:

Date From:{{pikaday-input value=dateFrom name="dateFrom" class="form-control"}}

I cannot get the value of the input to update the query parameter in the URL. If I use a standard input it works with the following controller:

import Controller from '@ember/controller';

export default Controller.extend({

queryParams: ['dateFrom', 'dateTo', 'unitNumber'],
dateFrom: null,
dateTo: null,
unitNumber: null,

  actions: {
    selected(x){
      module = x
    },

    submitQuery(dateFrom, dateTo, unitNumber){
        switch(module) {
          case 'Option 1':
          this.transitionToRoute('option1', {queryParams: {dateFrom: this.get('dateFrom'), dateTo: this.get('dateTo'), unitNumber: this.get('unitNumber') }})
        break;
    }
   }
  }
});

I suspect I need an action when a date is selected but I do not know how to handle the update within the action. I tried the following:

//onSelection=(action 'select') added to pikday input

select() {
    dateFrom = this.set('dateFrom')
}

But it did not represent in the URL. I think that would be incorrect scoping anyway. I am still very new to Ember (and coding). Any help would be very appreciated.

Body:
Here they mentioned how to use this package,
https://github.com/edgycircle/ember-pikaday#usage

{{pikaday-input onSelection=(action 'doSomethingWithSelectedValue')}}

In your case, you need to update the selected value from pikaday input to dateFrom property of the controller.

{{pikaday-input value=dateFrom name="dateFrom" class="form-control" onSelection=(action 'onChangeDateFrom') }}

define actions in the controller actions hash,

onChangeDateFrom(selectedValue)
{
 this.set('dateFrom',selectedValue);
}


问:
ServiceStack.Redis Service availability
I am trying to figure out how check the availability of the Redis Client.
The simple action of calling the client, will give me this information?
Is there a better method?</p>

```<code>private RedisManagerPool redisPool;
public RedisCacheProviderStatus ServiceStatus()
{
    try
    {
        using (IRedisClient client = redisPool.GetClient())
        {
        }
        return RedisCacheProviderStatus.Available;
    }
    catch (Exception)
    {
        return RedisCacheProviderStatus.NotAvailable;
    }
}
</code>```

答:
Call a Redis Operation like Ping():

```<code>using (var redis = redisPool.GetClient())
{
    return ((IRedisNativeClient)redis).Ping()
        ? RedisCacheProviderStatus.Available
        : RedisCacheProviderStatus.NotAvailable;
}
</code>```

Title: ServiceStack.Redis Service availability

Body:
I am trying to figure out how check the availability of the Redis Client.
The simple action of calling the client, will give me this information?
Is there a better method?

private RedisManagerPool redisPool;
public RedisCacheProviderStatus ServiceStatus()
{
    try
    {
        using (IRedisClient client = redisPool.GetClient())
        {
        }
        return RedisCacheProviderStatus.Available;
    }
    catch (Exception)
    {
        return RedisCacheProviderStatus.NotAvailable;
    }
}

Body:
Call a Redis Operation like Ping():

using (var redis = redisPool.GetClient())
{
    return ((IRedisNativeClient)redis).Ping()
        ? RedisCacheProviderStatus.Available
        : RedisCacheProviderStatus.NotAvailable;
}


问:
How to check if a textbox is empty using javascript
I have a jsp page with some TextBoxes. Now I want to fill them with some information and click the submit button. But I need to check whether this TextBox is empty or not.

How can I do this?

答:
```<code>```<form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" />
<input type="submit"/>
</form>```

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false);
    frmvalidator.EnableMsgsTogether();
    frmvalidator.addValidation("name","req","Plese Enter Name");

</script>
</code>```

Note: before using the code above you have to add the gen_validatorv31.js file.

Body:
<pre><form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" />
<input type="submit"/>
</form></pre>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false);
    frmvalidator.EnableMsgsTogether();
    frmvalidator.addValidation("name","req","Plese Enter Name");

</script>

Note: before using the code above you have to add the gen_validatorv31.js file.


问:
Should BufferedReader and InputStreamReader be closed explicitly?
I want to read the content of a InputStream into a String:

```<code>private String readToString(InputStream stream) {
    return new BufferedReader(new InputStreamReader(stream))
            .lines().collect(Collectors.joining("\n"));
}
</code>```

The stream comes from java.lang.Process.

Question: Do I have to explicitly close any of the InputStream, InputStreamReader or BufferedReader in this case?

Sidenote: the linked question is NOT a duplicate, as my question is about HOW to properly close the streams, not how to read the stream to a String!

答:
As per my comment, closing either the BufferedReader or the InputStreamReader will cause the InputStream to be closed. Your readToString method should not close the stream. This is the responsibility of the caller.

The rationale:-

Firstly, consider how you open the stream before you call readToString. A sensible way to do it is:

```<code>try (InputStream myStream = getInputStreamSomehow()) {
    //...
    String content = readToString(myStream);
    //...
}
</code>```

The stream will be closed at the end of your try-with-resources block.

Secondly, consider existing best practices and idioms. Look at Java API methods that, just like your method, read the whole contents of a stream. For example, from Java 9:

readAllBytes()

transferTo(OutputStream out)

Neither of the above methods closes the stream. Similarly, the users of your readToString method will not be expecting you to close their stream.

Body:
I want to read the content of a InputStream into a String:

private String readToString(InputStream stream) {
    return new BufferedReader(new InputStreamReader(stream))
            .lines().collect(Collectors.joining("\n"));
}

The stream comes from java.lang.Process.

Question: Do I have to explicitly close any of the InputStream, InputStreamReader or BufferedReader in this case?

Sidenote: the linked question is NOT a duplicate, as my question is about HOW to properly close the streams, not how to read the stream to a String!

Body:
As per my comment, closing either the BufferedReader or the InputStreamReader will cause the InputStream to be closed. Your readToString method should not close the stream. This is the responsibility of the caller.

The rationale:-

Firstly, consider how you open the stream before you call readToString. A sensible way to do it is:

try (InputStream myStream = getInputStreamSomehow()) {
    //...
    String content = readToString(myStream);
    //...
}

The stream will be closed at the end of your try-with-resources block.

Secondly, consider existing best practices and idioms. Look at Java API methods that, just like your method, read the whole contents of a stream. For example, from Java 9:

readAllBytes()

transferTo(OutputStream out)

Neither of the above methods closes the stream. Similarly, the users of your readToString method will not be expecting you to close their stream.


问:
Kill an App with background Services
I have an application where also running 5 background services. Base service class contains method:

```<code>public override void OnTaskRemoved(Intent rootIntent)
{
    base.OnTaskRemoved(rootIntent);
    StopSelf();
}
</code>```

Above code is working when application is being closed by user - servcies are being stopped. However I have implemeted another feature - user can close an application from itself. To achive that I have found this part of code to use:

```<code>Process.KillProcess(Process.MyPid());
</code>```

Application is being closed while debugging but after application is released there is magic sign

" Application has stopped ".

After some reading I figured out it has to be something with services. Did somone faced similar issue
?

答: You can use Finish() method for activity and call StopService() method for stop particular service</p>

Title: Kill an App with background Services

Body:
I have an application where also running 5 background services. Base service class contains method:

public override void OnTaskRemoved(Intent rootIntent)
{
    base.OnTaskRemoved(rootIntent);
    StopSelf();
}

Above code is working when application is being closed by user - servcies are being stopped. However I have implemeted another feature - user can close an application from itself. To achive that I have found this part of code to use:

Process.KillProcess(Process.MyPid());

Application is being closed while debugging but after application is released there is magic sign

" Application has stopped ".

After some reading I figured out it has to be something with services. Did somone faced similar issue
?


问:
Using JQuery to disable RequiredFieldValidators
I am using JQuery to hide/show a div depending on the selected value of a combo box. This part works fine. However, when hiding the div, the jquery function should also disable 3 RequiredFieldValidators which are in that div. I've been looking online and it seems that this can easily be accomplished using:

```<code>ValidatorEnable(ValidatorName, false);
</code>```

But when I try using that method, nothing works, the RequiredFieldValidators still display an error even though the div is hidden.

My JQuery function:

```<code><script type="text/javascript">
        $(document).ready(function () {
            var det = $("#SponsorDetails");
            $(det).hide();
            var all = $("#AllDetails");
            $(all).hide();

            $("#<%=SelectAccount.ClientID %>").click(function () {
                //hide social worker and sponsor stuff
                var value = $("#<%=SelectAccount.ClientID %> option:selected").val();
                if (value == "Social_Worker") {
                    //show social worker stuff
                    $("#AllDetails").show("slow");
                    $("#SponsorDetails").hide("slow");
                    ValidatorEnable(document.getElementById("#<%=AddressValidator.ClientID %>"), false);
                    ValidatorEnable(document.getElementById("#<%=CityValidator.ClientID %>"), false);
                    ValidatorEnable(document.getElementById("#<%=CountryValidator.ClientID %>"), false);

                } else if (value == "Sponsor") {
                    //show sponsor stuff
                    $("#AllDetails").show("slow");
                    $("#SponsorDetails").show("slow");
                    ValidatorEnable(document.getElementById("#<%=AddressValidator.ClientID %>"), true);
                    ValidatorEnable(document.getElementById("#<%=CityValidator.ClientID %>"), true);
                    ValidatorEnable(document.getElementById("#<%=CountryValidator.ClientID %>"), true);

                }
            });

        });

    </script>
</code>```

Someone suggested I could use Validation groups or a custom validator, but using jquery just seems much simpler but I don't know why it won't work.

答:
You can use following code snippet to enable validator manually for run again...use in Jquery</p>

```<code>  ValidatorEnable($("[id$='RegularExpressionValidator4']")[0], true);
</code>```

Body:
I am using JQuery to hide/show a div depending on the selected value of a combo box. This part works fine. However, when hiding the div, the jquery function should also disable 3 RequiredFieldValidators which are in that div. I've been looking online and it seems that this can easily be accomplished using:

ValidatorEnable(ValidatorName, false);

But when I try using that method, nothing works, the RequiredFieldValidators still display an error even though the div is hidden.

My JQuery function:

Someone suggested I could use Validation groups or a custom validator, but using jquery just seems much simpler but I don't know why it won't work.

Body:
You can use following code snippet to enable validator manually for run again...use in Jquery

  ValidatorEnable($("[id$='RegularExpressionValidator4']")[0], true);


问:
Java Date generate in different timezone that tomcat is running
I have a dates stored in mysql with no timezone, like 2001-01-10 00:00:00.
I have tomcat running in timezone +10:00 for example.
I need to generate a Date() that have no offset int the object.

If I do this:

```<code> Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
 cal.setTime( new Date(/*from 2001-01-10 00:00:00*/) );
 cal.set(Calendar.HOUR_OF_DAY, 0);
 cal.set(Calendar.MINUTE, 0);
 cal.set(Calendar.SECOND, 0);
 cal.set(Calendar.MILLISECOND, 0);
 Date newDate = cal.getTime();
</code>```

The result Date object still having the zoneinfo and zoneoffset reporting to server timezone, not UTC.

I need to generate a Date() Object that have ZERO TIME, but mantain the date stored in mysql, independent of tomcat timezone.
In other words, I want to generate date with zero hour/min/sec independent of server timezone.

```<code>The date generated shows 2001-01-01T00:00:00.000+1400
the time is zero but offset is +14:00.
I want to generate 2001-01-01T00:00:00.000+0000
</code>```

The mysql datatime is DATETIME

答:
The Date object does not keep timezone information, imagine it as a class with only a long property which stores the number of milliseconds that passed from 1970.

The SimpleDateFormat class or other libraries like JODA are responsible of keeping track of timezone when they transform the date to string.

Body:
I have a dates stored in mysql with no timezone, like 2001-01-10 00:00:00.
I have tomcat running in timezone +10:00 for example.
I need to generate a Date() that have no offset int the object.

If I do this:

 Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
 cal.setTime( new Date(/*from 2001-01-10 00:00:00*/) );
 cal.set(Calendar.HOUR_OF_DAY, 0);
 cal.set(Calendar.MINUTE, 0);
 cal.set(Calendar.SECOND, 0);
 cal.set(Calendar.MILLISECOND, 0);
 Date newDate = cal.getTime();

The result Date object still having the zoneinfo and zoneoffset reporting to server timezone, not UTC.

I need to generate a Date() Object that have ZERO TIME, but mantain the date stored in mysql, independent of tomcat timezone.
In other words, I want to generate date with zero hour/min/sec independent of server timezone.

The date generated shows 2001-01-01T00:00:00.000+1400
the time is zero but offset is +14:00.
I want to generate 2001-01-01T00:00:00.000+0000

The mysql datatime is DATETIME


问:
How to use Realm in both iOS and macOS projects of one workspace
I'm trying to figure out how to use Realm in both projects iOS and macOS of a single workspace.
At first try it fails to compile with more than 200 errors.

Workspace currently contains:

MyApp iOS project

MyAppMac macOS project

Pods project

Podfile:

```<code>workspace 'MyApp'

target 'MyApp' do

    workspace 'MyApp'
    xcodeproj 'MyApp.xcodeproj'

    use_frameworks!

    pod 'RealmSwift'
    pod 'SVProgressHUD'

end

target 'MyAppMac' do

    workspace 'MyApp'
    xcodeproj 'MyAppMac.xcodeproj'

    use_frameworks!

    pod 'RealmSwift'

end
</code>```

答:
I just discovered that adding pod 'Realm' to MyAppMac target, works fine and produces no errors.

However, is this optimal?

I've seen some ways to reuse shared pods like RealmSwift but not sure how to do this given the configuration.

Body:
I'm trying to figure out how to use Realm in both projects iOS and macOS of a single workspace.
At first try it fails to compile with more than 200 errors.

Workspace currently contains:

MyApp iOS project

MyAppMac macOS project

Pods project

Podfile:

workspace 'MyApp'

target 'MyApp' do

    workspace 'MyApp'
    xcodeproj 'MyApp.xcodeproj'

    use_frameworks!

    pod 'RealmSwift'
    pod 'SVProgressHUD'

end

target 'MyAppMac' do

    workspace 'MyApp'
    xcodeproj 'MyAppMac.xcodeproj'

    use_frameworks!

    pod 'RealmSwift'

end


问:
Creating a vulnerable Django search bar
I want to create a vulnerable search bar and have done everything but unfortunately, the search function doesn't show any result when I press submit.
But terminal shows successful, "POST /injection/ HTTP/1.1" 200 596</p>

```<code>views.py
    @csrf_exempt
    def search_form(request):
        if 'searchField' in request.POST:
            query= "SELECT * FROM injection_search WHERE injection_search.name LIKE '%searchField%'"
            print(query)
            item = search.objects.raw(query)

        else:
            item = search.objects.all()
        return render(request, 'home.html', {'item' : item})

template/home.html

{% load static %}
<link href="{% static 'css/style.css' %}" rel="stylesheet"></link>
<h1 class="page-header">INJECTION</h1>

<form action="" method="POST">
<input type="text" name="searchField" id="searchField" placeholder="search trainers..">
<button  type="submit">Find</button>
</form>

<h1> Search Page </h1>
<h3> Injection demo</h3>
<div class="shopping-container">

    <table border="3" cellspacing="0" cellpadding="10">
        <tbody>
           <tr>
              <th>Title</th>
              <th>Description</th>
              <th>Quantity</th>
           </tr>
           <!--{% for search in item %}-->
           <tr>
            <td>{{ search.name}}</td>
            <td>{{ search.description }}</td>
            <td>{{ search.price}}</td>
          </tr>
          <!--{%endfor%}-->
  </tbody>
    </table>
</div>

model.py
app_name = 'injection'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^injection/$', views.search_form, name='search_form'),
]
</code>```

答:
This wouldn't work on PHP either, because you are not using your variable in your SQL string. You are simply using the literal value "searchField".

In order for your code to work you actually need to put the value of the string into your SQL command. In Python there are multiple ways of doing this, one example would be:

```<code>query= "SELECT * FROM injection_search WHERE injection_search.name LIKE '%{}%'".format(searchField)
</code>```

Title: Creating a vulnerable Django search bar

Body:
I want to create a vulnerable search bar and have done everything but unfortunately, the search function doesn't show any result when I press submit.
But terminal shows successful, "POST /injection/ HTTP/1.1" 200 596

views.py
    @csrf_exempt
    def search_form(request):
        if 'searchField' in request.POST:
            query= "SELECT * FROM injection_search WHERE injection_search.name LIKE '%searchField%'"
            print(query)
            item = search.objects.raw(query)

        else:
            item = search.objects.all()
        return render(request, 'home.html', {'item' : item})

template/home.html

{% load static %}
<link href="{% static 'css/style.css' %}" rel="stylesheet"></link>

INJECTION

<form action="" method="POST">
<input type="text" name="searchField" id="searchField" placeholder="search trainers..">
<button  type="submit">Find</button>
</form>

 Search Page

 Injection demo

              Title
              Description
              Quantity

            {{ search.name}}
            {{ search.description }}
            {{ search.price}}

model.py
app_name = 'injection'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^injection/$', views.search_form, name='search_form'),
]

Body:
This wouldn't work on PHP either, because you are not using your variable in your SQL string. You are simply using the literal value "searchField".

In order for your code to work you actually need to put the value of the string into your SQL command. In Python there are multiple ways of doing this, one example would be:

query= "SELECT * FROM injection_search WHERE injection_search.name LIKE '%{}%'".format(searchField)


问:
How to alert getJSON response in jQuery file?
How to check the response of getJSON function call in jQuery file. Which function do I have to edit?</p>

答:
I've to agree with the comments above — your question is more than vague! So I'm now only guessing if that's what you want:

```<code>$.getJSON('ajax/test.json', function(data) {
  alert(JSON.stringify(data));
});
</code>```

You might have to required the JSON library for this to work:
http://www.json.org/js.html

Body:
I've to agree with the comments above — your question is more than vague! So I'm now only guessing if that's what you want:

$.getJSON('ajax/test.json', function(data) {
  alert(JSON.stringify(data));
});

You might have to required the JSON library for this to work:
http://www.json.org/js.html


问:
get only string after matching pattern and exclude everything else
I would like to get string which comes after matching pattern and exclude everything else. For example say,

```<code>Nov 17 21:52:06 web01-san roundcube: <he1v330n> User dxxssjksdfd [121.177.26.200]; \
Message for undisclosed-recipients:, stanpiatt@yahoo.com
Nov 17 21:48:26 web01-san roundcube: <fqu8k29l> User cxcnjdfdssd [121.177.26.200]; \
Message for undisclosed-recipients:, stanpiatt@yahoo.com
</code>```

So I would like to get ONLY string after pattern User and exclude everything else, so output should be

```<code>User dxxssjksdfd
User cxcnjdfdssd
</code>```

I've tried grep -Po 'User\K[^\s]*' but it doesn't give what I want. How can I do that ?

答:
Solution 1st:
Following awk should be helping you in same.

```<code>awk -v RS=" " '/User/{getline;print "User",$0}'   Input_file
</code>```

Output will be as follows.

```<code>User dxxssjksdfd
User cxcnjdfdssd
</code>```

Solution 2nd: You could use following too by going through the fields of line too.

```<code>awk '{for(i=1;i<=NF;i++){if($i ~ /User/){print $i,$(i+1)}}}'   Input_file
</code>```

Solution 3rd: By using sub utility of awk here too.

```<code>awk 'sub(/.*User/,""){print "User",$1}'   Input_file
</code>```

Body:
I would like to get string which comes after matching pattern and exclude everything else. For example say,

Nov 17 21:52:06 web01-san roundcube: <he1v330n> User dxxssjksdfd [121.177.26.200]; \
Message for undisclosed-recipients:, stanpiatt@yahoo.com
Nov 17 21:48:26 web01-san roundcube: <fqu8k29l> User cxcnjdfdssd [121.177.26.200]; \
Message for undisclosed-recipients:, stanpiatt@yahoo.com

So I would like to get ONLY string after pattern User and exclude everything else, so output should be

User dxxssjksdfd
User cxcnjdfdssd

I've tried grep -Po 'User\K[^\s]*' but it doesn't give what I want. How can I do that ?

Body:
Solution 1st:
Following awk should be helping you in same.

awk -v RS=" " '/User/{getline;print "User",$0}'   Input_file

Output will be as follows.

User dxxssjksdfd
User cxcnjdfdssd

Solution 2nd: You could use following too by going through the fields of line too.

awk '{for(i=1;i<=NF;i++){if($i ~ /User/){print $i,$(i+1)}}}'   Input_file

Solution 3rd: By using sub utility of awk here too.

awk 'sub(/.*User/,""){print "User",$1}'   Input_file


答:
Or like this:</p>

```<code>CREATE TABLE temp
(
    ID BIGINT,
    CODE VARCHAR(50),
    ID2 BIGINT,
    DATE DATE
);

INSERT INTO temp VALUES (686151209, 'E13232677', 1333439, '2017-10-23'),
                          (686151209, 'E13232677', 1333439, '2017-10-26');

SELECT generate_series(T.D1::timestamp, T.D2::timestamp, interval '1 day')::date
FROM
(
SELECT A.id, A.code, A.id2,  A.dates AS D1, B.dates  AS D2
FROM temp A
LEFT JOIN temp b ON (A.id = B.id AND
                      A.code=B.code AND
                      A.id2 = B.id2 AND
                      B.dates > A.dates)
WHERE B.id IS NOT NULL
) T;
</code>```

Title: How can I duplicate the result set like below

Body:
I have a table like below and I want to duplicate the records while the min date being less or equal the max date

686151209   E13232677   1333439 2017-10-23
686151209   E13232677   1333439 2017-10-26

I'd like to have the result set like below

686151209   E13232677   1333439 2017-10-23
686151209   E13232677   1333439 2017-10-24
686151209   E13232677   1333439 2017-10-25
86151209    E13232677   1333439 2017-10-26

Body:
Or like this:

CREATE TABLE temp
(
    ID BIGINT,
    CODE VARCHAR(50),
    ID2 BIGINT,
    DATE DATE
);

INSERT INTO temp VALUES (686151209, 'E13232677', 1333439, '2017-10-23'),
                          (686151209, 'E13232677', 1333439, '2017-10-26');

SELECT generate_series(T.D1::timestamp, T.D2::timestamp, interval '1 day')::date
FROM
(
SELECT A.id, A.code, A.id2,  A.dates AS D1, B.dates  AS D2
FROM temp A
LEFT JOIN temp b ON (A.id = B.id AND
                      A.code=B.code AND
                      A.id2 = B.id2 AND
                      B.dates > A.dates)
WHERE B.id IS NOT NULL
) T;


问:
Facebook Graph API - Months of Missing Page Posts from /posts
I've searched high and low for an answer to why this is happening with no luck.

When pulling and paginating results from a page's /posts, MONTHS of posts are missing. Things I have checked:

The user posting on the page has been ruled out. Posts that do show and posts that are missing can be from the same user

Post types seem not to matter. Posts that do show and those that are missing can be of the same post type

I have access to view the missing posts via my app - by querying for any of the missing posts, my app can access the post data, insights, etc

The missing posts are published, and public

The missing posts are only viewable when exporting from the "Export Data" option in the page admin section of the Facebook site.

My query:

```<code>$fb->get('/{PAGEID}/posts?fields=name,created_time,message,parent_id&since={SINCE}&until={UNTIL}&limit=100', '{ACCESS_TOKEN}');
</code>```

Paginating through these results, for example, when querying results between 2017-10-01 and 2017-11-01, returns 2 out of ~30 posts from Oct 27 (and not the first or last posts of that day), with dates later than Oct 27 showing most posts (only a handful missing) and dates before Oct 27 not showing at all.

Using Graph API 2.10.

Any ideas as to why so many posts are missing?

答:
This is a known bug in the Facebook API. I have the same issue. A staff member commented,

I've been informed by the product team that they will not be fixing the existing endpoint since it is working by design, as in it accurately represents what is visible of the pages feed to a user on the UI.

They are working on a new endpoint which will fetch all posts published by the page not subject to the limitations of feed. This is something we will be testing internally very soon.

The bug was reported on 22 September and the comment posted on 26 October. Another staff member commented on a duplicate of the bug on 14 November,

Unfortunately, we do not have an ETA on when the new endpoint will be ready. As a result, the bug was labeled closed to manage developer expectation that the fix won't be ready short-term.

Body:
I've searched high and low for an answer to why this is happening with no luck.

When pulling and paginating results from a page's /posts, MONTHS of posts are missing. Things I have checked:

The user posting on the page has been ruled out. Posts that do show and posts that are missing can be from the same user

Post types seem not to matter. Posts that do show and those that are missing can be of the same post type

I have access to view the missing posts via my app - by querying for any of the missing posts, my app can access the post data, insights, etc

The missing posts are published, and public

The missing posts are only viewable when exporting from the "Export Data" option in the page admin section of the Facebook site.

My query:

$fb->get('/{PAGEID}/posts?fields=name,created_time,message,parent_id&since={SINCE}&until={UNTIL}&limit=100', '{ACCESS_TOKEN}');

Paginating through these results, for example, when querying results between 2017-10-01 and 2017-11-01, returns 2 out of ~30 posts from Oct 27 (and not the first or last posts of that day), with dates later than Oct 27 showing most posts (only a handful missing) and dates before Oct 27 not showing at all.

Using Graph API 2.10.

Any ideas as to why so many posts are missing?


问:
Android Fragment onAttach() deprecated
I have updated my app to use the latest support library (version 23.0.0), I've found out that they deprecated the onAttach() function of the Fragment class.

Instead of:

```<code>onAttach (Activity activity)
</code>```

It's now:

```<code>onAttach (Context context)
</code>```

As my app uses the activity passed before deprecation, a possible solution i think is:

```<code>@Override
public void onAttach(Context context) {
    super.onAttach(context);
    activity = getActivity();
}
</code>```

Would that be the correct way to do it?

UPDATE:

If i run a device with API lower than 23, the new onAttach() is not even being called. I hope that this is not what they intended to do!

UPDATE 2:

Issue has been resolved with the latest updates to the SDK.

I have tested on my API 22 device and onAttach(Context) is being called.

Click here to follow the bug report I've opened a couple of weeks ago and the answers from the guys at Google.

答:
Although it seems that in most cases it's enough to have onAttach(Context), there are some phones (i.e: Xiaomi Redme Note 2) where it's not being called, thus it causes NullPointerExceptions. So to be on the safe side I suggest to leave the deprecated method as well:

```<code>// onAttach(Activity) is necessary in some Xiaomi phones
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    _onAttach(activity);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    _onAttach(context);
}

private void _onAttach(Context context) {
    // do your real stuff here
}
</code>```

Title: Android Fragment onAttach() deprecated

Body:
I have updated my app to use the latest support library (version 23.0.0), I've found out that they deprecated the onAttach() function of the Fragment class.

Instead of:

onAttach (Activity activity)

It's now:

onAttach (Context context)

As my app uses the activity passed before deprecation, a possible solution i think is:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    activity = getActivity();
}

Would that be the correct way to do it?

UPDATE:

If i run a device with API lower than 23, the new onAttach() is not even being called. I hope that this is not what they intended to do!

UPDATE 2:

Issue has been resolved with the latest updates to the SDK.

I have tested on my API 22 device and onAttach(Context) is being called.

Click here to follow the bug report I've opened a couple of weeks ago and the answers from the guys at Google.

Body:
Although it seems that in most cases it's enough to have onAttach(Context), there are some phones (i.e: Xiaomi Redme Note 2) where it's not being called, thus it causes NullPointerExceptions. So to be on the safe side I suggest to leave the deprecated method as well:

// onAttach(Activity) is necessary in some Xiaomi phones
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    _onAttach(activity);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    _onAttach(context);
}

private void _onAttach(Context context) {
    // do your real stuff here
}


问:
How do I write a for loop in C
Why does the following code loop 5000 times instead of the 5 times I expect?</p>

```<code>int height = 5;

for (int height; height > 0; height -= 1){
    printf('Something')  }
}
</code>```

答:
This is not what redefining originally was.

Basically, because C have scopes, redefining a variable hides all variables from outer scopes:

```<code>for (int i=0; i<10; i++)
    for (int i=0; i<10; i++) {
        // Code that'll be looped 100 times
        // Code here can't access the outer `i`
    }
</code>```

If you don't redefine it

```<code>for (int i=0; i<10; i++){
    for (; i<10; i++)
        // Code that'll be looped 10 times
    // Code that'll be run only once
}
</code>```

If you define a variable without initializing it:

```<code>for (int h; h>0; h--)
    // Code that'll be looped for unknown times
</code>```

In this code, the initial value of h is indeterminate. It could be 5000 or zero, or even more than 2,000,000,000! Always assign a value to a variable before using it.

Title: How do I write a for loop in C

Body:
Why does the following code loop 5000 times instead of the 5 times I expect?

int height = 5;

for (int height; height > 0; height -= 1){
    printf('Something')  }
}

Body:
This is not what redefining originally was.

Basically, because C have scopes, redefining a variable hides all variables from outer scopes:

for (int i=0; i<10; i++)
    for (int i=0; i<10; i++) {
        // Code that'll be looped 100 times
        // Code here can't access the outer `i`
    }

If you don't redefine it

for (int i=0; i<10; i++){
    for (; i<10; i++)
        // Code that'll be looped 10 times
    // Code that'll be run only once
}

If you define a variable without initializing it:

for (int h; h>0; h--)
    // Code that'll be looped for unknown times

In this code, the initial value of h is indeterminate. It could be 5000 or zero, or even more than 2,000,000,000! Always assign a value to a variable before using it.


问:
How to prevent access to all but ONE file with htaccess
I'm trying to prevent access to all files but ONE using .htaccess, in this way but it does not work.

```<code><Files accessibleFile.php>
allow from all
</Files>

<Filesmatch "^((?!accessibleFile\.php).)*$">
AuthUserFile .htpasswd
AuthGroupFile /dev/null
AuthName "Restricted Access"
AuthType Basic
</Filesmatch>

<Limit GET POST>
require valid-user
</Limit>
</code>```

Any one can help?
Added: I still want to have logged access to the other files.

答: Put the file in a seperate folder and secure this folder using .htaccess and .htpasswd</p>

Body:
I'm trying to prevent access to all files but ONE using .htaccess, in this way but it does not work.

<Files accessibleFile.php>
allow from all
</Files>

<Filesmatch "^((?!accessibleFile\.php).)*$">
AuthUserFile .htpasswd
AuthGroupFile /dev/null
AuthName "Restricted Access"
AuthType Basic
</Filesmatch>

<Limit GET POST>
require valid-user
</Limit>

Any one can help?
Added: I still want to have logged access to the other files.


问:
how to get value from textbox using typescript in angular 2
I am a beginner to angular2 / typescript I'm trying get numbers from two textboxes and adding both numbers and display the result using interpolation </p>

```<code>@Component({
selector: 'my-app',
template:
`<h1>Hello {{name}}</h1>
<h1>{{D}}</h1>
 <form>
  <p>first number:<input type="text" id="num1"></p>
  <p>second number:<input type ="text1" id="num2"></p>
  <h1> {{result}}</h1>
  </form>
   <test-app></test-app>`
  })

  export class AppComponent
  {
 name = 'Angular';
 value : number;value1 : number;result:number;
  constructor(value : number,value1 : number,result:number)
  {

  this.value = parseFloat
  ((document.getElementById("text") as HTMLInputElement).value);
  this.value1 = parseFloat((document.getElementById("text1")
  as HTMLInputElement).value);
  this.result=this.value+this.value1;
  }}
</code>```

答:
if you get without using ngModel:</p>

```<code>var   num1= ((document.getElementById("num1") as HTMLInputElement).value);
var   num2= ((document.getElementById("num2") as HTMLInputElement).value);
var result=parseInt(num1)+parseInt(num2);
console.log(result);
</code>```

Body:
I am a beginner to angular2 / typescript I'm trying get numbers from two textboxes and adding both numbers and display the result using interpolation

@Component({
selector: 'my-app',
template:
`
Hello {{name}}

{{D}}

 <form>

first number:<input type="text" id="num1">

second number:<input type ="text1" id="num2">

 {{result}}

  </form>
   <test-app></test-app>`
  })

  export class AppComponent
  {
 name = 'Angular';
 value : number;value1 : number;result:number;
  constructor(value : number,value1 : number,result:number)
  {

  this.value = parseFloat
  ((document.getElementById("text") as HTMLInputElement).value);
  this.value1 = parseFloat((document.getElementById("text1")
  as HTMLInputElement).value);
  this.result=this.value+this.value1;
  }}

Body:
if you get without using ngModel:

var   num1= ((document.getElementById("num1") as HTMLInputElement).value);
var   num2= ((document.getElementById("num2") as HTMLInputElement).value);
var result=parseInt(num1)+parseInt(num2);
console.log(result);


问:
Getting Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME error in my HTML5 application
I am working on HTML5 application with Trigger IO framework.I tested it on iPhone and it is working well there.But problem is with the Android. I am getting following error when I debug the application.

```<code>Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME
</code>```

this is for every resource file referenced from the html header. My header code is :

```<code> <script src="js/jquery-1.11.1.min.js"></script>
 <script src="js/index.js"></script>
</code>```

both files are present on the location and working well on iOS. But problem is with Android/Chrome. Any workaround ?

EDIT

Following is the header of the index.html :

```<code>      <head>
        <title>My App</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
'self'; img-src https://*; child-src 'none';">
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/slick.css" />
        <link rel="stylesheet" type="text/css" href="js/slick-theme.css"/>
        <link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
        <link rel="stylesheet" href="css/jquery.mobile.structure-1.4.5.min.css" />
        <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
        <script type="text/javascript" src="js/jquery.mobile-1.4.5.min.js"></script>
        <script type="text/javascript" src="js/jquery-migrate-1.2.1.min"></script>
        <script type="text/javascript" src="js/index.js"></script>
        <script type="text/javascript" src="js/network.js"></script>
        <script type="text/javascript" src="js/jquery.validate.min.js"></script>
        <script type="text/javascript" src="js/slick.min.js"></script>
     </head>
</code>```

Note : If I remove jquery.mobile-1.4.5.min.js file then it is taking reference of index.js

答:
It could be a regression of:

https://github.com/jquery/jquery-mobile/issues/6746

You can use the httpd module as a workaround for this and similar bugs in other libraries:

https://trigger.io/modules/httpd/current/docs/index.html

Body:
I am working on HTML5 application with Trigger IO framework.I tested it on iPhone and it is working well there.But problem is with the Android. I am getting following error when I debug the application.

Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME

this is for every resource file referenced from the html header. My header code is :

both files are present on the location and working well on iOS. But problem is with Android/Chrome. Any workaround ?

EDIT

Following is the header of the index.html :

        <title>My App</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
'self'; img-src https://*; child-src 'none';">
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/slick.css" />
        <link rel="stylesheet" type="text/css" href="js/slick-theme.css"/>
        <link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
        <link rel="stylesheet" href="css/jquery.mobile.structure-1.4.5.min.css" />

Note : If I remove jquery.mobile-1.4.5.min.js file then it is taking reference of index.js


问:
How to pass variable as property name to access value of other object in angular 2 interpolation operator?
I want to pass variable as property of other object and access the value of that property in angular 2 interpolation operator.

I have two objects as below:

```<code>obj1 = { "abc":"123", "xyz":"456", "pqr":"789"}
obj2 = { "123":"name1", "456":"name2", "789":"name3"}
</code>```

And I want to display name1, name2 and name3 based on obj1 property names so I tried below solution but value is not getting displayed in HTML.

```<code>{{obj2["'+obj1.abc+'"]}}
</code>```

How can I achieve this?

答:
You don't need to make a string. The expression in the [] will be evaluated and use it's value as a property name.

```<code>{{ obj2[obj1.abc] }}
</code>```

Example

const obj1 = { "abc":"123", "xyz":"456", "pqr":"789"};
const obj2 = { "123":"name1", "456":"name2", "789":"name3"};

console.log( obj2[obj1.abc] );```

Body:
I want to pass variable as property of other object and access the value of that property in angular 2 interpolation operator.

I have two objects as below:

obj1 = { "abc":"123", "xyz":"456", "pqr":"789"}
obj2 = { "123":"name1", "456":"name2", "789":"name3"}

And I want to display name1, name2 and name3 based on obj1 property names so I tried below solution but value is not getting displayed in HTML.

{{obj2["'+obj1.abc+'"]}}

How can I achieve this?

Body:
You don't need to make a string. The expression in the [] will be evaluated and use it's value as a property name.

{{ obj2[obj1.abc] }}

Example

const obj1 = { "abc":"123", "xyz":"456", "pqr":"789"};
const obj2 = { "123":"name1", "456":"name2", "789":"name3"};

console.log( obj2[obj1.abc] );


问:
wpf dynamically add items to stackpanel with scrollbar
I am trying to create two columns of controls.  Let's say first column has 20 labels or buttons that user can interact with and second column has about 80 labels/buttons.   I'd like scrollbar as well.

when I add scrollview, my first column disappears.  How can I add scrollbar?

```<code>            InitializeComponent();
        Populate();
    }

    protected void Populate()
    {
        for (int i = 0; i <= (int) 20; i++)
        {
            Button l = new Button();
            l.Content = i;
            StyleSP.Children.Add(l);
        }

        for (int i = 100; i < 170; i++)
        {
            Button l = new Button();
            l.Content = i;
            IndustrySP.Children.Add(l);
        }
    }
</code>```

WPF

```<code><UserControl x:Class="Factor.Control.FactorList"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="700" d:DesignWidth="300" >
<Grid Height="300">

    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ScrollViewer>
    <StackPanel Name="StyleSP" Background="Chocolate"  Grid.Column ="0" Height="300">

        </StackPanel>
        </ScrollViewer>
    <ScrollViewer>
        <StackPanel  Name="IndustrySP" Background="AliceBlue" Grid.Column="1" Height="300">

        </StackPanel>
    </ScrollViewer>
</Grid>
</code>```

答:
```<code>    <StackPanel Name="StyleSP"
                Background="Chocolate"
                Grid.Column ="0"
                Height="300"
                ScrollViewer.CanContentScroll="True"
                ScrollViewer.HorizontalScrollBarVisibility="Auto"
                ScrollViewer.VerticalScrollBarVisibility="Auto">

    </StackPanel>
    <StackPanel Name="IndustrySP"
                Background="AliceBlue"
                Grid.Column ="1"
                Height="300"
                ScrollViewer.CanContentScroll="True"
                ScrollViewer.HorizontalScrollBarVisibility="Auto"
                ScrollViewer.VerticalScrollBarVisibility="Auto">

    </StackPanel>
</code>```

Body:
I am trying to create two columns of controls.  Let's say first column has 20 labels or buttons that user can interact with and second column has about 80 labels/buttons.   I'd like scrollbar as well.

when I add scrollview, my first column disappears.  How can I add scrollbar?

            InitializeComponent();
        Populate();
    }

    protected void Populate()
    {
        for (int i = 0; i <= (int) 20; i++)
        {
            Button l = new Button();
            l.Content = i;
            StyleSP.Children.Add(l);
        }

        for (int i = 100; i < 170; i++)
        {
            Button l = new Button();
            l.Content = i;
            IndustrySP.Children.Add(l);
        }
    }

WPF

<UserControl x:Class="Factor.Control.FactorList"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="700" d:DesignWidth="300" >
<Grid Height="300">

    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ScrollViewer>
    <StackPanel Name="StyleSP" Background="Chocolate"  Grid.Column ="0" Height="300">

        </StackPanel>
        </ScrollViewer>
    <ScrollViewer>
        <StackPanel  Name="IndustrySP" Background="AliceBlue" Grid.Column="1" Height="300">

        </StackPanel>
    </ScrollViewer>
</Grid>


问:
Error during testing in rails
I am trying to run a unit test.

The test needs to have require_relative 'francis'

```<code>require 'minitest/autorun'
require_relative 'francis'

class FrancisTest < MiniTest::Test
</code>```

When I try running rake test TEST=test/francis_test.rb I get an error of

```<code>(in C:/Users/chris2/Documents/RailsProjects/francis)
rake aborted!
LoadError: cannot load such file -- C:/Users/chris2/Documents/RailsProjects/francis/test/francis
C:/Users/chris2/Documents/RailsProjects/francis/test/francis_test.rb:2:in `require_relative'
C:/Users/chris2/Documents/RailsProjects/francis/test/francis_test.rb:2:in `<top (required)>'
Tasks: TOP => test:single
(See full trace by running task with --trace)
</code>```

How can I run this test?

Update

I moved francis_test.rb to the root of the project. I also remarked out the require_relative statement., I also had to change the setup line to @teen = ::Franci.new instead of Francis.new

So the beginning of francis_test looks like

```<code>require 'minitest/autorun'
# require_relative 'franci'
require 'test_helper'

class FrancisTest < MiniTest::Test
  attr_reader :teen

  def setup
    @teen = ::Franci.new
  end

  def test_stating
    assert_equal 'Whatevs.', teen.yo('Oh blah di, oh blah da.')
  end

  def test_yelling
    assert_equal 'Chill!', teen.yo('GOOOAAAALLL!')
  end
</code>```

I seem to need require 'test_helper'.

BTW - my ruby and rails versions are

```<code>Rails 4.2.5.1
ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]
</code>```

Now if I run rake test TEST=francis_test.rb -v

I see  (partial)

```<code># Running:

FrancisTest#test_stating_with_acronyms = 0.01 s = E
FrancisTest#test_inquiring = 0.00 s = E
FrancisTest#test_question_with_just_numbers = 0.00 s = E
. . .

Finished in 0.013518s, 1257.5400 runs/s, 0.0000 assertions/s.

  1) Error:
FrancisTest#test_stating_with_acronyms:
ArgumentError: wrong number of arguments (1 for 0)

  2) Error:
FrancisTest#test_inquiring:
ArgumentError: wrong number of arguments (1 for 0)
</code>```

A couple of questions

is attr_reader valid in Ruby 2.2.4? I looked at the API but couldn't quite make sense of it.

Why am I getting 'wrong number of arguments'? I haven't used the attr_reader but it seems that when calling it the way I am, it should be passing the argument to teen.yo.

BTW - the francis table only has one column - 'yo'.

答:
is attr_reader valid in Ruby 2.2.4? I looked at the API but couldn't
  quite make sense of it.

Yes, it is. However you don't need it because columns are automatically made available as attributes by ActiveRecord.

Why am I getting 'wrong number of arguments'? I haven't used the
  attr_reader but it seems that when calling it the way I am, it should
  be passing the argument to teen.yo.

To answer this question, I need the content of your francis.rb file.

Title: Error during testing in rails

Body:
I am trying to run a unit test.

The test needs to have require_relative 'francis'

require 'minitest/autorun'
require_relative 'francis'

class FrancisTest < MiniTest::Test

When I try running rake test TEST=test/francis_test.rb I get an error of

(in C:/Users/chris2/Documents/RailsProjects/francis)
rake aborted!
LoadError: cannot load such file -- C:/Users/chris2/Documents/RailsProjects/francis/test/francis
C:/Users/chris2/Documents/RailsProjects/francis/test/francis_test.rb:2:in `require_relative'
C:/Users/chris2/Documents/RailsProjects/francis/test/francis_test.rb:2:in `<top (required)>'
Tasks: TOP => test:single
(See full trace by running task with --trace)

How can I run this test?

Update

I moved francis_test.rb to the root of the project. I also remarked out the require_relative statement., I also had to change the setup line to @teen = ::Franci.new instead of Francis.new

So the beginning of francis_test looks like

require 'minitest/autorun'
# require_relative 'franci'
require 'test_helper'

class FrancisTest < MiniTest::Test
  attr_reader :teen

  def setup
    @teen = ::Franci.new
  end

  def test_stating
    assert_equal 'Whatevs.', teen.yo('Oh blah di, oh blah da.')
  end

  def test_yelling
    assert_equal 'Chill!', teen.yo('GOOOAAAALLL!')
  end

I seem to need require 'test_helper'.

BTW - my ruby and rails versions are

Rails 4.2.5.1
ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]

Now if I run rake test TEST=francis_test.rb -v

I see  (partial)

# Running:

FrancisTest#test_stating_with_acronyms = 0.01 s = E
FrancisTest#test_inquiring = 0.00 s = E
FrancisTest#test_question_with_just_numbers = 0.00 s = E
. . .

Finished in 0.013518s, 1257.5400 runs/s, 0.0000 assertions/s.

  1) Error:
FrancisTest#test_stating_with_acronyms:
ArgumentError: wrong number of arguments (1 for 0)

  2) Error:
FrancisTest#test_inquiring:
ArgumentError: wrong number of arguments (1 for 0)

A couple of questions

is attr_reader valid in Ruby 2.2.4? I looked at the API but couldn't quite make sense of it.

Why am I getting 'wrong number of arguments'? I haven't used the attr_reader but it seems that when calling it the way I am, it should be passing the argument to teen.yo.

BTW - the francis table only has one column - 'yo'.


问:
Why is the counter decrementing correctly but the countdown is not?
Here is my angular code to define a countdown timer for my website:

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter--;
    var distance = $scope.counter;
    $scope.countdown = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor(((distance % (1000 * 60)) / 1000)) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!-- added for a working snippet -->

<!doctype html>
<html ng-app>

<head>
  <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
  <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>

<body>
  <div ng-controller="AlbumCtrl">
    {{counter}} {{countdown}}
  </div>
</body>

</html></code>```

The 'counter' appears to decrement correctly on my page but the 'countdown' stays fixed and shows the correct value only on page load or refresh. For example, I get the following output as time passes:

```<code>    1115148833 12d 21h 45m 48s
    1115148745 12d 21h 45m 48s
    1115148693 12d 21h 45m 48s
</code>```

What exactly is going wrong? Thanks for your help.

答:
https://github.com/johnpapa/angular-styleguide/tree/master/a1

// Declare a "main" module for the single page application
// second argument to module is an array of dependencies your module
// uses (examples: ui-router ui-bootstrap etc., 'ng' module is assumed as a dependency)
angular.module('myApp', [])

//Defining a service on the module allows you to encapsulate some functionality
//Injecting the angular $timeout service from the 'ng' module and defining
//a new service.  This object gets initialized the first time it's
//referenced and stays alive until the application/page is refreshed.
.service("CountdownService", function($timeout){
  //Define an object to attach properties and functions to and return for
  //use elsewhere in the app
  var countdownService = {};

  //Basically the functional code you had already adjusted the
  //seconds to just use %60 since some sort of issue with the existing math
  // %60 should give remainder after dividing by 60 and appears the "distance"
  // was moving at 1 second per second not 1000, so removed the 1000 factors
  countdownService.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  countdownService.onTimeout = function() {
    countdownService.counter--;
    var distance = countdownService.counter;

    var newValue = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor((distance % (60)) ) + "s ";
    countdownService.countdown = newValue;

      console.log(Math.floor((distance % (60))) + "s ");
    if (countdownService.counter > 0) {
      mytimeout = $timeout(countdownService.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout(countdownService.onTimeout, 1000);
  return countdownService;
})

//Now the controller just has the new service injected it uses "this"
//instead of scope in the ng-controller we use "controllerAs" syntax
//so we don't need to use the scope (angular 2 hides the scope so good
//to just get used to not using it)
.controller("TestCtrl", function(CountdownService){
  this.CountdownService = CountdownService;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html ng-app="myApp">

<head>
</head>

<body>
  <div ng-controller="TestCtrl as testCtrl">
    {{testCtrl.CountdownService.counter}} {{testCtrl.CountdownService.countdown}}
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script> <!-- added for a working snippet -->
</body>

</html></code>```

Body:
Here is my angular code to define a countdown timer for my website:

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter--;
    var distance = $scope.counter;
    $scope.countdown = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor(((distance % (1000 * 60)) / 1000)) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}

<!doctype html>

    {{counter}} {{countdown}}

The 'counter' appears to decrement correctly on my page but the 'countdown' stays fixed and shows the correct value only on page load or refresh. For example, I get the following output as time passes:

    1115148833 12d 21h 45m 48s
    1115148745 12d 21h 45m 48s
    1115148693 12d 21h 45m 48s

What exactly is going wrong? Thanks for your help.

Body:
https://github.com/johnpapa/angular-styleguide/tree/master/a1

// Declare a "main" module for the single page application
// second argument to module is an array of dependencies your module
// uses (examples: ui-router ui-bootstrap etc., 'ng' module is assumed as a dependency)
angular.module('myApp', [])

//Defining a service on the module allows you to encapsulate some functionality
//Injecting the angular $timeout service from the 'ng' module and defining
//a new service.  This object gets initialized the first time it's
//referenced and stays alive until the application/page is refreshed.
.service("CountdownService", function($timeout){
  //Define an object to attach properties and functions to and return for
  //use elsewhere in the app
  var countdownService = {};

  //Basically the functional code you had already adjusted the
  //seconds to just use %60 since some sort of issue with the existing math
  // %60 should give remainder after dividing by 60 and appears the "distance"
  // was moving at 1 second per second not 1000, so removed the 1000 factors
  countdownService.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  countdownService.onTimeout = function() {
    countdownService.counter--;
    var distance = countdownService.counter;

    var newValue = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor((distance % (60)) ) + "s ";
    countdownService.countdown = newValue;

      console.log(Math.floor((distance % (60))) + "s ");
    if (countdownService.counter > 0) {
      mytimeout = $timeout(countdownService.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout(countdownService.onTimeout, 1000);
  return countdownService;
})

//Now the controller just has the new service injected it uses "this"
//instead of scope in the ng-controller we use "controllerAs" syntax
//so we don't need to use the scope (angular 2 hides the scope so good
//to just get used to not using it)
.controller("TestCtrl", function(CountdownService){
  this.CountdownService = CountdownService;
});

<!doctype html>
<html ng-app="myApp">

<head>
</head>

<body>
  <div ng-controller="TestCtrl as testCtrl">
    {{testCtrl.CountdownService.counter}} {{testCtrl.CountdownService.countdown}}
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script> <!-- added for a working snippet -->
</body>

</html>


问:
unexpected response code 401 for URL
```<code>package com.example.murarilal.volley;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="API_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);
            }
        });
    }

    public void home()
    {
        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {
                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);
                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
}

package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);
    }
}
</code>```

https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e

I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity

this the log error

11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
  14350-14350/com.example.murarilal.volley W/System.err:     at
  com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
  11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err:     at
  com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)

答:
public class MainActivity extends AppCompatActivity {

    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

               /* Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);*/
            }
        });
    }

    public void home()
    {
        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {
                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        Log.d("title ", String.valueOf(array.getJSONObject(i).get("title")));
                        Log.d("urlToImage ", String.valueOf(array.getJSONObject(i).get("urlToImage")));
                        heroList.add(hero);
                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
}```

Title: unexpected response code 401 for URL

Body:
package com.example.murarilal.volley;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="API_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);
            }
        });
    }

    public void home()
    {
        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {
                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);
                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
}

package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);
    }
}

https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e

I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity

this the log error

11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
  14350-14350/com.example.murarilal.volley W/System.err:     at
  com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
  11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err:     at
  com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)