问:
What are the possible kinds of webhooks Trello can send? What attributes come in each?
I'm developing an app that is tightly integrated with Trello and uses Trello webhooks for a lot of things. However, I can't find anywhere in Trello's developer documentation what are the "actions" that may trigger a webhook and what data will come in each of these.

In fact, in my experience, the data that comes with each webhook is kinda random. For example, while most webhooks contain the shortLink of the card which is being the target of some action, some do not, in a totally unpredictable way. Also, creating cards from checklists doesn't seem to trigger the same webhook that is triggered when a card is created normally, and so on.

So, is that documented somewhere?

答:
based on @flatjaf's repo, I gathered and summarized all* the webhooks types.

```<code>addAttachmentToCard
addChecklistToCard
addLabelToCard
addMemberToBoard
addMemberToCard
commentCard
convertToCardFromCheckItem
copyCard
createCard
createCheckItem
createLabel
createList
deleteAttachmentFromCard
deleteCard
deleteCheckItem
deleteComment
deleteLabel
emailCard
moveCardFromBoard
moveCardToBoard
moveListFromBoard
moveListToBoard
removeChecklistFromCard
removeLabelFromCard
removeMemberFromBoard
removeMemberFromCard
updateBoard
updateCard
updateCheckItem
updateCheckItemStateOnCard
updateChecklist
updateComment
updateLabel
updateList
</code>```

hope it helps!

*I don't know if that list includes all the available webhooks types because as i already said, it's based on flatjaf's repo created 2 years ago

Body:
based on @flatjaf's repo, I gathered and summarized all* the webhooks types.

addAttachmentToCard
addChecklistToCard
addLabelToCard
addMemberToBoard
addMemberToCard
commentCard
convertToCardFromCheckItem
copyCard
createCard
createCheckItem
createLabel
createList
deleteAttachmentFromCard
deleteCard
deleteCheckItem
deleteComment
deleteLabel
emailCard
moveCardFromBoard
moveCardToBoard
moveListFromBoard
moveListToBoard
removeChecklistFromCard
removeLabelFromCard
removeMemberFromBoard
removeMemberFromCard
updateBoard
updateCard
updateCheckItem
updateCheckItemStateOnCard
updateChecklist
updateComment
updateLabel
updateList

hope it helps!

*I don't know if that list includes all the available webhooks types because as i already said, it's based on flatjaf's repo created 2 years ago


来源: stackexchange

问:
How to create a BizTalk Application btaproj
I am using BizTalk 2016 and I want to enable build from VSTS.

Build fails because it asks for some *.json files.

After some investigation I reached the conclusion that I have to create
a btaproj file. Add a BizTalk Server application to Visual Studio Team Services

I installed Feature Pack 1 but there is no option for BizTalk Application project.

How can I create a btaproj file?

答:
I used the steps described in usman-shaheen post

Then I had an error during building. In project's properties, under Build Events -> Post-build events there were some commands, probable written by VS. These commands were causing an error during building. If I was starting VS as admin, they were not causing any error and building was finished correctly. By removing these commands, agent could run and build my app.

ContentLicense: CC BY-SA 3.0


问:
Java polymorphism: finding the right design pattern
Disclaimer: I know there are a lot of questions about polymorphism out there, but I couldn't find a suitable answer for my problem. If your Google-fu is better than mine, please forgive the dupe.

I have a model using inheritance, such as in the example below.

```<code>public abstract class Base {
// ...
}

public class ConcreteA extends Base {
    private String someString;
// ...
}

public class ConcreteB extends Base {
    private boolean someBool;
// ...
}
</code>```

And I also have a List<Base>, which is composed of objects that are either ConcreteAs or ConcreteBs.

I need to generate a graphical view for each object in the list, but the resulting element is not the same for ConcreteAs and ConcreteBs. From the example above, the view for ConcreteA would be a text field, while the view for a ConcreteB would be a check box.

How can I achieve this using OO principles?

答:
In such cases, I usually use generics something like this

```<code>public abstract  class Base <T extends  Shape>{
public abstract T drawShape();
</code>```

}

```<code>public class ConcreatA extends Base<Circle> {
@Override
public Circle drawShape() {
    return null;
}
</code>```

}

```<code>public class ConcreatB extends Base<Square> {
@Override
public Square drawShape() {
    return null;
}
</code>```

}

So now you can use list of Shapes

Body:
Disclaimer: I know there are a lot of questions about polymorphism out there, but I couldn't find a suitable answer for my problem. If your Google-fu is better than mine, please forgive the dupe.

I have a model using inheritance, such as in the example below.

public abstract class Base {
// ...
}

public class ConcreteA extends Base {
    private String someString;
// ...
}

public class ConcreteB extends Base {
    private boolean someBool;
// ...
}

And I also have a List<Base>, which is composed of objects that are either ConcreteAs or ConcreteBs.

I need to generate a graphical view for each object in the list, but the resulting element is not the same for ConcreteAs and ConcreteBs. From the example above, the view for ConcreteA would be a text field, while the view for a ConcreteB would be a check box.

How can I achieve this using OO principles?

Body:
In such cases, I usually use generics something like this

public abstract  class Base <T extends  Shape>{
public abstract T drawShape();

}

public class ConcreatA extends Base<Circle> {
@Override
public Circle drawShape() {
    return null;
}

}

public class ConcreatB extends Base<Square> {
@Override
public Square drawShape() {
    return null;
}

}

So now you can use list of Shapes


问:
How to get a text from SearchView?
I need to get a text from SearchView and compare it to strings in my activity's ListView and show a Toast if the word in a SearchView is in my ListView. How do I do that? Here's my working code for the SearchView:

```<code>MenuItem ourSearchItem = menu.findItem(R.id.menu_item_search);

SearchView sv = (SearchView) ourSearchItem.getActionView();

sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        adapter.getFilter().filter(newText);

        return false;
    }
});
</code>```

答:
try this code :</p>

```<code>    MenuItem ourSearchItem = menu.findItem(R.id.menu_item_search);

    SearchView sv = (SearchView) ourSearchItem.getActionView();

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Toast.makeText(getContext(), query, Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            adapter.getFilter().filter(newText);
            }
            return false;
        }
    });
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get a text from SearchView?

Body:
I need to get a text from SearchView and compare it to strings in my activity's ListView and show a Toast if the word in a SearchView is in my ListView. How do I do that? Here's my working code for the SearchView:

MenuItem ourSearchItem = menu.findItem(R.id.menu_item_search);

SearchView sv = (SearchView) ourSearchItem.getActionView();

sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        adapter.getFilter().filter(newText);

        return false;
    }
});

Body:
try this code :

    MenuItem ourSearchItem = menu.findItem(R.id.menu_item_search);

    SearchView sv = (SearchView) ourSearchItem.getActionView();

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Toast.makeText(getContext(), query, Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            adapter.getFilter().filter(newText);
            }
            return false;
        }
    });


问:
How to rebind tinyMCE editor to a moved dom element?
I list the tinyMCE plugin under a structure like so:

```
Email-Workspace
 module-container
  email-contact-ui
   inner-container
    email-body-section
    email-editor
     mceu_12
      mceu_12-body
```

A user event shifts the module-container element to another location

```
New-Workspace
module-container
 email-contact-ui
  inner-container
   email-body-section
    email-editor
```

However under the email-editor tinyMCE no longer appears to be bound to that new DOM location.

```
What I see:
* tinyMCE.editors.length --> 1
* tinyMCE.editors[0].getBody() --> shows correct body text

I've tried:
* destroying editor and reinit,
* I've tried this with .destroy, remove, tinyMCE.EditorManager.execCommand 'mceRemoveEditor' and 'mceAddEditor', true.
```

None of these seem to rebind to that existing DOM element?

Any other ideas to try?

答: In the end, I solved this by writing a destroyEditor function, which set the editor to null and that allowed me to rebind it in the new location. Then it was a matter of setting the rebind to the last possible event, to ensure all the DOM was in place and any changes are made. Also need to check for making too many editors. I did try many of the suggestions I found online, but none of those seemed to work for my situation. </p>

Body:
I list the tinyMCE plugin under a structure like so:

Email-Workspace
 module-container
  email-contact-ui
   inner-container
    email-body-section
    email-editor
     mceu_12
      mceu_12-body

A user event shifts the module-container element to another location

New-Workspace
module-container
 email-contact-ui
  inner-container
   email-body-section
    email-editor

However under the email-editor tinyMCE no longer appears to be bound to that new DOM location.

What I see:
* tinyMCE.editors.length --> 1
* tinyMCE.editors[0].getBody() --> shows correct body text

I've tried:
* destroying editor and reinit,
* I've tried this with .destroy, remove, tinyMCE.EditorManager.execCommand 'mceRemoveEditor' and 'mceAddEditor', true.

None of these seem to rebind to that existing DOM element?

Any other ideas to try?


答:
Here is how you interpret this error:

In Python, every operator redirects to some special function on the class of your object. In this case, the operator [...] is equivalent to calling __getitem__. It is the same operator for both sequences and dictionaries.

The issue is with m3. You can know this immediately because the previous line does not raise an error for m1 and m2. m3 comes for searching for some attributes of m2 in my_data using the nexus function*.

This would normally be OK, but in some cases a match is not found. The default return value of every Python function that does not have an explicit return statement is None, which is what nexus inevitably returns when a match is not found.

The easiest fix for this would be to return a sequence from nexus even if a match is not found. For example, add return [0, 0] as the last line of your function. Alternatively, you can add a check for a None result in dist2, but then you have to figure out what to return and how to handle it in moving.

*I should probably mention at some point that I have no idea what your code is really doing, but that should not affect the accuracy of my answer.

Title: Python Traceback (most recent call last): TypeError: 'NoneType' object has no attribute '__getitem__'

Body:
My code does have output like this:

0.0
17424.9931038
0.999998852224
0.0
26892.5610797
0.9999992563
0.0
197429.598938
0.999999898698
0.0
206067.715126
0.999999902945
0.0
119901.778166
0.999999833197
0.0
48243.1852781
0.999999585434
0.0
161251.135425
0.99999987597
0.0
460059.512284
0.999999956527
0.0
1616904.64834
0.999999987631
20.0
10048.6928044
0.999998009693
20.0
19783.0112229
0.999998989032
20.0
106444.618031
0.999999812109
20.0
208645.708656
0.999999904144
20.0
85754.2720566
0.999999766775
20.0
35024.1659145
0.999999428966
20.0
162536.879087
0.999999876951
20.0
494504.420369
0.999999959555
20.0
1523905.77844
0.999999986876
40.0
7539.80921955
0.999997347417
40.0
20041.735046
0.999999002083
40.0
58683.4742137
0.999999659189
40.0
234270.969023
0.999999914629
40.0
49306.4157177
0.999999594373
40.0
27876.4404592
0.999999282549
40.0
165300.231338
0.999999879008
40.0
568614.839048
0.999999964827
40.0
1502387.8595
0.999999986688
60.0
4544.45338191
0.99999559904
60.0
21050.154867
0.999999049889
60.0
29282.4962414
0.999999316998
60.0
261564.996448
0.999999923537
60.0
24097.4648119
0.999999170038
...

But then it errors with traceback...

Traceback (most recent call last):
  File "2_moving.py", line 34, in <module>
    print moving(my_data)
  File "2_moving.py", line 29, in moving
    print dist2(k,l)
  File "2_moving.py", line 16, in dist2
    d2 = math.hypot(m1[0]-m3[0],m1[1]-m3[1])
 TypeError: 'NoneType' object has no attribute '__getitem__'

My code is

import numpy as np
import math

my_data = np.loadtxt(open("demo_tindex.csv","rb"),delimiter=",",skiprows=0)
# print my_data

def nexus(m,n):
    for k in n:
        if k[3] == m[3] and k[2] == m[2]+20:
            return k

def dist2(m1,m2):
    m3 = nexus(m2,my_data)
    d1 = math.hypot(m1[0]-m2[0],m1[1]-m2[1])
    d2 = math.hypot(m1[0]-m3[0],m1[1]-m3[1])
    d3 = math.hypot(m2[0]-m3[0],m2[1]-m3[1])
    dist2 = (d1+d2)**2 - d3**2
    return dist2

def moving(p):
    k = p[0][:]
    theta2 = 0.02

    for l in p[1:]:
        if l[2] == k[2]:
            print l[2]
            print dist2(k,l)
            print math.exp(-theta2/dist2(k,l))
        else:
            k = l

print moving(my_data)

this file is csv file in the code
demo_tindex.csv

And this question is to calculate the influence map from dataset


问:
jQuery radio button checked, else statement not working
I want an input to change its styles (add background color) when checked. This is working, however, the else statement to remove the background color when the input radio type isn't checked is not working.

Have tried various different ways but cannot get the else statement to fire when you click a different input.

HTML:

```<code><tr style="color:white;">
<td id="test" style="background-color:rgb(153, 117, 82);" value="1">
<label><input type="radio" name="c0" class="c0" value="10" onclick="output();" id="t"/>1</label>
</td>
</tr>

<tr style="color:white;">
<td style="background-color: rgb(255, 57, 57);">
<label><input type="radio" name="c0" class="c0" value="20" onclick="output();" id="t"/>2</label>
</td>
</code>```

JS:

```<code>$('input#t').on("click", function() {
if ($("input#t").is(':checked')) {
    $(this).parent().addClass("active");
}
    else {
    $(this).parent().removeClass("active");
}
});
</code>```

codepen: https://codepen.io/Not_A_Fax_Machine/pen/zzRMNZ/

答:
The problem is because you have two elements with the same id attribute - they must be unique.

To fix the problem use a class to group the radio buttons, then use the this keyword to reference the element within the change event handler. Try this:

$('.t').on("change", function() {
  $('label').removeClass('active');
  $(this).parent().toggleClass('active', this.checked);
  // output();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tr {
  color: white;
}

td.foo {
  background-color: rgb(153, 117, 82);
}

td.bar {
  background-color: rgb(255, 57, 57);
}

.active {
  background-color: blue;
}</code>```

      <input type="radio" name="c0" class="t c0" value="10" />1

      <input type="radio" name="c0" class="t c0" value="20" />2

```

Note the removal of the inline styles, which should be avoided.

Body:
I want an input to change its styles (add background color) when checked. This is working, however, the else statement to remove the background color when the input radio type isn't checked is not working.

Have tried various different ways but cannot get the else statement to fire when you click a different input.

HTML:

<input type="radio" name="c0" class="c0" value="10" onclick="output();" id="t"/>1

<input type="radio" name="c0" class="c0" value="20" onclick="output();" id="t"/>2

JS:

$('input#t').on("click", function() {
if ($("input#t").is(':checked')) {
    $(this).parent().addClass("active");
}
    else {
    $(this).parent().removeClass("active");
}
});

codepen: https://codepen.io/Not_A_Fax_Machine/pen/zzRMNZ/

Body:
The problem is because you have two elements with the same id attribute - they must be unique.

To fix the problem use a class to group the radio buttons, then use the this keyword to reference the element within the change event handler. Try this:

$('.t').on("change", function() {
  $('label').removeClass('active');
  $(this).parent().toggleClass('active', this.checked);
  // output();
});

tr {
  color: white;
}

td.foo {
  background-color: rgb(153, 117, 82);
}

td.bar {
  background-color: rgb(255, 57, 57);
}

.active {
  background-color: blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="foo">
      <label><input type="radio" name="c0" class="t c0" value="10" />1</label>
    </td>
  </tr>
  <tr>
    <td class="bar">
      <label><input type="radio" name="c0" class="t c0" value="20" />2</label>
    </td>
  </tr>
</table>

Note the removal of the inline styles, which should be avoided.


问:
Remove URL parameters after redisplaying page
I have a page which lets me create and save a record.  When I click Save, I want to stay on the same page, but have that page display an updated view model.  The problem I'm having is that after I save, the GET parameters stay in the page URL.

When I run my application, I go to the "list records" page and click the "create new" button.  That causes a GET request to EditRecord with the createNew parameter set to true.  The request looks like localhost/Home/EditRecord?createNew=True

```<code>public ActionResult EditRecord(string id, bool createNew = false)
{
    MyRecordViewModel viewModel;
    if (createNew)
    {
        viewModel = new MyRecordViewModel
        {
            IsNew = true
        };
    }
    else
    {
        var myRecord = (from p in this.context.MyRecords
                        where p.Id = id
                        select p).FirstOrDefault();
        if (myRecord == null)
        {
            this.ErrorMessage("Cannot find record.");
            return View();
        }
        viewModel = new MyRecordViewModel(myRecord);
    }

    return View(viewModel);
}
</code>```

Then when I click save, it POSTs to this method

```<code>[HttpPost]
public ActionResult EditRecord(MyRecordViewModel viewModel)
{
    // Save record to database
    // ...

    // Update the view model
    viewModel.LastUpdatedDttm = DateTime.Now;

    // Clear the model state dictionary so that my updated view model's values will be shown on the page
    ModelState.Clear();

    // Go back to the same page with an updated view model
    return View(viewModel);
}
</code>```

The updated page is displayed correctly with the updated view model.  The problem is that the URL is still localhost/Home/EditRecord?createNew=True.  I want the URL to be localhost/Home/EditRecord

I don't want to redirect back to the GET page with my record ID and with createNew equal to false, because that'll cause an unnecessary trip to the database in order to redisplay the same record.

答:
```<code>public ActionResult EditRecord(string id, bool createNew = false)
{
    id = id ?? TempData["id"];

    //your code
}

[HttpPost]
public ActionResult EditProductAlias(MyRecordViewModel viewModel)
{
    //your code

    TempData[id] = viewModel.Id;

    return RedirectToAction("EditRecord", "ControllerName")
}
</code>```

But it very bad solution

Body:
I have a page which lets me create and save a record.  When I click Save, I want to stay on the same page, but have that page display an updated view model.  The problem I'm having is that after I save, the GET parameters stay in the page URL.

When I run my application, I go to the "list records" page and click the "create new" button.  That causes a GET request to EditRecord with the createNew parameter set to true.  The request looks like localhost/Home/EditRecord?createNew=True

public ActionResult EditRecord(string id, bool createNew = false)
{
    MyRecordViewModel viewModel;
    if (createNew)
    {
        viewModel = new MyRecordViewModel
        {
            IsNew = true
        };
    }
    else
    {
        var myRecord = (from p in this.context.MyRecords
                        where p.Id = id
                        select p).FirstOrDefault();
        if (myRecord == null)
        {
            this.ErrorMessage("Cannot find record.");
            return View();
        }
        viewModel = new MyRecordViewModel(myRecord);
    }

    return View(viewModel);
}

Then when I click save, it POSTs to this method

[HttpPost]
public ActionResult EditRecord(MyRecordViewModel viewModel)
{
    // Save record to database
    // ...

    // Update the view model
    viewModel.LastUpdatedDttm = DateTime.Now;

    // Clear the model state dictionary so that my updated view model's values will be shown on the page
    ModelState.Clear();

    // Go back to the same page with an updated view model
    return View(viewModel);
}

The updated page is displayed correctly with the updated view model.  The problem is that the URL is still localhost/Home/EditRecord?createNew=True.  I want the URL to be localhost/Home/EditRecord

I don't want to redirect back to the GET page with my record ID and with createNew equal to false, because that'll cause an unnecessary trip to the database in order to redisplay the same record.

Body:
public ActionResult EditRecord(string id, bool createNew = false)
{
    id = id ?? TempData["id"];

    //your code
}

[HttpPost]
public ActionResult EditProductAlias(MyRecordViewModel viewModel)
{
    //your code

    TempData[id] = viewModel.Id;

    return RedirectToAction("EditRecord", "ControllerName")
}

But it very bad solution


问:
Outlook VBA module changes not saved after restart
Good day,
I have a VBA script running as a rule for a few months now, which basically saves some attachments from a specific sender into some folders. Recently, the module had to be edited to add a few lines for a new Folder. The new script worked as expected the day it was implemented. The problem is, the next day, after shutdown, all the changes made were reverted to the previous version. So, it seems I am stuck with that first script made.

How can I edit the script and actually have the changes saved?

PS. We are using MS Server 2012 and Outlook 2013

答:
We saw this happen with roaming profiles.

We noticed that the modify date of the OTM file is not changing in C:\Users\"usename"\AppData\Roaming\Microsoft\Outlook

Therefore, when user logs off and profile synchronizes back to the profile host server, this file does not appear to have changed, and does not get synchronized.  When user logs in next day and downloads fresh copy of profile, they keep getting old OTM file...

Our solution was to write code to manually change the modify date of the OTM file in the VB script.


问:
NullPointerException when i use navigation drawer
i make a navigation drawer in my project , then i wanted to make button for slide left and right but my app stop and block .

i get that error : java.lang.RuntimeException: Unable to start activity ComponentInfo{radiofm.arabelradio/radiofm.arabelradio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

main activity

package radiofm.arabelradio;

```<code>import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar() .setDisplayHomeAsUpEnabled(true);
        getSupportActionBar() .setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

activity_main

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context="radiofm.arabelradio.MainActivity"
                android:background="#e10716"
                android:id="@+id/drawerLayout"

    >

    <android.support.design.widget.NavigationView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    app:menu="@menu/navigation_menu"
                    android:layout_gravity="start"
                >
    </android.support.design.widget.NavigationView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
            <ImageButton
                android:id="@+id/id_play"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:scaleType="fitCenter"
                android:background="#e10716"
                android:layout_marginBottom="84dp"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true" />

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="250dp"
                android:layout_height="100dp"
                android:layout_marginTop="55dp"
                app:srcCompat="@drawable/arabel"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true" />

    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>
</code>```

navigation_menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/na_listening"
        android:title="Listening"></item>

    <item
        android:id="@+id/nav_alarm"
        android:title="Alarm"></item>

    <item
        android:id="@+id/nav_settings"
        android:title="Settings"></item>

    <item
        android:id="@+id/nav_logout"
        android:title="Logout"></item>

</menu>
</code>```

Style

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowNoTitle">true</item>`
    </style>

</resources>
</code>```

答:
Remove the

<item name="android:windowNoTitle">true</item>
 from styles.xml.
and instead use

```<code>  requestWindowFeature(Window.FEATURE_NO_TITLE);
</code>```

instead.

you should call requestWindowFeature before calling setContentView().

Body:
i make a navigation drawer in my project , then i wanted to make button for slide left and right but my app stop and block .

i get that error : java.lang.RuntimeException: Unable to start activity ComponentInfo{radiofm.arabelradio/radiofm.arabelradio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

main activity

package radiofm.arabelradio;

import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar() .setDisplayHomeAsUpEnabled(true);
        getSupportActionBar() .setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context="radiofm.arabelradio.MainActivity"
                android:background="#e10716"
                android:id="@+id/drawerLayout"

    >

    <android.support.design.widget.NavigationView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    app:menu="@menu/navigation_menu"
                    android:layout_gravity="start"
                >
    </android.support.design.widget.NavigationView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
            <ImageButton
                android:id="@+id/id_play"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:scaleType="fitCenter"
                android:background="#e10716"
                android:layout_marginBottom="84dp"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true" />

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="250dp"
                android:layout_height="100dp"
                android:layout_marginTop="55dp"
                app:srcCompat="@drawable/arabel"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true" />

    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>

navigation_menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/na_listening"
        android:title="Listening"></item>

    <item
        android:id="@+id/nav_alarm"
        android:title="Alarm"></item>

    <item
        android:id="@+id/nav_settings"
        android:title="Settings"></item>

    <item
        android:id="@+id/nav_logout"
        android:title="Logout"></item>

</menu>

Style

<resources>

</resources>

Body:
Remove the

<item name="android:windowNoTitle">true</item>
 from styles.xml.
and instead use

  requestWindowFeature(Window.FEATURE_NO_TITLE);

instead.

you should call requestWindowFeature before calling setContentView().


问:
AngularFire / Firebase - checking the authentication state
Note: I'm new to all of this, please excuse what might be obvious. Any help is massively appreciated :)

What I have

An auth service to log in and out

An album service to fetch items based on user id

albumList > UserId > albumKey

In my album list service I query the path 'albumList > userId'

Once I log in, this works perfectly, and only the results based on the matched query of the above are returned

Issues

If I were to copy and paste the URL of 'localhost:4200/albums' into another tab, the console reads

Uncaught (in promise): TypeError: Cannot read property 'uid' of null

As a result, nothing loads and the URL pasted isn't maintained

Questions

Do I need to add a user observable in all my components?

How do I ensure that the user state is checked before loading my data?

Is it possible to just use my Auth.Service as a reference point for all other components?

My Auth Service

import { Injectable } from '@angular/core';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {
  user: Observable<firebase.User>;

  constructor(
    private firebaseAuth: AngularFireAuth,
    private router: Router) {
    this.user = firebaseAuth.authState;
  }

  login(email: string, password: string) {
    this.firebaseAuth
      .auth
      .signInWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Nice, it worked!');
        console.log(this.firebaseAuth.auth.currentUser.uid);

        this.router.navigate(['/albums'])
      })
      .catch(err => {
        console.log('Something went wrong:', err.message);
      });
  }

  logout() {
    this.firebaseAuth
      .auth
      .signOut();
  }

}```
</div>
</div>
</p>

<p><strong>My Album List Service</strong></p>

<p><strong>note:</strong> If i remove the albumList query with the user id on the end (commented out query), I can copy and paste the URL into a new tab and the URL is maintained (url.com/albums). However, any data won't be filtered by the user key first.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ProjectsListService {
  albumList: FirebaseListObservable<any[]>;
  user: Observable<firebase.User>;

  constructor(
    private database: AngularFireDatabase,
    private firebaseAuth: AngularFireAuth) {

    //this.albumList = database.list('/albumList');
    this.albumList = database.list('/albumList/' + this.firebaseAuth.auth.currentUser.uid);
    //console.log(this.firebaseAuth.auth.currentUser.uid);
  }

  getAlbumList() {
    return this.albumList;
    }

}</code>```

答:
Questions

Do I need to add a user observable in all my components?

Yes, you are working with async data all the time, you need to subscribe to the changes coming from the firebase

How do I ensure that the user state is checked before loading my data?

It seems that you are also relatively new to angular, it might be harder for you to learn everything at once. You should check the Router tutorial, more exactly the module 5 Route Guards.

Is it possible to just use my Auth.Service as a reference point for all other components?

Yes, that's entirely up to you and it's a very common thing.

As for the Type error, you are trying to accessing a value that doesn't exist when you initialize your app, since you get that asynchronously you need to subscribe to the authState

```<code>import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ProjectsListService {
  albumList: FirebaseListObservable<any[]>;
  user: Observable<firebase.User>;

  constructor(
    private database: AngularFireDatabase,
    private firebaseAuth: AngularFireAuth
  ) {
      firebaseAuth.authState.subscribe(user => {
        console.log(user);
        if (user) {
          this.albumList = database.list('/albumList/' + user.uid);
        }
      })
  }

  getAlbumList() {
    return this.albumList;
  }
}
</code>```

Edit

The previous code didn't work, because when you first run your app, the albumList is an empty var, that's why after you navigate everything works fine, because after that it's already initialised and you can subscribe to it.

So because you depend on the auth state you should be subscribing to your albumList on your components instead. Why? Because if your user for some reason logs out, you also hide the information.

So instead of using ProjectsListService on your component you will do something like this:

```<code>import { Component } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'

@Component({
  selector: 'your-component',
  template: `<ul><li *ngFor="let album of albumList | async">{{ todo.text }}</li></ul>`
})
export class YOURComponent {
  albumList: FirebaseListObservable<any[]>;

  constructor(
    private fAuth: AngularFireAuth,
    private database: AngularFireDatabase
  ) {
    fAuth.authState.subscribe(user => {
      if (user) {
        this.albumList = database.list('/albumList/' + user.uid);
        return;
      }
      this.albumList = null;
    })
  }
}
</code>```

Body:
Note: I'm new to all of this, please excuse what might be obvious. Any help is massively appreciated :)

What I have

An auth service to log in and out

An album service to fetch items based on user id

albumList > UserId > albumKey

In my album list service I query the path 'albumList > userId'

Once I log in, this works perfectly, and only the results based on the matched query of the above are returned

Issues

If I were to copy and paste the URL of 'localhost:4200/albums' into another tab, the console reads

Uncaught (in promise): TypeError: Cannot read property 'uid' of null

As a result, nothing loads and the URL pasted isn't maintained

Questions

Do I need to add a user observable in all my components?

How do I ensure that the user state is checked before loading my data?

Is it possible to just use my Auth.Service as a reference point for all other components?

My Auth Service

import { Injectable } from '@angular/core';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {
  user: Observable<firebase.User>;

  constructor(
    private firebaseAuth: AngularFireAuth,
    private router: Router) {
    this.user = firebaseAuth.authState;
  }

  login(email: string, password: string) {
    this.firebaseAuth
      .auth
      .signInWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Nice, it worked!');
        console.log(this.firebaseAuth.auth.currentUser.uid);

        this.router.navigate(['/albums'])
      })
      .catch(err => {
        console.log('Something went wrong:', err.message);
      });
  }

  logout() {
    this.firebaseAuth
      .auth
      .signOut();
  }

}

My Album List Service

note: If i remove the albumList query with the user id on the end (commented out query), I can copy and paste the URL into a new tab and the URL is maintained (url.com/albums). However, any data won't be filtered by the user key first.

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ProjectsListService {
  albumList: FirebaseListObservable<any[]>;
  user: Observable<firebase.User>;

  constructor(
    private database: AngularFireDatabase,
    private firebaseAuth: AngularFireAuth) {

    //this.albumList = database.list('/albumList');
    this.albumList = database.list('/albumList/' + this.firebaseAuth.auth.currentUser.uid);
    //console.log(this.firebaseAuth.auth.currentUser.uid);
  }

  getAlbumList() {
    return this.albumList;
    }

}

Body:
Questions

Do I need to add a user observable in all my components?

Yes, you are working with async data all the time, you need to subscribe to the changes coming from the firebase

How do I ensure that the user state is checked before loading my data?

It seems that you are also relatively new to angular, it might be harder for you to learn everything at once. You should check the Router tutorial, more exactly the module 5 Route Guards.

Is it possible to just use my Auth.Service as a reference point for all other components?

Yes, that's entirely up to you and it's a very common thing.

As for the Type error, you are trying to accessing a value that doesn't exist when you initialize your app, since you get that asynchronously you need to subscribe to the authState

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ProjectsListService {
  albumList: FirebaseListObservable<any[]>;
  user: Observable<firebase.User>;

  constructor(
    private database: AngularFireDatabase,
    private firebaseAuth: AngularFireAuth
  ) {
      firebaseAuth.authState.subscribe(user => {
        console.log(user);
        if (user) {
          this.albumList = database.list('/albumList/' + user.uid);
        }
      })
  }

  getAlbumList() {
    return this.albumList;
  }
}

Edit

The previous code didn't work, because when you first run your app, the albumList is an empty var, that's why after you navigate everything works fine, because after that it's already initialised and you can subscribe to it.

So because you depend on the auth state you should be subscribing to your albumList on your components instead. Why? Because if your user for some reason logs out, you also hide the information.

So instead of using ProjectsListService on your component you will do something like this:

import { Component } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'

@Component({
  selector: 'your-component',
  template: `<ul><li *ngFor="let album of albumList | async">{{ todo.text }}</li></ul>`
})
export class YOURComponent {
  albumList: FirebaseListObservable<any[]>;

  constructor(
    private fAuth: AngularFireAuth,
    private database: AngularFireDatabase
  ) {
    fAuth.authState.subscribe(user => {
      if (user) {
        this.albumList = database.list('/albumList/' + user.uid);
        return;
      }
      this.albumList = null;
    })
  }
}


答:
Not a pattern - this is what abstraction is all about. Declare a method you want all subclasses of Base to implement and each must implement it in their own way.

Obviously you would pass parameters and/or get results of the methods.

```<code>public abstract class Base {
    abstract void graphicalView();
}

public class ConcreteA extends Base {
    @Override
    void graphicalView() {

    }
}

public class ConcreteB extends Base {
    @Override
    void graphicalView() {

    }
}

public void test() throws IOException {
    List<Base> bases = new ArrayList<>();
    for ( Base b : bases ) {
        b.graphicalView();
    }
}
</code>```

Title: Java polymorphism: finding the right design pattern

Body:
Not a pattern - this is what abstraction is all about. Declare a method you want all subclasses of Base to implement and each must implement it in their own way.

Obviously you would pass parameters and/or get results of the methods.

public abstract class Base {
    abstract void graphicalView();
}

public class ConcreteA extends Base {
    @Override
    void graphicalView() {

    }
}

public class ConcreteB extends Base {
    @Override
    void graphicalView() {

    }
}

public void test() throws IOException {
    List<Base> bases = new ArrayList<>();
    for ( Base b : bases ) {
        b.graphicalView();
    }
}


问:
C# why cant i exit this while loop?
I'm tryig to make a program that can auto press space.
but i can only enable it. after the program crashes.

so i cant turn it off. pleace help

here is my code:

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

namespace Auto_Abillty
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public bool startFlag = false;
    public bool stopFlag = false;
    private void Preiststop_Click(object sender, EventArgs e)
    {
        stopFlag = true;
    }
    private void Preist_Click(object sender, EventArgs e)
    {
        startFlag = true;
        while (startFlag)
        {
            SendKeys.Send(" ");
            Thread.Sleep(5000);
            if (stopFlag)
                startFlag = false;
        }
    }

}
}
</code>```

答:
Your Preist_Click call blocks the UI: it executes in the same thread, instead of starting its own.

Try this:

```<code>private bool keepRunning = true;

private void Preiststop_Click(object sender, EventArgs e)
{
    keepRunning = false;
}

private async void Preist_Click(object sender, EventArgs e)
{
    keepRunning = true;
    await Task.Run(() => {
        while (keepRunning)
        {
            SendKeys.Send(" ");
            Thread.Sleep(5000);
        }
    });
}
</code>```

Title: C# why cant i exit this while loop?

Body:
I'm tryig to make a program that can auto press space.
but i can only enable it. after the program crashes.

so i cant turn it off. pleace help

here is my code:

using System.Windows.Forms;

namespace Auto_Abillty
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public bool startFlag = false;
    public bool stopFlag = false;
    private void Preiststop_Click(object sender, EventArgs e)
    {
        stopFlag = true;
    }
    private void Preist_Click(object sender, EventArgs e)
    {
        startFlag = true;
        while (startFlag)
        {
            SendKeys.Send(" ");
            Thread.Sleep(5000);
            if (stopFlag)
                startFlag = false;
        }
    }

}
}

Body:
Your Preist_Click call blocks the UI: it executes in the same thread, instead of starting its own.

Try this:

private bool keepRunning = true;

private void Preiststop_Click(object sender, EventArgs e)
{
    keepRunning = false;
}

private async void Preist_Click(object sender, EventArgs e)
{
    keepRunning = true;
    await Task.Run(() => {
        while (keepRunning)
        {
            SendKeys.Send(" ");
            Thread.Sleep(5000);
        }
    });
}


问:
Laravel remove first item in a collection
I want to remove the first item in a collection:

```<code>unset($productData->images->first())
</code>```

The above doesn't work.

The reason I want this is so that later when I do a foreach, the first item doesn't come out:

```<code>@foreach($productData->images as $images)
    <img class="product-thumb" src="/images/products/{{$images->src_thumb}}">
@endforeach
</code>```

How can this be done?

答:
In Laravel 5 you can use slice() method:</p>

```<code>$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);

$slice->all();    // [5, 6, 7, 8, 9, 10]
</code>```

Body:
I want to remove the first item in a collection:

unset($productData->images->first())

The above doesn't work.

The reason I want this is so that later when I do a foreach, the first item doesn't come out:

@foreach($productData->images as $images)
    src_thumb}}">
@endforeach

How can this be done?

Body:
In Laravel 5 you can use slice() method:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);

$slice->all();    // [5, 6, 7, 8, 9, 10]


答:
I think you're looking for Visitor Design Pattern.

From Wikipedia :

In object-oriented programming and software engineering, the visitor
  design pattern is a way of separating an algorithm from an object
  structure on which it operates. A practical result of this separation
  is the ability to add new operations to extant object structures
  without modifying the structures. It is one way to follow the
  open/closed principle.

In essence, the visitor allows adding new virtual functions to a
  family of classes, without modifying the classes. Instead, a visitor
  class is created that implements all of the appropriate
  specializations of the virtual function. The visitor takes the
  instance reference as input, and implements the goal through double
  dispatch.

Body:
Disclaimer: I know there are a lot of questions about polymorphism out there, but I couldn't find a suitable answer for my problem. If your Google-fu is better than mine, please forgive the dupe.

I have a model using inheritance, such as in the example below.

public abstract class Base {
// ...
}

public class ConcreteA extends Base {
    private String someString;
// ...
}

public class ConcreteB extends Base {
    private boolean someBool;
// ...
}

And I also have a List<Base>, which is composed of objects that are either ConcreteAs or ConcreteBs.

I need to generate a graphical view for each object in the list, but the resulting element is not the same for ConcreteAs and ConcreteBs. From the example above, the view for ConcreteA would be a text field, while the view for a ConcreteB would be a check box.

How can I achieve this using OO principles?


问:
How to send list of items to function in new thread using python
I want send list of items to function in new thread:

```<code>thread = Thread(target=commit_list, args=(list))
thread.start()

def commit_list(list):
    for p in list:
        print p
</code>```

In this code, I am getting error:

TypeError: commit_list() takes exactly 1 argument (11 given)

I dont know why.

I tried:
Compile error:

```<code>Thread(target=commit_list, args=(*list))
</code>```

and
Compile error:

```<code>Thread(target=commit_list, args=(**list))
</code>```

and
Same error with 11 given arguments

```<code>Thread(target=commit_list, args=(list[:]))
</code>```

Thank for any help.

答:
use args=(list,) instead.

since args needs to be a tuple, (list) will just be a list, but (list,) will be a tuple including a list as the first argument.

Hope that helps.

Body:
I want send list of items to function in new thread:

thread = Thread(target=commit_list, args=(list))
thread.start()

def commit_list(list):
    for p in list:
        print p

In this code, I am getting error:

TypeError: commit_list() takes exactly 1 argument (11 given)

I dont know why.

I tried:
Compile error:

Thread(target=commit_list, args=(*list))

and
Compile error:

Thread(target=commit_list, args=(**list))

and
Same error with 11 given arguments

Thread(target=commit_list, args=(list[:]))

Thank for any help.


问:
How to find all instances of a procedure (or function) in SQL Server 2005/2008
I modified a procedure and it now takes a greater number of parameters. How can I find every place that the procedure is called so I can update the number of arguments the proc is passed?

I tried this:

```<code>select * from syscomments where text like '%MODIFIED-PROCEDURE-NAME%'
</code>```

but I'm still finding other places the proc is called that this query did not return.

答:
If this is all inside of SQL server you could just recompile it.

Just create a single script containing all stored procedures and functions.  Run the script.  It'll bomb where the problems are.

Optionally, you could just search the script you created as well.

ContentLicense: CC BY-SA 2.5

Body:
I modified a procedure and it now takes a greater number of parameters. How can I find every place that the procedure is called so I can update the number of arguments the proc is passed?

I tried this:

select * from syscomments where text like '%MODIFIED-PROCEDURE-NAME%'

but I'm still finding other places the proc is called that this query did not return.


答:
Seems like all you need is a thread so another button can be pushed to change the condition of "j". If there is only one thread, the UI will not be updated until that thread is stopped hence the need to make another thread, like below example.</p>

```<code>public Form1()
{
    InitializeComponent();

}

public bool x = false;
public bool j = false;
private void Preiststop_Click(object sender, EventArgs e)
{
    j = true;
}
private void Preist_Click(object sender, EventArgs e)
{
    Thread newThread = new Thread(DoPriestWork);
    newThread.Start();
}
public void DoPriestWork()
{
    x = true;
    while (x == true)
    {
        SendKeys.Send(" ");
        Thread.Sleep(5000);
        if (j == true)
            x = false;
    }
}
</code>```

Title: C# why cant i exit this while loop?

Body:
Seems like all you need is a thread so another button can be pushed to change the condition of "j". If there is only one thread, the UI will not be updated until that thread is stopped hence the need to make another thread, like below example.

public Form1()
{
    InitializeComponent();

}

public bool x = false;
public bool j = false;
private void Preiststop_Click(object sender, EventArgs e)
{
    j = true;
}
private void Preist_Click(object sender, EventArgs e)
{
    Thread newThread = new Thread(DoPriestWork);
    newThread.Start();
}
public void DoPriestWork()
{
    x = true;
    while (x == true)
    {
        SendKeys.Send(" ");
        Thread.Sleep(5000);
        if (j == true)
            x = false;
    }
}


问:
How to implement INotifyPropertyChanged in C# 6.0?
The answer to this question has been edited to say that in C# 6.0, INotifyPropertyChanged can be implemented with the following OnPropertyChanged procedure:

```<code>protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
</code>```

However, it isn't clear from that answer what the corresponding property definition should be. What does a complete implementation of INotifyPropertyChanged look like in C# 6.0 when this construction is used?

答:
I know this question is old, but here is my implementation

Bindable uses a dictionary as a property store. It's easy enough to add the necessary overloads for a subclass to manage its own backing field using ref parameters.

No magic string

No reflection

Can be improved to suppress the default dictionary lookup

The code:

```<code>    public class Bindable : INotifyPropertyChanged
    {
        private Dictionary<string, object> _properties = new Dictionary<string, object>();

        /// <summary>
        /// Gets the value of a property
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T Get<T>([CallerMemberName] string name = null)
        {
            object value = null;
            if (_properties.TryGetValue(name, out value))
                return value == null ? default(T) : (T)value;
            return default(T);
        }

        /// <summary>
        /// Sets the value of a property
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="name"></param>
        protected void Set<T>(T value, [CallerMemberName] string name = null)
        {
            if (Equals(value, Get<T>(name)))
                return;
            _properties[name] = value;
            OnPropertyChanged(name);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
</code>```

used like this

```<code>public class Item : Bindable
{
     public Guid Id { get { return Get<Guid>(); } set { Set<Guid>(value); } }
}
</code>```

Body:
The answer to this question has been edited to say that in C# 6.0, INotifyPropertyChanged can be implemented with the following OnPropertyChanged procedure:

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

However, it isn't clear from that answer what the corresponding property definition should be. What does a complete implementation of INotifyPropertyChanged look like in C# 6.0 when this construction is used?

Body:
I know this question is old, but here is my implementation

Bindable uses a dictionary as a property store. It's easy enough to add the necessary overloads for a subclass to manage its own backing field using ref parameters.

No magic string

No reflection

Can be improved to suppress the default dictionary lookup

The code:

    public class Bindable : INotifyPropertyChanged
    {
        private Dictionary<string, object> _properties = new Dictionary<string, object>();

        /// <summary>
        /// Gets the value of a property
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T Get<T>([CallerMemberName] string name = null)
        {
            object value = null;
            if (_properties.TryGetValue(name, out value))
                return value == null ? default(T) : (T)value;
            return default(T);
        }

        /// <summary>
        /// Sets the value of a property
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="name"></param>
        protected void Set<T>(T value, [CallerMemberName] string name = null)
        {
            if (Equals(value, Get<T>(name)))
                return;
            _properties[name] = value;
            OnPropertyChanged(name);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

used like this

public class Item : Bindable
{
     public Guid Id { get { return Get<Guid>(); } set { Set<Guid>(value); } }
}


问:
In a WPF application (with Devexpress), Store data for retrieval after the application is reopened
I want to save the contents of a SelectedItem or Item's from a ComboBox as well as DataGrid Column Order so as retain the information when the application is reopened.
Initially I am using the below code for saving the data as long as the application is open:

```<code>App.Current.Properties[1] = SelectedDataSetList;
App.Current.Properties[2] = SelectedModuleList;
App.Current.Properties[0] = SelectedContentSet;
</code>```

SelectedDataSetList is bound to a ComboBox:

```<code><dxe:ComboBoxEdit Text="SCOPE" x:Name="ContentSetCombobox" Grid.Column="1" Height="25" IncrementalFiltering="True" ItemsSource="{Binding ContentSetList}" DisplayMember="Name" AllowUpdateTwoWayBoundPropertiesOnSynchronization="False"  SelectedItem="{Binding SelectedContentSet,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
</code>```

But, I was unable to store the information in a Chache memory for retrieving even if the application is closed and opened again.

Is there any way to do this without using an external file like .xml?

答:
If you're looking to save to IsolatedStorage you can use this class I've put together (see below). It's not perfect and will fail if you try to save a type that isn't marked as Serializable but it's good enough for casual use. I've left exception handling as an exercise for the OP.

```<code>public class IsolatedStorageManager
{
    public void Save<T>(T item, string key)
    {
        var isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
        using (var writeStream = new IsolatedStorageFileStream(key, FileMode.Create, isf))
        {
            Serialise(item, writeStream);
        }
    }

    public T Open<T>(string key)
    {
        var isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
        using (var readStream = new IsolatedStorageFileStream(key, FileMode.Open, isf))
        {
            var item = Deserialise<T>(readStream);
            return item;
        }
    }

    private Stream Serialise<T>(T item, Stream stream)
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, item);
        return stream;
    }

    private T Deserialise<T>(Stream stream)
    {
        var formatter = new BinaryFormatter();
        var item = formatter.Deserialize(stream);
        return (T) item;
    }
}
</code>```

Saving classes and datasets is demonstrated in the test fixture below.

```<code>[TestFixture]
public class IsolatedStorageManagerTestFixture
{
    private IsolatedStorageManager _underTest;
    private const string SaveFileKey = "TestSaveFileKey";

    [SetUp]
    public void SetUp()
    {
        _underTest = new IsolatedStorageManager();
    }

    [Test]
    public void TestSavingDataset()
    {
        var tableName = "TestTable";

        var ds = new DataSet();
        ds.Tables.Add(new DataTable(tableName));
        _underTest.Save(ds, SaveFileKey);

        var saved = _underTest.Open<DataSet>(SaveFileKey);

        Assert.That(saved.Tables.Count==1);
        Assert.That(saved.Tables[0].TableName == tableName);
    }

    [Test]
    public void TestSavingClass()
    {
        var list = new ArrayList {"Hello", new DataTable(), 2};

        _underTest.Save(list,SaveFileKey);

        var saved = _underTest.Open<ArrayList>(SaveFileKey);

        Assert.That(saved.Count==3);
        Assert.That(string.Equals((string)saved[0], "Hello"));
        Assert.That(list[1] is DataTable);
        Assert.That((int)list[2] == 2);
    }
}
</code>```

Body:
I want to save the contents of a SelectedItem or Item's from a ComboBox as well as DataGrid Column Order so as retain the information when the application is reopened.
Initially I am using the below code for saving the data as long as the application is open:

App.Current.Properties[1] = SelectedDataSetList;
App.Current.Properties[2] = SelectedModuleList;
App.Current.Properties[0] = SelectedContentSet;

SelectedDataSetList is bound to a ComboBox:

<dxe:ComboBoxEdit Text="SCOPE" x:Name="ContentSetCombobox" Grid.Column="1" Height="25" IncrementalFiltering="True" ItemsSource="{Binding ContentSetList}" DisplayMember="Name" AllowUpdateTwoWayBoundPropertiesOnSynchronization="False"  SelectedItem="{Binding SelectedContentSet,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >

But, I was unable to store the information in a Chache memory for retrieving even if the application is closed and opened again.

Is there any way to do this without using an external file like .xml?

Body:
If you're looking to save to IsolatedStorage you can use this class I've put together (see below). It's not perfect and will fail if you try to save a type that isn't marked as Serializable but it's good enough for casual use. I've left exception handling as an exercise for the OP.

public class IsolatedStorageManager
{
    public void Save<T>(T item, string key)
    {
        var isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
        using (var writeStream = new IsolatedStorageFileStream(key, FileMode.Create, isf))
        {
            Serialise(item, writeStream);
        }
    }

    public T Open<T>(string key)
    {
        var isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
        using (var readStream = new IsolatedStorageFileStream(key, FileMode.Open, isf))
        {
            var item = Deserialise<T>(readStream);
            return item;
        }
    }

    private Stream Serialise<T>(T item, Stream stream)
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, item);
        return stream;
    }

    private T Deserialise<T>(Stream stream)
    {
        var formatter = new BinaryFormatter();
        var item = formatter.Deserialize(stream);
        return (T) item;
    }
}

Saving classes and datasets is demonstrated in the test fixture below.

[TestFixture]
public class IsolatedStorageManagerTestFixture
{
    private IsolatedStorageManager _underTest;
    private const string SaveFileKey = "TestSaveFileKey";

    [SetUp]
    public void SetUp()
    {
        _underTest = new IsolatedStorageManager();
    }

    [Test]
    public void TestSavingDataset()
    {
        var tableName = "TestTable";

        var ds = new DataSet();
        ds.Tables.Add(new DataTable(tableName));
        _underTest.Save(ds, SaveFileKey);

        var saved = _underTest.Open<DataSet>(SaveFileKey);

        Assert.That(saved.Tables.Count==1);
        Assert.That(saved.Tables[0].TableName == tableName);
    }

    [Test]
    public void TestSavingClass()
    {
        var list = new ArrayList {"Hello", new DataTable(), 2};

        _underTest.Save(list,SaveFileKey);

        var saved = _underTest.Open<ArrayList>(SaveFileKey);

        Assert.That(saved.Count==3);
        Assert.That(string.Equals((string)saved[0], "Hello"));
        Assert.That(list[1] is DataTable);
        Assert.That((int)list[2] == 2);
    }
}


问:
React dynamic forms that are nested
I'm soooo close to getting this to work but just can't seem to wrap my head around this.

I have a form that's supposed to submit to a json file with the following structure:

```<code>    {
      title: '',
      content: [
        {className: '', body: ''}
      ]
    }
</code>```

I'm able to set the state for the title no problem, as well as the first object in the content array. I think I need to create a loop or something? Below is my full component.

```<code>import React, { Component } from 'react';

class AddEditPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '',
      content: [
        {className: '', body: ''}
      ]
    }
    this.addInput = this.addInput.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleNestedChange = this.handleNestedChange.bind(this);
  }

  handleChange(e) {
    const value = e.target.value
    this.setState({
      [e.target.name]: value
    })
  }

  handleNestedChange(e) {
    const value = e.target.value
    console.log(e.target.id)
    this.setState({

    })

  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(this.state)
  }

  addInput() {
    const newInput = { className: '', body: ''}
    this.setState({content: this.state.content.concat(newInput)});
  }

  render() {
    const contentInputs = this.state.content.map((content, i)=> {
     return (
        <div key={i}>
          <input
            type="text"
            name="className"
            id={`${i}`}
            placeholder="Class name"
            onChange={this.handleNestedChange}
          />
          <input
            type="text"
            name="body"
            placeholder="Body"
            id={`${i}`}
            onChange={this.handleNestedChange}
          />
        </div>
      )
    })

    return (
      <div>
        <h2>New Page</h2>
        <form onSubmit={this.handleSubmit}>
            <input
            type="text"
            name="title"
            placeholder={this.state.title || `Enter the title`}
            onChange={this.handleChange}
            />
          <h3>Content</h3>
            {contentInputs}
            <button onClick={this.addInput}>Add</button>
          <input type="submit" />
        </form>
      </div>
    );
  }
}

export default AddEditPage;
</code>```

 & praise for the answer haha

答:
I think handleNestedChange is not binded properly, because the context this is refering to map function not the component. You have to bind map function with current context.

```<code>const contentInputs = this.state.content.map((content, i)=> {
    return (
    <div key={i}> <input type="text" name="className" id={`${i}`} placeholder="Class name" onChange={this.handleNestedChange} /> <input type="text" name="body" placeholder="Body" id={`${i}`} onChange={this.handleNestedChange} /> </div>
)
}).bind(this)
</code>```

Title: React dynamic forms that are nested

Body:
I'm soooo close to getting this to work but just can't seem to wrap my head around this.

I have a form that's supposed to submit to a json file with the following structure:

    {
      title: '',
      content: [
        {className: '', body: ''}
      ]
    }

I'm able to set the state for the title no problem, as well as the first object in the content array. I think I need to create a loop or something? Below is my full component.

import React, { Component } from 'react';

class AddEditPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '',
      content: [
        {className: '', body: ''}
      ]
    }
    this.addInput = this.addInput.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleNestedChange = this.handleNestedChange.bind(this);
  }

  handleChange(e) {
    const value = e.target.value
    this.setState({
      [e.target.name]: value
    })
  }

  handleNestedChange(e) {
    const value = e.target.value
    console.log(e.target.id)
    this.setState({

    })

  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(this.state)
  }

  addInput() {
    const newInput = { className: '', body: ''}
    this.setState({content: this.state.content.concat(newInput)});
  }

  render() {
    const contentInputs = this.state.content.map((content, i)=> {
     return (

          <input
            type="text"
            name="className"
            id={`${i}`}
            placeholder="Class name"
            onChange={this.handleNestedChange}
          />
          <input
            type="text"
            name="body"
            placeholder="Body"
            id={`${i}`}
            onChange={this.handleNestedChange}
          />

      )
    })

    return (

New Page

        <form onSubmit={this.handleSubmit}>
            <input
            type="text"
            name="title"
            placeholder={this.state.title || `Enter the title`}
            onChange={this.handleChange}
            />

Content

            {contentInputs}
            <button onClick={this.addInput}>Add</button>
          <input type="submit" />
        </form>

    );
  }
}

export default AddEditPage;

 & praise for the answer haha

Body:
I think handleNestedChange is not binded properly, because the context this is refering to map function not the component. You have to bind map function with current context.

const contentInputs = this.state.content.map((content, i)=> {
    return (
    <div key={i}> <input type="text" name="className" id={`${i}`} placeholder="Class name" onChange={this.handleNestedChange} /> <input type="text" name="body" placeholder="Body" id={`${i}`} onChange={this.handleNestedChange} /> </div>
)
}).bind(this)


问:
Yarn (JS) commands failing with "Error: Could not find or load main class run"
I'm working on an application that recently switched from npm to yarn and I am unable to run package.json scripts. Running a command with yarn results in the following error:

Error: Could not find or load main class run

Running the same commands with npm work fine. Example:

```<code>$ yarn run test
> Error: Could not find or load main class run
$ npm run test
> RUNS  test/jest/components/DataTable.test.js
> RUNS  test/jest/components/NavItem.test.js
> // etc
</code>```

答:
You've also got Apache Yarn installed and your system is using this yarn.

To confirm, run yarn version and you'll see something like the following:

```<code>hadoop 2.7.1
Subversion https://git-wip-us.apache.org/repos/asf/hadoop.git -r 15ec7ccf46de536e6ce7a
Compiled by jenkins on 2015-06-29T06:04Z
Compiled with protoc 2.5.0
From source with checksum fc0a1a23fc1868e4d5ee7fa2b28a58a
This command was run using
/usr/local/Cellar/hadoop/2.7.1/libexec/share/hadoop/common/hadoop-common-2.7.1.jar
</code>```

You'll need to resolve the conflict by aliasing one of the commands.

Body:
I'm working on an application that recently switched from npm to yarn and I am unable to run package.json scripts. Running a command with yarn results in the following error:

Error: Could not find or load main class run

Running the same commands with npm work fine. Example:

$ yarn run test
> Error: Could not find or load main class run
$ npm run test
> RUNS  test/jest/components/DataTable.test.js
> RUNS  test/jest/components/NavItem.test.js
> // etc

Body:
You've also got Apache Yarn installed and your system is using this yarn.

To confirm, run yarn version and you'll see something like the following:

hadoop 2.7.1
Subversion https://git-wip-us.apache.org/repos/asf/hadoop.git -r 15ec7ccf46de536e6ce7a
Compiled by jenkins on 2015-06-29T06:04Z
Compiled with protoc 2.5.0
From source with checksum fc0a1a23fc1868e4d5ee7fa2b28a58a
This command was run using
/usr/local/Cellar/hadoop/2.7.1/libexec/share/hadoop/common/hadoop-common-2.7.1.jar

You'll need to resolve the conflict by aliasing one of the commands.


问:
Google Maps Transit: Time it takes from point A to B
I found some code that shows the map and calculate the travel time by Driving. Is it possible to find the travel time using transit (e.g. BUS) ? The code that I found was using google.maps.DirectionsTravelMode.DRIVING , I looked into the API and only DRIVING, BICYCLING and WALKING were available.

Thanks in advance!

答:
unfortunately, Google Maps only supports static route computation. When I talk about satic it means that the system considers only the route and the average speeds, which are fixed, to determine travel time.

Taking buses into account would require a comprehensive knowledge of bus lines, stops and timetables. It's not impossible to do, but it is really hard. Just for an example, the estimated bus travel time must take into account the waiting time for the next bus at the stop, and it must have then knowledge of timetables too! (not only lines and speeds).

The same applies merging bus and underground (where available).

I hope believe that, in the future, Google Maps will be able to provide these information too.


问:
Stop ngAfterContentInit from executing twice
I'm a bit confused as to why ngAfterContentInit is executing twice in this scenario. I've created a stripped-down version of our application to reproduce the bug. In short, I make use of a *contentItem to tag components which is then picked up by the standard-layout component for rendering. As soon as I follow this pattern, demo's ngAfterContentInit is executed twice.

I placed the demo app on github which will reproduce the error:
https://github.com/jVaaS/stackoverflow/tree/master/ngaftercontentinit

Otherwise here are the important bits:

buggy-app.dart:

```<code>@Component(
    selector: "buggy-app",
    template: """
        <standard-layout>
            <demo *contentItem></demo>
        </standard-layout>
    """,
    directives: const [
        ContentItemDirective,
        StandardLayout,
        Demo
    ]
)
class BuggyApp implements AfterContentInit {

    @override
    ngAfterContentInit() {
        print(">>> ngAfterContentInit: BuggyApp");
    }
}
</code>```

standard-layout.dart:

```<code>////////////////////////////////////////////////////////////////////////////////
///
/// Standard Layout Component
/// <standard-layout></standard-layout>
///
@Component(
    selector: "standard-layout",
    template: """
        <div *ngFor="let item of contentItems ?? []">
            <template [ngTemplateOutlet]="item.template"></template>
        </div>
    """,
    directives: const [ROUTER_DIRECTIVES, ContentItem])
class StandardLayout implements AfterContentInit {

    @ContentChildren(ContentItemDirective)
    QueryList<ContentItemDirective> contentItems;

    @override
    ngAfterContentInit() {
        print(">>> ngAfterContentInit: StandardLayout");
    }

}

////////////////////////////////////////////////////////////////////////////////
///
/// Content Item Directive
/// *contentItem
///
@Directive(selector: '[contentItem]')
class ContentItemDirective implements AfterContentInit {
    final ViewContainerRef vcRef;
    final TemplateRef template;
    final ComponentResolver componentResolver;

    ContentItemDirective(this.vcRef, this.template, this.componentResolver);

    ComponentRef componentRef;

    @override
    ngAfterContentInit() async {
        final componentFactory =
        await componentResolver.resolveComponent(ContentItem);
        componentRef = vcRef.createComponent(componentFactory);
        (componentRef.instance as ContentItem)
            ..template = template;
    }
}

////////////////////////////////////////////////////////////////////////////////
///
/// Content Item Generator
///
@Component(
    selector: "content-item",
    host: const {
        '[class.content-item]': "true",
    },
    template: """
        <template [ngTemplateOutlet]="template"></template>
    """,
    directives: const [NgTemplateOutlet]
)
class ContentItem {
    TemplateRef template;
}
////////////////////////////////////////////////////////////////////////////////
</code>```

and finally demo.dart:

```<code>@Component(
    selector: "demo",
    template: "Hello World Once, but demo prints twice!")
class Demo implements AfterContentInit {

    @override
    ngAfterContentInit() {
        print(">>> ngAfterContentInit: Demo");
    }

}
</code>```

main.dart doesn't have much in it:

```<code>void main() {
    bootstrap(BuggyApp);
}
</code>```

When I run this, Hello World prints once as expected:

but when looking at the terminal:

So the demo component renders exactly once, but its ngAfterContentInit is being executed twice which causes havoc when your assumption is that it only gets executed once.

I've tried adding a hacky workaround, but it seems that component actually gets re-rendered twice:

```<code>int counter = 0;

@override
ngAfterContentInit() {

    if (counter == 0) {
        print(">>> ngAfterContentInit: Demo");
        counter++;
    }

}
</code>```

Is this a bug in Angular or is there something I can do to prevent this?

pubspec.yaml in case it's needed:

```<code>name: bugdemo
version: 0.0.0
description: Bug Demo
environment:
  sdk: '>=1.13.0 <2.0.0'
dependencies:
  angular2: 3.1.0
  browser: ^0.10.0
  http: any
  js: ^0.6.0
  dart_to_js_script_rewriter: ^1.0.1
transformers:
- angular2:
    platform_directives:
    - package:angular2/common.dart#COMMON_DIRECTIVES
    platform_pipes:
    - package:angular2/common.dart#COMMON_PIPES
    entry_points: web/main.dart
- dart_to_js_script_rewriter
- $dart2js:
    commandLineOptions: [--enable-experimental-mirrors]
</code>```

and index.html for good measure:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Strange Bug</title>
</head>
<body>

    <buggy-app>
        Loading ...
    </buggy-app>

<script async src="main.dart" type="application/dart"></script>
<script async src="packages/browser/dart.js"></script>
</body>
</html>
</code>```

Update

So it was suggested that it might be that it only happens twice in dev-mode. I've done a pub build and ran the index.html which now contains main.dart.js in regular Chrome.

It's still executing twice, tried with ngAfterViewInit and that too executes twice.

Logged a bug in the meantime:
https://github.com/dart-lang/angular/issues/478

答:
This doesn't seem like a bug.

Here is the generated code for demo.dart:
https://gist.github.com/matanlurey/f311d90053e36cc09c6e28f28ab2d4cd

```<code>void detectChangesInternal() {
  bool firstCheck = identical(this.cdState, ChangeDetectorState.NeverChecked);
  final _ctx = ctx;
  if (!import8.AppViewUtils.throwOnChanges) {
    dbg(0, 0, 0);
    if (firstCheck) {
      _Demo_0_2.ngAfterContentInit();
    }
  }
  _compView_0.detectChanges();
}
</code>```

I was suspicious, so I changed your print message to include the hashCode:

```<code>@override
ngAfterContentInit() {
  print(">>> ngAfterContentInit: Demo $hashCode");
}
</code>```

Then I saw the following:

ngAfterContentInit: Demo 516575718

ngAfterContentInit: Demo 57032191

Which means two diffferent instances of demo were alive, not just one emitting twice. I then added StackTrace.current to the constructor of demo to get a stack trace:

```<code>Demo() {
  print('Created $this:$hashCode');
  print(StackTrace.current);
}
</code>```

And got:

0      Demo.Demo (package:bugdemo/demo.dart:11:20)
  1      ViewBuggyApp1.build (package:bugdemo/buggy-app.template.dart:136:21)
  2      AppView.create (package:angular2/src/core/linker/app_view.dart:180:12)
  3      DebugAppView.create (package:angular2/src/debug/debug_app_view.dart:73:26)
  4      TemplateRef.createEmbeddedView (package:angular2/src/core/linker/template_ref.dart:27:10)
  5      ViewContainer.createEmbeddedView (package:angular2/src/core/linker/view_container.dart:86:43)

Which in turn said your component was being created by BuggyApp's template:

```<code><standard-layout>
  <demo *contentItem></demo>
</standard-layout>
</code>```

Closer. Kept digging.

I commented out ContentItemDirective, and saw Demo was now created once. I imagine you expected it not to be created at all due to *contentItem, so kept digging - and finally figured it out.

Your StandardLayout component creates templates:

```<code><div *ngFor="let item of contentItems ?? []">
  <template [ngTemplateOutlet]="item.template"></template>
</div>
</code>```

But so does your ContentItemDirective via ComponentResolver. I imagine you did not intend this. So I'd figure out what you were trying to do and address your issue by removing creating the component in one of these places.

Body:
I'm a bit confused as to why ngAfterContentInit is executing twice in this scenario. I've created a stripped-down version of our application to reproduce the bug. In short, I make use of a *contentItem to tag components which is then picked up by the standard-layout component for rendering. As soon as I follow this pattern, demo's ngAfterContentInit is executed twice.

I placed the demo app on github which will reproduce the error:
https://github.com/jVaaS/stackoverflow/tree/master/ngaftercontentinit

Otherwise here are the important bits:

buggy-app.dart:

@Component(
    selector: "buggy-app",
    template: """
        <standard-layout>
            <demo *contentItem></demo>
        </standard-layout>
    """,
    directives: const [
        ContentItemDirective,
        StandardLayout,
        Demo
    ]
)
class BuggyApp implements AfterContentInit {

    @override
    ngAfterContentInit() {
        print(">>> ngAfterContentInit: BuggyApp");
    }
}

standard-layout.dart:

////////////////////////////////////////////////////////////////////////////////
///
/// Standard Layout Component
/// <standard-layout></standard-layout>
///
@Component(
    selector: "standard-layout",
    template: """

            <template [ngTemplateOutlet]="item.template"></template>

    """,
    directives: const [ROUTER_DIRECTIVES, ContentItem])
class StandardLayout implements AfterContentInit {

    @ContentChildren(ContentItemDirective)
    QueryList<ContentItemDirective> contentItems;

    @override
    ngAfterContentInit() {
        print(">>> ngAfterContentInit: StandardLayout");
    }

}

////////////////////////////////////////////////////////////////////////////////
///
/// Content Item Directive
/// *contentItem
///
@Directive(selector: '[contentItem]')
class ContentItemDirective implements AfterContentInit {
    final ViewContainerRef vcRef;
    final TemplateRef template;
    final ComponentResolver componentResolver;

    ContentItemDirective(this.vcRef, this.template, this.componentResolver);

    ComponentRef componentRef;

    @override
    ngAfterContentInit() async {
        final componentFactory =
        await componentResolver.resolveComponent(ContentItem);
        componentRef = vcRef.createComponent(componentFactory);
        (componentRef.instance as ContentItem)
            ..template = template;
    }
}

////////////////////////////////////////////////////////////////////////////////
///
/// Content Item Generator
///
@Component(
    selector: "content-item",
    host: const {
        '[class.content-item]': "true",
    },
    template: """
        <template [ngTemplateOutlet]="template"></template>
    """,
    directives: const [NgTemplateOutlet]
)
class ContentItem {
    TemplateRef template;
}
////////////////////////////////////////////////////////////////////////////////

and finally demo.dart:

@Component(
    selector: "demo",
    template: "Hello World Once, but demo prints twice!")
class Demo implements AfterContentInit {

    @override
    ngAfterContentInit() {
        print(">>> ngAfterContentInit: Demo");
    }

}

main.dart doesn't have much in it:

void main() {
    bootstrap(BuggyApp);
}

When I run this, Hello World prints once as expected:

but when looking at the terminal:

So the demo component renders exactly once, but its ngAfterContentInit is being executed twice which causes havoc when your assumption is that it only gets executed once.

I've tried adding a hacky workaround, but it seems that component actually gets re-rendered twice:

int counter = 0;

@override
ngAfterContentInit() {

    if (counter == 0) {
        print(">>> ngAfterContentInit: Demo");
        counter++;
    }

}

Is this a bug in Angular or is there something I can do to prevent this?

pubspec.yaml in case it's needed:

name: bugdemo
version: 0.0.0
description: Bug Demo
environment:
  sdk: '>=1.13.0 <2.0.0'
dependencies:
  angular2: 3.1.0
  browser: ^0.10.0
  http: any
  js: ^0.6.0
  dart_to_js_script_rewriter: ^1.0.1
transformers:
- angular2:
    platform_directives:
    - package:angular2/common.dart#COMMON_DIRECTIVES
    platform_pipes:
    - package:angular2/common.dart#COMMON_PIPES
    entry_points: web/main.dart
- dart_to_js_script_rewriter
- $dart2js:
    commandLineOptions: [--enable-experimental-mirrors]

and index.html for good measure:

<!DOCTYPE html>

    <title>Strange Bug</title>

    <buggy-app>
        Loading ...
    </buggy-app>

Update

So it was suggested that it might be that it only happens twice in dev-mode. I've done a pub build and ran the index.html which now contains main.dart.js in regular Chrome.

It's still executing twice, tried with ngAfterViewInit and that too executes twice.

Logged a bug in the meantime:
https://github.com/dart-lang/angular/issues/478

Body:
This doesn't seem like a bug.

Here is the generated code for demo.dart:
https://gist.github.com/matanlurey/f311d90053e36cc09c6e28f28ab2d4cd

void detectChangesInternal() {
  bool firstCheck = identical(this.cdState, ChangeDetectorState.NeverChecked);
  final _ctx = ctx;
  if (!import8.AppViewUtils.throwOnChanges) {
    dbg(0, 0, 0);
    if (firstCheck) {
      _Demo_0_2.ngAfterContentInit();
    }
  }
  _compView_0.detectChanges();
}

I was suspicious, so I changed your print message to include the hashCode:

@override
ngAfterContentInit() {
  print(">>> ngAfterContentInit: Demo $hashCode");
}

Then I saw the following:

ngAfterContentInit: Demo 516575718

ngAfterContentInit: Demo 57032191

Which means two diffferent instances of demo were alive, not just one emitting twice. I then added StackTrace.current to the constructor of demo to get a stack trace:

Demo() {
  print('Created $this:$hashCode');
  print(StackTrace.current);
}

And got:

0      Demo.Demo (package:bugdemo/demo.dart:11:20)
  1      ViewBuggyApp1.build (package:bugdemo/buggy-app.template.dart:136:21)
  2      AppView.create (package:angular2/src/core/linker/app_view.dart:180:12)
  3      DebugAppView.create (package:angular2/src/debug/debug_app_view.dart:73:26)
  4      TemplateRef.createEmbeddedView (package:angular2/src/core/linker/template_ref.dart:27:10)
  5      ViewContainer.createEmbeddedView (package:angular2/src/core/linker/view_container.dart:86:43)

Which in turn said your component was being created by BuggyApp's template:

<standard-layout>
  <demo *contentItem></demo>
</standard-layout>

Closer. Kept digging.

I commented out ContentItemDirective, and saw Demo was now created once. I imagine you expected it not to be created at all due to *contentItem, so kept digging - and finally figured it out.

Your StandardLayout component creates templates:

<div *ngFor="let item of contentItems ?? []">
  <template [ngTemplateOutlet]="item.template"></template>
</div>

But so does your ContentItemDirective via ComponentResolver. I imagine you did not intend this. So I'd figure out what you were trying to do and address your issue by removing creating the component in one of these places.


问:
How could I get rid off border around header image
I created basic html and css webpage and in header element i put image,with 100% width margin:auto and it still exist some space between image and border of my screen.I am using Edge browser on my laptop with recent update.</p>

答: Most likely you're looking for body { margin: 0; }


问:
Equivalent of `git add -p` for cvs
I am stuck with cvs (don't ask!) and I was thinking that out of all the goodness of git, there is one that could be approximated reasonably enough: incremental addition of changes, à la git add -p followed by git commit. Before I try to hack together a solution, does anyone know of an implementation of such a feature?

答:
If I were in your situation, I would consider using a git interface to a cvs repository.

Best practices for using git with CVS
cvs

I do not have experience doing this, so there may be some hidden gotchas I don't know about that would prevent it from working for you, but that is where I would start.

Title: Equivalent of `git add -p` for cvs


答:
I would suggest using System.Windows.Forms.Timer with 5000 ms interval instead of your approach. Then by clicking on the button on a form you may start or stop it.

Another approach is to move your while loop into another thread that will make UI thread still be responsive

Title: C# why cant i exit this while loop?

Body:
I'm tryig to make a program that can auto press space.
but i can only enable it. after the program crashes.

so i cant turn it off. pleace help

here is my code:

using System.Windows.Forms;

namespace Auto_Abillty
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public bool startFlag = false;
    public bool stopFlag = false;
    private void Preiststop_Click(object sender, EventArgs e)
    {
        stopFlag = true;
    }
    private void Preist_Click(object sender, EventArgs e)
    {
        startFlag = true;
        while (startFlag)
        {
            SendKeys.Send(" ");
            Thread.Sleep(5000);
            if (stopFlag)
                startFlag = false;
        }
    }

}
}