问:
Can I update the UI one "tick" during intensive task on the UI thread?
My app has an intensive task that I'm currently running on the UI thread. It takes about 15 seconds. As such, I really need to update the UI at strategic points during the task, in order for the user (and the OS) not to think the app has crashed (stopped responding).

It seems like it might be possible to do something like this (pseudocode):

```<code>void longTaskOnUIThread() {
    // Here I'm maintaining the sequence of steps as a sequence of statements
    // in one method, despite letting the UI catch its breath between steps.
    doAChunkOfTheTask();
    dispatchUIQueueMessage();
    int result = doSecondChunkOfTheTask();
    if (result < 3) {
        dispatchUIQueueMessage();
        doThirdChunkOfTheTask();
    }
}

void dispatchUIQueueMessage() {
    // Give the UI a chance to catch up a little:
    final MessageQueue queue = Looper.getMainLooper().mQueue; // not public
    // Don't block if no messages are ready.
    if (queue.hasMessages(...)) {
        Message msg = queue.next(); // Isn't public. :-(
        msg.target.dispatchMessage(msg);
    }
}
</code>```

I'm basing this on the Looper source code, but I don't want to use undocumented features, since I wouldn't be able to rely on them. If there was a looper.dispatchNextMessageIfAny() method, that would be ideal.

Not a duplicate: Android - updating UI during intensive task? is similar, but that one is about updating the UI from a worker thread. That approach wouldn't work here, because only the UI thread can update the UI, and the UI thread is continuously occupied with its intensive task... unless it explicitly takes a moment to allow dispatching of the messages.

I realize that the recommended approach is to run the intensive task on a background thread, which should leave the UI thread free to update the UI when it needs to. And that is what I normally do, e.g. using new AsyncTasks and separate services. But that requires more control flow complexity (orchestration), passing control back after each task completes, and tracking state in order to determine which asynchronous task follows which.

This question is to investigate what options are available to do things on the UI thread, while allowing the UI to update sometimes. Knowing what the options are will help decide whether there are some cases where it's OK to do things on the UI thread. If the conclusion is no, then the answer to this question will help me know why I can be confident about investing my time in another direction.

答:
My app has an intensive task that I'm currently running on the UI thread

As name indicates UI thread is for UI. If you are doing heavy lifting on that thread, then definitely you are doing it wrong.

But that requires more control flow complexity (orchestration),

No. It just requires same amount of work you do with AsyncTask. Alternatively you can use RxJava. Or just simply EventBus. It's no more complex than normally.

passing control back after each task completes

Why you hand control to computation thread in first place? Control should stay on UI thread all the time.

Body:
My app has an intensive task that I'm currently running on the UI thread. It takes about 15 seconds. As such, I really need to update the UI at strategic points during the task, in order for the user (and the OS) not to think the app has crashed (stopped responding).

It seems like it might be possible to do something like this (pseudocode):

void longTaskOnUIThread() {
    // Here I'm maintaining the sequence of steps as a sequence of statements
    // in one method, despite letting the UI catch its breath between steps.
    doAChunkOfTheTask();
    dispatchUIQueueMessage();
    int result = doSecondChunkOfTheTask();
    if (result < 3) {
        dispatchUIQueueMessage();
        doThirdChunkOfTheTask();
    }
}

void dispatchUIQueueMessage() {
    // Give the UI a chance to catch up a little:
    final MessageQueue queue = Looper.getMainLooper().mQueue; // not public
    // Don't block if no messages are ready.
    if (queue.hasMessages(...)) {
        Message msg = queue.next(); // Isn't public. :-(
        msg.target.dispatchMessage(msg);
    }
}

I'm basing this on the Looper source code, but I don't want to use undocumented features, since I wouldn't be able to rely on them. If there was a looper.dispatchNextMessageIfAny() method, that would be ideal.

Not a duplicate: Android - updating UI during intensive task? is similar, but that one is about updating the UI from a worker thread. That approach wouldn't work here, because only the UI thread can update the UI, and the UI thread is continuously occupied with its intensive task... unless it explicitly takes a moment to allow dispatching of the messages.

I realize that the recommended approach is to run the intensive task on a background thread, which should leave the UI thread free to update the UI when it needs to. And that is what I normally do, e.g. using new AsyncTasks and separate services. But that requires more control flow complexity (orchestration), passing control back after each task completes, and tracking state in order to determine which asynchronous task follows which.

This question is to investigate what options are available to do things on the UI thread, while allowing the UI to update sometimes. Knowing what the options are will help decide whether there are some cases where it's OK to do things on the UI thread. If the conclusion is no, then the answer to this question will help me know why I can be confident about investing my time in another direction.


来源: stackexchange

问:
Implement RemoveAll on AsyncObservableCollection
I'm trying to implement the RemoveAll on AsyncObservableCollection, this class was created for edit the collection on another thread, the structure is this:

```<code>public class AsyncObservableCollection<T> : ObservableCollection<T>
{
    private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current;

    public AsyncObservableCollection()
    {
    }

    public AsyncObservableCollection(IEnumerable<T> list)
        : base(list)
    {
    }

    private void ExecuteOnSyncContext(Action action)
    {
        if (SynchronizationContext.Current == _synchronizationContext)
        {
            action();
        }
        else
        {
            _synchronizationContext.Send(_ => action(), null);
        }
    }

    protected override void InsertItem(int index, T item)
    {
        ExecuteOnSyncContext(() => base.InsertItem(index, item));
    }

    protected override void RemoveItem(int index)
    {
        ExecuteOnSyncContext(() => base.RemoveItem(index));
    }

    protected override void SetItem(int index, T item)
    {
        ExecuteOnSyncContext(() => base.SetItem(index, item));
    }

    protected override void MoveItem(int oldIndex, int newIndex)
    {
        ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex));
    }

    protected override void ClearItems()
    {
        ExecuteOnSyncContext(() => base.ClearItems());
    }

    public void RemoveAll(Predicate<T> predicate)
    {
        CheckReentrancy();

        List<T> itemsToRemove = Items.Where(x => predicate(x)).ToList();
        itemsToRemove.ForEach(item => Items.Remove(item));

        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}
</code>```

actually the method working well if the collection is used on the main thread, but if I use on a different thread I get:

Not Supported Exception

on this line:

```<code>OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
</code>```

there is something that I can do for fix this?

答:
I am not really sure the purpose of this class and why you need to keep the current context, but anyways the solution to your problem is

```<code>public class ObservableCollectionAsync<T> : ObservableCollection<T>
{
    public ObservableCollectionAsync()
    {
        BindingOperations.EnableCollectionSynchronization(this, _lock);
    }

    public ObservableCollectionAsync(List<T> list) : base(list)
    {
        BindingOperations.EnableCollectionSynchronization(this, _lock);
    }

    public ObservableCollectionAsync(IEnumerable<T> collection) : base(collection)
    {
        BindingOperations.EnableCollectionSynchronization(this, _lock);
    }
    private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current;
    private readonly object _lock = new object();
    private void ExecuteOnSyncContext(Action action)
    {
        if (SynchronizationContext.Current == _synchronizationContext)
        {
            action();
        }
        else
        {
            _synchronizationContext.Send(_ => action(), null);
        }
    }

    protected override void ClearItems()
    {
        ExecuteOnSyncContext(() => base.ClearItems());
    }

    protected override void InsertItem(int index, T item)
    {
        ExecuteOnSyncContext(() => base.InsertItem(index, item));
    }

    protected override void MoveItem(int oldIndex, int newIndex)
    {
        ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex));
    }

    protected override void RemoveItem(int index)
    {
        ExecuteOnSyncContext(() => base.RemoveItem(index));
    }

    protected override void SetItem(int index, T item)
    {

        ExecuteOnSyncContext(() => base.SetItem(index, item));

    }

    public void RemoveAll(Func<T,bool> predicate)
    {
        CheckReentrancy();
        foreach (var item in this.Where(predicate).ToArray())
        {
            this.Remove(item);
        }
    }
</code>```

But any of the other methods within the Observable Collection itself will not go through your "ExecuteOnSyncContext", so it may be better to just make it public and call it outside the class for the other methods.

Otherwise you'll need to build an Observable Collection using the ICollection interface.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement the RemoveAll on AsyncObservableCollection, this class was created for edit the collection on another thread, the structure is this:

public class AsyncObservableCollection<T> : ObservableCollection<T>
{
    private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current;

    public AsyncObservableCollection()
    {
    }

    public AsyncObservableCollection(IEnumerable<T> list)
        : base(list)
    {
    }

    private void ExecuteOnSyncContext(Action action)
    {
        if (SynchronizationContext.Current == _synchronizationContext)
        {
            action();
        }
        else
        {
            _synchronizationContext.Send(_ => action(), null);
        }
    }

    protected override void InsertItem(int index, T item)
    {
        ExecuteOnSyncContext(() => base.InsertItem(index, item));
    }

    protected override void RemoveItem(int index)
    {
        ExecuteOnSyncContext(() => base.RemoveItem(index));
    }

    protected override void SetItem(int index, T item)
    {
        ExecuteOnSyncContext(() => base.SetItem(index, item));
    }

    protected override void MoveItem(int oldIndex, int newIndex)
    {
        ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex));
    }

    protected override void ClearItems()
    {
        ExecuteOnSyncContext(() => base.ClearItems());
    }

    public void RemoveAll(Predicate<T> predicate)
    {
        CheckReentrancy();

        List<T> itemsToRemove = Items.Where(x => predicate(x)).ToList();
        itemsToRemove.ForEach(item => Items.Remove(item));

        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

actually the method working well if the collection is used on the main thread, but if I use on a different thread I get:

Not Supported Exception

on this line:

OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

there is something that I can do for fix this?

Body:
I am not really sure the purpose of this class and why you need to keep the current context, but anyways the solution to your problem is

public class ObservableCollectionAsync<T> : ObservableCollection<T>
{
    public ObservableCollectionAsync()
    {
        BindingOperations.EnableCollectionSynchronization(this, _lock);
    }

    public ObservableCollectionAsync(List<T> list) : base(list)
    {
        BindingOperations.EnableCollectionSynchronization(this, _lock);
    }

    public ObservableCollectionAsync(IEnumerable<T> collection) : base(collection)
    {
        BindingOperations.EnableCollectionSynchronization(this, _lock);
    }
    private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current;
    private readonly object _lock = new object();
    private void ExecuteOnSyncContext(Action action)
    {
        if (SynchronizationContext.Current == _synchronizationContext)
        {
            action();
        }
        else
        {
            _synchronizationContext.Send(_ => action(), null);
        }
    }

    protected override void ClearItems()
    {
        ExecuteOnSyncContext(() => base.ClearItems());
    }

    protected override void InsertItem(int index, T item)
    {
        ExecuteOnSyncContext(() => base.InsertItem(index, item));
    }

    protected override void MoveItem(int oldIndex, int newIndex)
    {
        ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex));
    }

    protected override void RemoveItem(int index)
    {
        ExecuteOnSyncContext(() => base.RemoveItem(index));
    }

    protected override void SetItem(int index, T item)
    {

        ExecuteOnSyncContext(() => base.SetItem(index, item));

    }

    public void RemoveAll(Func<T,bool> predicate)
    {
        CheckReentrancy();
        foreach (var item in this.Where(predicate).ToArray())
        {
            this.Remove(item);
        }
    }

But any of the other methods within the Observable Collection itself will not go through your "ExecuteOnSyncContext", so it may be better to just make it public and call it outside the class for the other methods.

Otherwise you'll need to build an Observable Collection using the ICollection interface.


问:
Fit flex parent cross-axis to items
Where the parent has display: flex; flex-direction: column, is it possible to make the parent's width expand to fit a flex item wider than the parent?

It's worth noting that the grandparent does not have display: flex nor a fixed width. It has a min-width: 100% though.

答:
Yes, you can, and by using inline-flex instead of flex, it will grow with the child.

The reason why the flex parent won't grow along with its child when using flex is because flex work similar to a block element, and block element won't grow larger than its parent, which inline element does.

This can be seen here, where the grand parent, with or w/o min-width: 100%, won't grow with its content, but the inline-flex will. This would also be the case if the flex element would instead have inline-block.

Still, the parent's content will overflow and effect its surroundings as if it would grow with content, and make the outer scroll to show up.

Why the parent with min-width is slightly wider is because of the padding not being included in its set width, so adding box-sizing: border-box; to its rule will make them equal wide.

Stack snippet

.parent {
  padding: 20px;
  background: yellow;
}

.parent.with-min-width {
  min-width: 100%;
}

.flex {
  display: inline-flex;
  flex-direction: column;
  background-color: red;
  padding: 20px;
}

.flex .item {
  width: 800px;
  padding: 20px;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="flex">
    <div class="item">
    </div>
  </div>
</div>

<div class="parent with-min-width">
  <div class="flex">
    <div class="item">
    </div>
  </div>
</div></code>```

Title: Fit flex parent cross-axis to items

Body:
Yes, you can, and by using inline-flex instead of flex, it will grow with the child.

The reason why the flex parent won't grow along with its child when using flex is because flex work similar to a block element, and block element won't grow larger than its parent, which inline element does.

This can be seen here, where the grand parent, with or w/o min-width: 100%, won't grow with its content, but the inline-flex will. This would also be the case if the flex element would instead have inline-block.

Still, the parent's content will overflow and effect its surroundings as if it would grow with content, and make the outer scroll to show up.

Why the parent with min-width is slightly wider is because of the padding not being included in its set width, so adding box-sizing: border-box; to its rule will make them equal wide.

Stack snippet

.parent {
  padding: 20px;
  background: yellow;
}

.parent.with-min-width {
  min-width: 100%;
}

.flex {
  display: inline-flex;
  flex-direction: column;
  background-color: red;
  padding: 20px;
}

.flex .item {
  width: 800px;
  padding: 20px;
  background-color: blue;
}

<div class="parent">
  <div class="flex">
    <div class="item">
    </div>
  </div>
</div>

<div class="parent with-min-width">
  <div class="flex">
    <div class="item">
    </div>
  </div>
</div>


问:
Android Studio, My Activities are going to the wrong activity
so I am a fresh face to android development, and I encountered a problem which I have been going loops for.

I have three activities here, they are for registration,  I don't want to implement scrollview because it isn't that good looking so I made it to three form activities,

The first activity gathers all info from the XML's and passes the values as via intent to the second activity,
then the second activity gathers all info from it's own XML, and then passes it together with the Extra of the first activity to the third activity, and the third activity together with the first and seconds Extras PLUS it's own values from it's own XML's, finally, saves the values to firebase.

Yes the values get's saved, but my problem is the third activity doesn't go to the Welcome class which is supposedly written on its intent. I tried rebuilding and cleaning but it did not work. I couldn't find the bug to my work, can anyone help me out? any help is appreciated. Thanks

Here are my three java classes, and I will also put in the welcome class incase you might want to ask for it:

Profile.java

```<code>public class Profile extends Activity {

    //DECLARE FIELDS

    EditText name,username, phone, age, birth;
    Button  saveBtn;

    //FIREBASE REF
    DatabaseReference userRef;

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

        //FIREBASE DATABASE REF
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        //ASSIGN ID's
        saveBtn = (Button) findViewById(R.id.profileBtn);
        name = (EditText) findViewById(R.id.profileName);
        username = (EditText) findViewById(R.id.profileUsername);
        age = (EditText) findViewById(R.id.profileAge);
        phone = (EditText) findViewById(R.id.profilePhone);
        birth = (EditText) findViewById(R.id.profileBirth);

        // SAVE BUTTON LOGIC

       saveBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                addUser();

            }
        });
    }

    private void addUser(){

        String userNameString = name.getText().toString();
        String userPhoneString  = phone.getText().toString();
        String userAgeString  = age.getText().toString();
        String userBirthString = birth.getText().toString();
        String userUserNameString = username.getText().toString();

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");
        String userPass = getIntent().getStringExtra("USER_PASS");
        String userID = getIntent().getStringExtra("USER_ID");

        if (!TextUtils.isEmpty(userNameString) && !TextUtils.isEmpty(userPhoneString) && !TextUtils.isEmpty(userAgeString) && !TextUtils.isEmpty(userBirthString) && !TextUtils.isEmpty(userUserNameString)) {

            Toast.makeText(Profile.this, "Next!", Toast.LENGTH_LONG).show();
            Intent myIntent  = new Intent(Profile.this, Profile2.class);
            myIntent.putExtra("USER_KEY", userKey);
            myIntent.putExtra("USER_NAME", userNameString);
            myIntent.putExtra("USER_PHONE", userPhoneString);
            myIntent.putExtra("USER_AGE", userAgeString);
            myIntent.putExtra("USER_BIRTH", userBirthString);
            myIntent.putExtra("USER_USERNAME", userUserNameString);
            myIntent.putExtra("USER_EMAIL", userEmail);
            myIntent.putExtra("USER_PASS", userPass);
            myIntent.putExtra("USER_ID", userID);

            startActivity(myIntent);

        } else {
            Toast.makeText(Profile.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Profile.this, Profile.class));

        }
    }

}
</code>```

Profile2.java

```<code>public class Profile2 extends Activity {

    //DECLARE FIELDS

    EditText Address, FSN, bType, Height, Weight;
    Button saveBtn;

    //FIREBASE REF
    DatabaseReference userRef;

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

        //FIREBASE DATABASE REF
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        //ASSIGN ID's
        saveBtn = (Button) findViewById(R.id.profileBtn);
        Address = (EditText) findViewById(R.id.Address);
        FSN = (EditText) findViewById(R.id.FSN);
        bType = (EditText) findViewById(R.id.bType);
        Height = (EditText) findViewById(R.id.Height);
        Weight = (EditText) findViewById(R.id.Weight);

        //MOVE TO LOGIN

        // SAVE BUTTON LOGIC

        saveBtn.setOnClickListener(new View.OnClickListener() {
            // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View view) {

                addUser();
            }
        });
    }

    private void addUser(){

        String AddressString = Address.getText().toString();
        String FSNString  = FSN.getText().toString();
        String WeightString = Weight.getText().toString();
        String bTypeString  = bType.getText().toString();
        String HeightString = Height.getText().toString();

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userNameString = getIntent().getStringExtra("USER_NAME");
        String userPhoneString = getIntent().getStringExtra("USER_PHONE");
        String userAgeString = getIntent().getStringExtra("USER_AGE");
        String userBirthString = getIntent().getStringExtra("USER_BIRTH");
        String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
        String userPass = getIntent().getStringExtra("USER_PASS");
        String userID = getIntent().getStringExtra("USER_ID");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");

        if (!TextUtils.isEmpty(AddressString) && !TextUtils.isEmpty(FSNString) && !TextUtils.isEmpty(WeightString) && !TextUtils.isEmpty(bTypeString) && !TextUtils.isEmpty(HeightString)) {

            Toast.makeText(Profile2.this, "Go mamshie!", Toast.LENGTH_LONG).show();

            Intent myIntent2  = new Intent(Profile2.this, Profile3.class);
            myIntent2.putExtra("USER_KEY", userKey);
            myIntent2.putExtra("USER_NAME", userNameString);
            myIntent2.putExtra("USER_PHONE", userPhoneString);
            myIntent2.putExtra("USER_AGE", userAgeString);
            myIntent2.putExtra("USER_BIRTH", userBirthString);
            myIntent2.putExtra("USER_USERNAME", userUserNameString);
            myIntent2.putExtra("USER_ADDRESS", AddressString);
            myIntent2.putExtra("USER_FSN", FSNString);
            myIntent2.putExtra("USER_BTYPE", bTypeString);
            myIntent2.putExtra("USER_HEIGHT", HeightString);
            myIntent2.putExtra("USER_WEIGHT", WeightString);
            myIntent2.putExtra("USER_PASS", userPass);
            myIntent2.putExtra("USER_ID", userID);
            myIntent2.putExtra("USER_EMAIL", userEmail);
            startActivity(myIntent2);

        } else {
            Toast.makeText(Profile2.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Profile2.this, Profile2.class));

        }
    }

}
</code>```

Profile3.java

```<code>public class Profile3 extends Activity {

    //DECLARE FIELDS

    EditText NPP, PCS, MC, SB, PPH;
    Button saveBtn;

    //FIREBASE REF
    DatabaseReference mDataRef, userRef;

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

        //FIREBASE DATABASE REF
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        //ASSIGN ID's
        saveBtn = (Button) findViewById(R.id.profileBtn);
        NPP = (EditText) findViewById(R.id.previous);
        PCS = (EditText) findViewById(R.id.previouscs);
        MC = (EditText) findViewById(R.id.miscar);
        SB = (EditText) findViewById(R.id.stillbirth);
        PPH = (EditText) findViewById(R.id.post);

        //MOVE TO LOGIN

        // SAVE BUTTON LOGIC

        saveBtn.setOnClickListener(new View.OnClickListener() {
            // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View view) {

                addUser();
            }
        });
    }

    private void addUser(){

        String NoPrevPregnancies = NPP.getText().toString();
        String PreviousCS  = PCS.getText().toString();
        String Miscarriages = MC.getText().toString();
        String Stillbirth  = SB.getText().toString();
        String PostPartumHem = PPH.getText().toString();

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");
        String userPass = getIntent().getStringExtra("USER_PASSWORD");
        String userID = getIntent().getStringExtra("USER_ID");
        String userNameString = getIntent().getStringExtra("USER_NAME");
        String userPhoneString = getIntent().getStringExtra("USER_PHONE");
        String userAgeString = getIntent().getStringExtra("USER_AGE");
        String userBirthString = getIntent().getStringExtra("USER_BIRTH");
        String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
        String AddressString = getIntent().getStringExtra("USER_ADDRESS");
        String FSNString = getIntent().getStringExtra("USER_FSN");
        String bTypeString = getIntent().getStringExtra("USER_BTYPE");
        String HeightString = getIntent().getStringExtra("USER_HEIGHT");
        String WeightString = getIntent().getStringExtra("USER_WEIGHT");

        mDataRef = userRef.child(userNameString);

        if (!TextUtils.isEmpty(PreviousCS) && !TextUtils.isEmpty(NoPrevPregnancies) && !TextUtils.isEmpty(PostPartumHem) && !TextUtils.isEmpty(Miscarriages) && !TextUtils.isEmpty(Stillbirth)) {

            User3 user = new User3(PreviousCS, NoPrevPregnancies, PostPartumHem, Miscarriages, Stillbirth);

            userRef.child(userNameString).setValue(user);
            mDataRef.child("USER_KEY").setValue(userKey);
            mDataRef.child("USER_PASS").setValue(userPass);//
            mDataRef.child("USER_ID").setValue(userID);//
            mDataRef.child("USER_NAME").setValue(userNameString);//
            mDataRef.child("USER_PHONE").setValue(userPhoneString);
            mDataRef.child("USER_AGE").setValue(userAgeString);
            mDataRef.child("USER_BIRTH").setValue(userBirthString);
            mDataRef.child("USER_USERNAME").setValue(userUserNameString);//
            mDataRef.child("USER_ADDRESS").setValue(AddressString);
            mDataRef.child("USER_FSN").setValue(FSNString);
            mDataRef.child("USER_BTYPE").setValue(bTypeString);
            mDataRef.child("USER_HEIGHT").setValue(HeightString);
            mDataRef.child("USER_WEIGHT").setValue(WeightString);
            mDataRef.child("USER_EMAIL").setValue(userEmail);//

            Toast.makeText(Profile3.this, "User Details Completed and Saved!", Toast.LENGTH_LONG).show();
            Intent myIntent1  = new Intent(Profile3.this, Welcome.class);

            myIntent1.putExtra("USER_KEY", userKey);
            myIntent1.putExtra("USER_EMAIL", userEmail);
            myIntent1.putExtra("USER_PHONE", userPhoneString);
            myIntent1.putExtra("USER_BIRTH", userBirthString);
            myIntent1.putExtra("USER_USERNAME", userUserNameString);
            myIntent1.putExtra("USER_NAME", userNameString);
            myIntent1.putExtra("USER_AGE", userAgeString);
            myIntent1.putExtra("USER_ID", userID);

            startActivity(myIntent1);

        } else {

            Toast.makeText(Profile3.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Profile3.this, Profile3.class));

        }
    }

}
</code>```

My welcome activity which gets some data and shows it

```<code>public class Welcome extends AppCompatActivity {

    private static final String TAG = "ViewDatabase";
    //ADD FIREBASE STUFF

    //DECLARE FIELDS
    Button outBtn;
    TextView welcome;
    private DatabaseReference myRef, mDataRef, userRef;
    private FirebaseDatabase mFirebaseDatabase;
    private String userIDPassed;
    private String userID;
    private String userKey;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    private ListView mListView;

    //FIREBASE AUTH FIELDS
    private FirebaseAuth nAuth;
    private FirebaseAuth.AuthStateListener nAuthlistener;

    //GET USER KEY  FROM INTENT

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

        //DRAWER LAYOUT
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);

        //ASSIGN IDS
        outBtn = (Button) findViewById(R.id.logoutBtn);
        welcome = (TextView) findViewById(R.id.WelcomeName);
        mListView = (ListView) findViewById(R.id.listview);

        //ASSIGN INSTANCE
        myRef = FirebaseDatabase.getInstance().getReference().child("Users");
        nAuth = FirebaseAuth.getInstance();
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        FirebaseUser User = nAuth.getCurrentUser();
        userID = User.getUid();

//navigation Drawer
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
            @Override public boolean onNavigationItemSelected(MenuItem menuItem)
            { switch (menuItem.getItemId())
            {
                case(R.id.nav_account): Intent accountActivity = new Intent(getApplicationContext(), Welcome.class);
                    startActivity(accountActivity);
                    break;

                case(R.id.nav_exercises): Intent accountActivity1 = new Intent(getApplicationContext(), Video.class);
                    startActivity(accountActivity1);
                    break;

                case(R.id.nav_tips): Intent accountActivity2 = new Intent(getApplicationContext(), Image.class);
                    startActivity(accountActivity2);
                    break;

                case(R.id.nav_scheduler): Intent accountActivity3 = new Intent(getApplicationContext(), CalendarActivity.class);
                    startActivity(accountActivity3);
                    break;
                case(R.id.nav_logout): Intent accountActivity4 = new Intent(getApplicationContext(), LoginActivity.class);
                    startActivity(accountActivity4);
                    finish();
                    break;
                case(R.id.nav_settings): Intent accountActivity5 = new Intent(getApplicationContext(), Profile.class);
                    startActivity(accountActivity5);
                    break;
                case(R.id.nav_info): Intent accountActivity6 = new Intent(getApplicationContext(), Info.class);
                    startActivity(accountActivity6);
                    break;
            }
            return true;
            } });

        //Navigation Drawer

        nAuthlistener = new FirebaseAuth.AuthStateListener(){
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser User = firebaseAuth.getCurrentUser();

                if (User != null){

                    Log.d(TAG, "onAuthStateChanged:signed_in:" + User.getUid());
                    Toast.makeText(Welcome.this, "Successfully signed in with: " + User.getEmail(), Toast.LENGTH_LONG).show();

                }else{

                    Log.d(TAG, "onAuthStateChanged:signed_out" + userID);
                    Toast.makeText(Welcome.this, "Successfully signed out.", Toast.LENGTH_LONG).show();
                }

            }

        };

        myRef.addListenerForSingleValueEvent(new ValueEventListener() {

                    @Override
                    public void onDataChange (DataSnapshot dataSnapshot){
                        showData(dataSnapshot);
                    }

                    @Override
                    public void onCancelled (DatabaseError databaseError){

                    }

        });

        outBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nAuth.signOut();
                finish();
                startActivity(new Intent(Welcome.this, MainActivity.class));
            }
        });
    }

    private void showData(DataSnapshot dataSnapshot) {

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");
        String  userPhone = getIntent().getStringExtra("USER_PHONE");
        String userBirth = getIntent().getStringExtra("USER_BIRTH");
        String  userUserName = getIntent().getStringExtra("USER_USERNAME");
        String userName = getIntent().getStringExtra("USER_NAME");
        String userAge = getIntent().getStringExtra("USER_AGE");
        String userID = getIntent().getStringExtra("USER_ID");

        mDataRef = userRef.child(userName);

        if (!TextUtils.isEmpty(userKey) && !TextUtils.isEmpty(userEmail) && !TextUtils.isEmpty(userID) && !TextUtils.isEmpty(userBirth) && !TextUtils.isEmpty(userUserName)) {

            for(DataSnapshot ds : dataSnapshot.getChildren()){

                Log.d(TAG, "showData: snapshot: " + ds);
                Log.d(TAG, "showData: snapshot: " + ds.child("Users"));

                //display all info taken

                Log.d(TAG, "showData: USER_NAME: " + userName);
                Log.d(TAG, "showData: USER_AGE: " + userAge);
                Log.d(TAG, "showData: USER_BIRTH: " + userBirth);
                Log.d(TAG, "showData: USER_PHONE: " + userPhone);
                Log.d(TAG, "showData: USER_USERNAME: " + userUserName);

                ArrayList<String> array = new ArrayList<>();
                array.add(userName);
                array.add(userAge);
                array.add(userBirth);
                array.add(userPhone);
                array.add(userUserName);
                ArrayAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,array);
                mListView.setAdapter(adapter);

            }

        } else {

        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        nAuth.addAuthStateListener(nAuthlistener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        nAuth.removeAuthStateListener(nAuthlistener);
    }

    //FOR NAVIGATION DRAWER

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

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

    }
    //Navigation Drawer End

}
</code>```

What did I do wrong? Thinking of it as flowing water, I think the values flowed well until the last activity?

答: Try debugging by removing your else statements and maybe add them all to the last activity</p>

Body:
so I am a fresh face to android development, and I encountered a problem which I have been going loops for.

I have three activities here, they are for registration,  I don't want to implement scrollview because it isn't that good looking so I made it to three form activities,

The first activity gathers all info from the XML's and passes the values as via intent to the second activity,
then the second activity gathers all info from it's own XML, and then passes it together with the Extra of the first activity to the third activity, and the third activity together with the first and seconds Extras PLUS it's own values from it's own XML's, finally, saves the values to firebase.

Yes the values get's saved, but my problem is the third activity doesn't go to the Welcome class which is supposedly written on its intent. I tried rebuilding and cleaning but it did not work. I couldn't find the bug to my work, can anyone help me out? any help is appreciated. Thanks

Here are my three java classes, and I will also put in the welcome class incase you might want to ask for it:

Profile.java

public class Profile extends Activity {

    //DECLARE FIELDS

    EditText name,username, phone, age, birth;
    Button  saveBtn;

    //FIREBASE REF
    DatabaseReference userRef;

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

        //FIREBASE DATABASE REF
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        //ASSIGN ID's
        saveBtn = (Button) findViewById(R.id.profileBtn);
        name = (EditText) findViewById(R.id.profileName);
        username = (EditText) findViewById(R.id.profileUsername);
        age = (EditText) findViewById(R.id.profileAge);
        phone = (EditText) findViewById(R.id.profilePhone);
        birth = (EditText) findViewById(R.id.profileBirth);

        // SAVE BUTTON LOGIC

       saveBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                addUser();

            }
        });
    }

    private void addUser(){

        String userNameString = name.getText().toString();
        String userPhoneString  = phone.getText().toString();
        String userAgeString  = age.getText().toString();
        String userBirthString = birth.getText().toString();
        String userUserNameString = username.getText().toString();

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");
        String userPass = getIntent().getStringExtra("USER_PASS");
        String userID = getIntent().getStringExtra("USER_ID");

        if (!TextUtils.isEmpty(userNameString) && !TextUtils.isEmpty(userPhoneString) && !TextUtils.isEmpty(userAgeString) && !TextUtils.isEmpty(userBirthString) && !TextUtils.isEmpty(userUserNameString)) {

            Toast.makeText(Profile.this, "Next!", Toast.LENGTH_LONG).show();
            Intent myIntent  = new Intent(Profile.this, Profile2.class);
            myIntent.putExtra("USER_KEY", userKey);
            myIntent.putExtra("USER_NAME", userNameString);
            myIntent.putExtra("USER_PHONE", userPhoneString);
            myIntent.putExtra("USER_AGE", userAgeString);
            myIntent.putExtra("USER_BIRTH", userBirthString);
            myIntent.putExtra("USER_USERNAME", userUserNameString);
            myIntent.putExtra("USER_EMAIL", userEmail);
            myIntent.putExtra("USER_PASS", userPass);
            myIntent.putExtra("USER_ID", userID);

            startActivity(myIntent);

        } else {
            Toast.makeText(Profile.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Profile.this, Profile.class));

        }
    }

}

Profile2.java

public class Profile2 extends Activity {

    //DECLARE FIELDS

    EditText Address, FSN, bType, Height, Weight;
    Button saveBtn;

    //FIREBASE REF
    DatabaseReference userRef;

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

        //FIREBASE DATABASE REF
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        //ASSIGN ID's
        saveBtn = (Button) findViewById(R.id.profileBtn);
        Address = (EditText) findViewById(R.id.Address);
        FSN = (EditText) findViewById(R.id.FSN);
        bType = (EditText) findViewById(R.id.bType);
        Height = (EditText) findViewById(R.id.Height);
        Weight = (EditText) findViewById(R.id.Weight);

        //MOVE TO LOGIN

        // SAVE BUTTON LOGIC

        saveBtn.setOnClickListener(new View.OnClickListener() {
            // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View view) {

                addUser();
            }
        });
    }

    private void addUser(){

        String AddressString = Address.getText().toString();
        String FSNString  = FSN.getText().toString();
        String WeightString = Weight.getText().toString();
        String bTypeString  = bType.getText().toString();
        String HeightString = Height.getText().toString();

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userNameString = getIntent().getStringExtra("USER_NAME");
        String userPhoneString = getIntent().getStringExtra("USER_PHONE");
        String userAgeString = getIntent().getStringExtra("USER_AGE");
        String userBirthString = getIntent().getStringExtra("USER_BIRTH");
        String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
        String userPass = getIntent().getStringExtra("USER_PASS");
        String userID = getIntent().getStringExtra("USER_ID");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");

        if (!TextUtils.isEmpty(AddressString) && !TextUtils.isEmpty(FSNString) && !TextUtils.isEmpty(WeightString) && !TextUtils.isEmpty(bTypeString) && !TextUtils.isEmpty(HeightString)) {

            Toast.makeText(Profile2.this, "Go mamshie!", Toast.LENGTH_LONG).show();

            Intent myIntent2  = new Intent(Profile2.this, Profile3.class);
            myIntent2.putExtra("USER_KEY", userKey);
            myIntent2.putExtra("USER_NAME", userNameString);
            myIntent2.putExtra("USER_PHONE", userPhoneString);
            myIntent2.putExtra("USER_AGE", userAgeString);
            myIntent2.putExtra("USER_BIRTH", userBirthString);
            myIntent2.putExtra("USER_USERNAME", userUserNameString);
            myIntent2.putExtra("USER_ADDRESS", AddressString);
            myIntent2.putExtra("USER_FSN", FSNString);
            myIntent2.putExtra("USER_BTYPE", bTypeString);
            myIntent2.putExtra("USER_HEIGHT", HeightString);
            myIntent2.putExtra("USER_WEIGHT", WeightString);
            myIntent2.putExtra("USER_PASS", userPass);
            myIntent2.putExtra("USER_ID", userID);
            myIntent2.putExtra("USER_EMAIL", userEmail);
            startActivity(myIntent2);

        } else {
            Toast.makeText(Profile2.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Profile2.this, Profile2.class));

        }
    }

}

Profile3.java

public class Profile3 extends Activity {

    //DECLARE FIELDS

    EditText NPP, PCS, MC, SB, PPH;
    Button saveBtn;

    //FIREBASE REF
    DatabaseReference mDataRef, userRef;

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

        //FIREBASE DATABASE REF
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        //ASSIGN ID's
        saveBtn = (Button) findViewById(R.id.profileBtn);
        NPP = (EditText) findViewById(R.id.previous);
        PCS = (EditText) findViewById(R.id.previouscs);
        MC = (EditText) findViewById(R.id.miscar);
        SB = (EditText) findViewById(R.id.stillbirth);
        PPH = (EditText) findViewById(R.id.post);

        //MOVE TO LOGIN

        // SAVE BUTTON LOGIC

        saveBtn.setOnClickListener(new View.OnClickListener() {
            // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View view) {

                addUser();
            }
        });
    }

    private void addUser(){

        String NoPrevPregnancies = NPP.getText().toString();
        String PreviousCS  = PCS.getText().toString();
        String Miscarriages = MC.getText().toString();
        String Stillbirth  = SB.getText().toString();
        String PostPartumHem = PPH.getText().toString();

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");
        String userPass = getIntent().getStringExtra("USER_PASSWORD");
        String userID = getIntent().getStringExtra("USER_ID");
        String userNameString = getIntent().getStringExtra("USER_NAME");
        String userPhoneString = getIntent().getStringExtra("USER_PHONE");
        String userAgeString = getIntent().getStringExtra("USER_AGE");
        String userBirthString = getIntent().getStringExtra("USER_BIRTH");
        String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
        String AddressString = getIntent().getStringExtra("USER_ADDRESS");
        String FSNString = getIntent().getStringExtra("USER_FSN");
        String bTypeString = getIntent().getStringExtra("USER_BTYPE");
        String HeightString = getIntent().getStringExtra("USER_HEIGHT");
        String WeightString = getIntent().getStringExtra("USER_WEIGHT");

        mDataRef = userRef.child(userNameString);

        if (!TextUtils.isEmpty(PreviousCS) && !TextUtils.isEmpty(NoPrevPregnancies) && !TextUtils.isEmpty(PostPartumHem) && !TextUtils.isEmpty(Miscarriages) && !TextUtils.isEmpty(Stillbirth)) {

            User3 user = new User3(PreviousCS, NoPrevPregnancies, PostPartumHem, Miscarriages, Stillbirth);

            userRef.child(userNameString).setValue(user);
            mDataRef.child("USER_KEY").setValue(userKey);
            mDataRef.child("USER_PASS").setValue(userPass);//
            mDataRef.child("USER_ID").setValue(userID);//
            mDataRef.child("USER_NAME").setValue(userNameString);//
            mDataRef.child("USER_PHONE").setValue(userPhoneString);
            mDataRef.child("USER_AGE").setValue(userAgeString);
            mDataRef.child("USER_BIRTH").setValue(userBirthString);
            mDataRef.child("USER_USERNAME").setValue(userUserNameString);//
            mDataRef.child("USER_ADDRESS").setValue(AddressString);
            mDataRef.child("USER_FSN").setValue(FSNString);
            mDataRef.child("USER_BTYPE").setValue(bTypeString);
            mDataRef.child("USER_HEIGHT").setValue(HeightString);
            mDataRef.child("USER_WEIGHT").setValue(WeightString);
            mDataRef.child("USER_EMAIL").setValue(userEmail);//

            Toast.makeText(Profile3.this, "User Details Completed and Saved!", Toast.LENGTH_LONG).show();
            Intent myIntent1  = new Intent(Profile3.this, Welcome.class);

            myIntent1.putExtra("USER_KEY", userKey);
            myIntent1.putExtra("USER_EMAIL", userEmail);
            myIntent1.putExtra("USER_PHONE", userPhoneString);
            myIntent1.putExtra("USER_BIRTH", userBirthString);
            myIntent1.putExtra("USER_USERNAME", userUserNameString);
            myIntent1.putExtra("USER_NAME", userNameString);
            myIntent1.putExtra("USER_AGE", userAgeString);
            myIntent1.putExtra("USER_ID", userID);

            startActivity(myIntent1);

        } else {

            Toast.makeText(Profile3.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Profile3.this, Profile3.class));

        }
    }

}

My welcome activity which gets some data and shows it

public class Welcome extends AppCompatActivity {

    private static final String TAG = "ViewDatabase";
    //ADD FIREBASE STUFF

    //DECLARE FIELDS
    Button outBtn;
    TextView welcome;
    private DatabaseReference myRef, mDataRef, userRef;
    private FirebaseDatabase mFirebaseDatabase;
    private String userIDPassed;
    private String userID;
    private String userKey;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    private ListView mListView;

    //FIREBASE AUTH FIELDS
    private FirebaseAuth nAuth;
    private FirebaseAuth.AuthStateListener nAuthlistener;

    //GET USER KEY  FROM INTENT

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

        //DRAWER LAYOUT
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);

        //ASSIGN IDS
        outBtn = (Button) findViewById(R.id.logoutBtn);
        welcome = (TextView) findViewById(R.id.WelcomeName);
        mListView = (ListView) findViewById(R.id.listview);

        //ASSIGN INSTANCE
        myRef = FirebaseDatabase.getInstance().getReference().child("Users");
        nAuth = FirebaseAuth.getInstance();
        userRef = FirebaseDatabase.getInstance().getReference("Users");

        FirebaseUser User = nAuth.getCurrentUser();
        userID = User.getUid();

//navigation Drawer
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
            @Override public boolean onNavigationItemSelected(MenuItem menuItem)
            { switch (menuItem.getItemId())
            {
                case(R.id.nav_account): Intent accountActivity = new Intent(getApplicationContext(), Welcome.class);
                    startActivity(accountActivity);
                    break;

                case(R.id.nav_exercises): Intent accountActivity1 = new Intent(getApplicationContext(), Video.class);
                    startActivity(accountActivity1);
                    break;

                case(R.id.nav_tips): Intent accountActivity2 = new Intent(getApplicationContext(), Image.class);
                    startActivity(accountActivity2);
                    break;

                case(R.id.nav_scheduler): Intent accountActivity3 = new Intent(getApplicationContext(), CalendarActivity.class);
                    startActivity(accountActivity3);
                    break;
                case(R.id.nav_logout): Intent accountActivity4 = new Intent(getApplicationContext(), LoginActivity.class);
                    startActivity(accountActivity4);
                    finish();
                    break;
                case(R.id.nav_settings): Intent accountActivity5 = new Intent(getApplicationContext(), Profile.class);
                    startActivity(accountActivity5);
                    break;
                case(R.id.nav_info): Intent accountActivity6 = new Intent(getApplicationContext(), Info.class);
                    startActivity(accountActivity6);
                    break;
            }
            return true;
            } });

        //Navigation Drawer

        nAuthlistener = new FirebaseAuth.AuthStateListener(){
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser User = firebaseAuth.getCurrentUser();

                if (User != null){

                    Log.d(TAG, "onAuthStateChanged:signed_in:" + User.getUid());
                    Toast.makeText(Welcome.this, "Successfully signed in with: " + User.getEmail(), Toast.LENGTH_LONG).show();

                }else{

                    Log.d(TAG, "onAuthStateChanged:signed_out" + userID);
                    Toast.makeText(Welcome.this, "Successfully signed out.", Toast.LENGTH_LONG).show();
                }

            }

        };

        myRef.addListenerForSingleValueEvent(new ValueEventListener() {

                    @Override
                    public void onDataChange (DataSnapshot dataSnapshot){
                        showData(dataSnapshot);
                    }

                    @Override
                    public void onCancelled (DatabaseError databaseError){

                    }

        });

        outBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nAuth.signOut();
                finish();
                startActivity(new Intent(Welcome.this, MainActivity.class));
            }
        });
    }

    private void showData(DataSnapshot dataSnapshot) {

        //GET USER KEY  FROM INTENT
        String userKey = getIntent().getStringExtra("USER_KEY");
        String userEmail = getIntent().getStringExtra("USER_EMAIL");
        String  userPhone = getIntent().getStringExtra("USER_PHONE");
        String userBirth = getIntent().getStringExtra("USER_BIRTH");
        String  userUserName = getIntent().getStringExtra("USER_USERNAME");
        String userName = getIntent().getStringExtra("USER_NAME");
        String userAge = getIntent().getStringExtra("USER_AGE");
        String userID = getIntent().getStringExtra("USER_ID");

        mDataRef = userRef.child(userName);

        if (!TextUtils.isEmpty(userKey) && !TextUtils.isEmpty(userEmail) && !TextUtils.isEmpty(userID) && !TextUtils.isEmpty(userBirth) && !TextUtils.isEmpty(userUserName)) {

            for(DataSnapshot ds : dataSnapshot.getChildren()){

                Log.d(TAG, "showData: snapshot: " + ds);
                Log.d(TAG, "showData: snapshot: " + ds.child("Users"));

                //display all info taken

                Log.d(TAG, "showData: USER_NAME: " + userName);
                Log.d(TAG, "showData: USER_AGE: " + userAge);
                Log.d(TAG, "showData: USER_BIRTH: " + userBirth);
                Log.d(TAG, "showData: USER_PHONE: " + userPhone);
                Log.d(TAG, "showData: USER_USERNAME: " + userUserName);

                ArrayList<String> array = new ArrayList<>();
                array.add(userName);
                array.add(userAge);
                array.add(userBirth);
                array.add(userPhone);
                array.add(userUserName);
                ArrayAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,array);
                mListView.setAdapter(adapter);

            }

        } else {

        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        nAuth.addAuthStateListener(nAuthlistener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        nAuth.removeAuthStateListener(nAuthlistener);
    }

    //FOR NAVIGATION DRAWER

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

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

    }
    //Navigation Drawer End

}

What did I do wrong? Thinking of it as flowing water, I think the values flowed well until the last activity?


问:
Random fetch from core data

I have n number of object of an entity.

I want to fetch 30, random object from the same entity.

I'm using core data, swift 3. Could anybody help me to solve this problem?

Thanks,

答:
This is going to require an extra step, because Core Data doesn't have any built-in support for a random selection. You'll need to have some unique attribute, select your own random subset of values for that attribute, and then get the managed objects with those values.

First, you need a managed object property that has unique values. Any property will do, but numeric properties will work faster. Let's say for example you have an integer property called myUniqueID that has unique values.

Do a fetch request to get all current values of this property. You only want values of this specific property, so set the fetch result type to NSFetchRequestResultType.dictionaryResultType and set the fetch request's propertiesToFetch to include only myUniqueID. The result will be an array of dictionaries, each containing a single value of myUniqueID.

Add your own logic to choose 30 random values from this result. Collect them in an array.

Do a second fetch request, this time fetching managed objects instead of dictionaries. If your array of random IDs is called uniqueIDArray, use a predicate of something like NSPredicate(format: "myUniqueID in %@", uniqueIDArray)

Title: Random fetch from core data


问:
How to convert NSString to NSArray in Objective C
I need to convert NSString to NSArray. if, few objects contains double quotes, few objects are doesn't contain anything.

```<code>NSString *string = @"["Line", "Operations(UK)", "Operations(USA)", "Total of Invoice", "", "Star", "10040101", "31.Jan.2001", "31.Jan.2001", "", "USD", "1653", "28,145.00", 163.48, "Stock, Ms.Pat", "MGR", "14.Nov.2006", "01-000-2210-0000-000", "V1- New York City", 20343, 5]";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];
</code>```

I have tried to convert using replacing characters like [, ", ] and did "componentsSeparatedByString:" with comma. but its not working properly.

答:
I will give you solution with example.I tried this.I got the solution.

```<code>NSString *strJson=@"{\"name\":{\"dob\":88,\"age\":61},\"family\" : [{\"location\":\"us\",\"mobile\":\"mobile\"}]}";
NSData *data = [strJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",dict);
</code>```

The output result is

Body:
I need to convert NSString to NSArray. if, few objects contains double quotes, few objects are doesn't contain anything.

NSString *string = @"["Line", "Operations(UK)", "Operations(USA)", "Total of Invoice", "", "Star", "10040101", "31.Jan.2001", "31.Jan.2001", "", "USD", "1653", "28,145.00", 163.48, "Stock, Ms.Pat", "MGR", "14.Nov.2006", "01-000-2210-0000-000", "V1- New York City", 20343, 5]";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];

I have tried to convert using replacing characters like [, ", ] and did "componentsSeparatedByString:" with comma. but its not working properly.

Body:
I will give you solution with example.I tried this.I got the solution.

NSString *strJson=@"{\"name\":{\"dob\":88,\"age\":61},\"family\" : [{\"location\":\"us\",\"mobile\":\"mobile\"}]}";
NSData *data = [strJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",dict);

The output result is


问:
Need example of cross origin request from angular js
Have a question that I hope can be answered simply.

I have an application on server xxx.yyy.com written in angular.js.  It accesses data, via HTTP/JSONP requests, on server abc.def.com.

I want allow my data server to support POST requests from other servers.

In developing this capability, I want to prove out the process where I replace the JSONP request with a POST request.  Am now getting CORS errors.  I understand what is happening here but I can not figure out a way fix the problem.

In this sample code, on xxx.yyy.com I make this request:

```<code>kaunasAPI.simPost = function(meter_data)
    {
    URL = 'http://abc.def.com/models/ajx_reading.php';
    return $http({
    method: 'POST',
    data: meter_data,
    url: URL
        });
    }
</code>```

On the server abc.def.com I have the following code:

```<code><?php

    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $json = json_encode($jTableResult);
    exit ( $json  );
    }

?>
</code>```

What am I missing to make this work?
Thanks in advance.

答:
Turns out I have been looking for answer on the wrong side, i.e. angular side.

Answer was to add a line to the server code. and the code is now:

```<code><?php
        {
    header("Access-Control-Allow-Origin: *");       //Fixes cross origin issue
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $json = json_encode($jTableResult);
    exit ( $json  );
    }

?>
</code>```

Body:
Have a question that I hope can be answered simply.

I have an application on server xxx.yyy.com written in angular.js.  It accesses data, via HTTP/JSONP requests, on server abc.def.com.

I want allow my data server to support POST requests from other servers.

In developing this capability, I want to prove out the process where I replace the JSONP request with a POST request.  Am now getting CORS errors.  I understand what is happening here but I can not figure out a way fix the problem.

In this sample code, on xxx.yyy.com I make this request:

kaunasAPI.simPost = function(meter_data)
    {
    URL = 'http://abc.def.com/models/ajx_reading.php';
    return $http({
    method: 'POST',
    data: meter_data,
    url: URL
        });
    }

On the server abc.def.com I have the following code:

<?php

    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $json = json_encode($jTableResult);
    exit ( $json  );
    }

?>

What am I missing to make this work?
Thanks in advance.

Body:
Turns out I have been looking for answer on the wrong side, i.e. angular side.

Answer was to add a line to the server code. and the code is now:

<?php
        {
    header("Access-Control-Allow-Origin: *");       //Fixes cross origin issue
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $json = json_encode($jTableResult);
    exit ( $json  );
    }

?>


问:
Conflict in "Promise" while setting up new project using Angular 4
```<code>1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es2015.iterable.d.ts(203,11): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es2015.promise.d.ts(223,13): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es2015.symbol.wellknown.d.ts(168,11): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es5.d.ts(1292,11): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\users\username\node_modules@types\es6-promise\index.d.ts(11,15): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\users\username\node_modules@types\es6-promise\index.d.ts(42,19): error TS2300: Build:Duplicate identifier 'Promise'.
</code>```

tsconfig: -

```<code>{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"noStrictGenericChecks": true
}
}
</code>```

Package.Json:

```<code>{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~4.3.4",
    "@angular/compiler": "~4.3.4",
    "@angular/core": "~4.3.4",
    "@angular/forms": "~4.3.4",
    "@angular/http": "~4.3.4",
    "@angular/platform-browser": "~4.3.4",
    "@angular/platform-browser-dynamic": "~4.3.4",
    "@angular/router": "~4.3.4",
    "angular-in-memory-web-api": "~0.3.0",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "typescript": "2.6.0",
    "canonical-path": "0.0.2",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "@types/node": "^6.0.46",
    "@types/jasmine": "2.5.36"
  },
  "repository": {}
}
</code>```

npm 5.5.1
node 8.9.1

Any workaround?

答:
Add this to tsConfig file

"skipLibCheck": true

Body:
1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es2015.iterable.d.ts(203,11): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es2015.promise.d.ts(223,13): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es2015.symbol.wellknown.d.ts(168,11): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\Program Files (x86)\Microsoft SDKs\TypeScript\2.6\lib.es5.d.ts(1292,11): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\users\username\node_modules@types\es6-promise\index.d.ts(11,15): error TS2300: Build:Duplicate identifier 'Promise'.
1>c:\users\username\node_modules@types\es6-promise\index.d.ts(42,19): error TS2300: Build:Duplicate identifier 'Promise'.

tsconfig: -

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"noStrictGenericChecks": true
}
}

Package.Json:

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~4.3.4",
    "@angular/compiler": "~4.3.4",
    "@angular/core": "~4.3.4",
    "@angular/forms": "~4.3.4",
    "@angular/http": "~4.3.4",
    "@angular/platform-browser": "~4.3.4",
    "@angular/platform-browser-dynamic": "~4.3.4",
    "@angular/router": "~4.3.4",
    "angular-in-memory-web-api": "~0.3.0",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "typescript": "2.6.0",
    "canonical-path": "0.0.2",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "@types/node": "^6.0.46",
    "@types/jasmine": "2.5.36"
  },
  "repository": {}
}

npm 5.5.1
node 8.9.1

Any workaround?


问:
Can/should I use mod_rewrite to change the paths of links on a local Dev environment? (Kohana)
First time collaborating on a large project: I may be in over my head.

All the links on the site broke when I try to run the code on my local machine.

/localhost/dir/file need to become /localhost/appname/html/dir/file

I changed APPPATH, SYSPATH &tc to reflect the dir change & that all works now, but the html/css/js links are all broken still. I think I need to change .htaccess & mod_rewrite to prepend appname/html/ to the links, but perhaps not?

edit: I was able to get some of the links working using the html <base> tag, the ones still not working seem to be created using Kohana classes, so I'm guessing there is a variable somewhere I still need to change.

答: I think the correct thing to do would be to use url::base() to generate the links. That would make the application more resilient to changes. But given that you're working on existing code, using mod_rewrite is a pragmatic approach, nothing wrong with that.</p>

ContentLicense: CC BY-SA 2.5


答:
You can use the runOnUiThread method:

```<code>    SomeActivity.this.runOnUiThread(new Runnable() {
        public void run() {

            //update your ui here
        }
    });
</code>```

You can call this from a worker thread

Title: Can I update the UI one "tick" during intensive task on the UI thread?

Body:
You can use the runOnUiThread method:

    SomeActivity.this.runOnUiThread(new Runnable() {
        public void run() {

            //update your ui here
        }
    });

You can call this from a worker thread


问:
How can I find occurences in a list?
I´m working on an assigment in Python, and I have a question if you could answer.
I wanna write a function that returns a list with the locations of the first nucleotide of all occurrences of "ATG" in the sequence.
For example, we can say that our DNA sequence is AATGCATGC. We see that ATG can start in the index 1, and the other possibility is index 5.
I tried this one to solve this assignment;

```<code>dna = "AATGCATGC"
starting_offset = dna.index("ATG")
print(starting_offset)
</code>```

The result I´ve got is 1. But I wanna get result as [1, 5]

So how should I write this function for all occurrences?

Thanks for helping me :)

答:
If you want something to think about, analyse this:</p>

```<code>def GetMultipleInString(dna, term):
    # computing end condition 0
    if (term not in dna):
        print (dna + " does not contain the term " + term)
        return []

    # start of list of lists of 2 elements: index, rest
    result = [[None,dna]]

    # we look for the index in the rest, need to keep track how much we
    # shortened the string in total so far to get index in complete string
    totalIdx = 0

    # we look at the last element of the list until it's length is shorter
    # than the term we look for (end of computing condition 1)
    termLen = len(term)

    while len(result[-1][1]) >= termLen:
        # get the last element
        last = result[-1][1]
        try:
            # find our term, if not found -> exception
            idx = last.index(term)
            # partition "abcdefg" with "c" -> ("ab","c", "defg")
            # we take only the remaining
            rest = last.partition(term)[2]
            # we compute the total index, and put it in our result
            result.append( [idx+totalIdx , rest] )
            totalIdx += idx+termLen
        except:
            result.append([None,last])
            break

    # any results found that are not none?
    if (any( x[0] != None for x in result)):

        print (dna + " contains the term " + term + " at positions:"),
        # get only indexes from our results
        rv = [ str(x[0]) for x in result if x[0] != None]
        print (' '.join(rv))

        return rv

    else:
        print (dna + " does not contain the term " + term)
        return []

print("_----------------------------------_")
myDna = "AATGCATGC"
res1 = GetMultipleInString(myDna,"ATG")
print(res1)

res2 = GetMultipleInString(myDna,"A")
print(res2)
</code>```

Title: How can I find occurences in a list?

Body:
I´m working on an assigment in Python, and I have a question if you could answer.
I wanna write a function that returns a list with the locations of the first nucleotide of all occurrences of "ATG" in the sequence.
For example, we can say that our DNA sequence is AATGCATGC. We see that ATG can start in the index 1, and the other possibility is index 5.
I tried this one to solve this assignment;

dna = "AATGCATGC"
starting_offset = dna.index("ATG")
print(starting_offset)

The result I´ve got is 1. But I wanna get result as [1, 5]

So how should I write this function for all occurrences?

Thanks for helping me :)

Body:
If you want something to think about, analyse this:

def GetMultipleInString(dna, term):
    # computing end condition 0
    if (term not in dna):
        print (dna + " does not contain the term " + term)
        return []

    # start of list of lists of 2 elements: index, rest
    result = [[None,dna]]

    # we look for the index in the rest, need to keep track how much we
    # shortened the string in total so far to get index in complete string
    totalIdx = 0

    # we look at the last element of the list until it's length is shorter
    # than the term we look for (end of computing condition 1)
    termLen = len(term)

    while len(result[-1][1]) >= termLen:
        # get the last element
        last = result[-1][1]
        try:
            # find our term, if not found -> exception
            idx = last.index(term)
            # partition "abcdefg" with "c" -> ("ab","c", "defg")
            # we take only the remaining
            rest = last.partition(term)[2]
            # we compute the total index, and put it in our result
            result.append( [idx+totalIdx , rest] )
            totalIdx += idx+termLen
        except:
            result.append([None,last])
            break

    # any results found that are not none?
    if (any( x[0] != None for x in result)):

        print (dna + " contains the term " + term + " at positions:"),
        # get only indexes from our results
        rv = [ str(x[0]) for x in result if x[0] != None]
        print (' '.join(rv))

        return rv

    else:
        print (dna + " does not contain the term " + term)
        return []

print("_----------------------------------_")
myDna = "AATGCATGC"
res1 = GetMultipleInString(myDna,"ATG")
print(res1)

res2 = GetMultipleInString(myDna,"A")
print(res2)


问:
Adjacent JSX elements must be wrapped in an enclosing tag
I want to have a navigation bar at the bottom and a toolbar at the top of every page in my React-Native app. However, if I create these two elements in the index.ios.js file, I get the error: "Adjacent JSX elements must be wrapped in an enclosing tag". If I put  tags surrounding the Navigator and NavBar I just see a blank screen in my app. What should I do? Here is what my render function looks like in index.ios.js

render() {
    return (
      <Navigator
        initialRoute={{name: 'Login'}}
        renderScene={this.renderScene}
        navigationBar={
          <Navigator.NavigationBar
          style={ styles.nav }
          routeMapper={ NavigationBarRouteMapper } />
        }
        />
        <NavBar />
    );
  }```

答:
As per React 16, if you wan't to avoid the <View> wrapping,
you can return multiple components from render as an array.

```<code>return ([
    <Navigator key="navigator" />,
    <NavBar key="navbar" />
]);
</code>```

Or in a stateless ES6 component:

```<code>import React from 'react';

const Component = () => [
  <Navigator key="navigator" />,
  <NavBar key="navbar" />
];

export default Component;
</code>```

Don't forget the key property as React needs (as for iteration on Array) to be able to discriminate your components.

Edit (Nov. 2018)

Your can also use React.Fragment shorthand:

```<code>render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}
</code>```

Body:
As per React 16, if you wan't to avoid the <View> wrapping,
you can return multiple components from render as an array.

return ([
    <Navigator key="navigator" />,
    <NavBar key="navbar" />
]);

Or in a stateless ES6 component:

import React from 'react';

const Component = () => [
  <Navigator key="navigator" />,
  <NavBar key="navbar" />
];

export default Component;

Don't forget the key property as React needs (as for iteration on Array) to be able to discriminate your components.

Edit (Nov. 2018)

Your can also use React.Fragment shorthand:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

ContentLicense: CC BY-SA 4.0


问:
Read content of file and put particular portion of content in separate files using bash
I would like to get specific file contains from single file and put into separate files via bash. I have tried getting test1 file contain using below code and able to get it but i'm failed when getting everything in respected files.

Tried code:

```<code>reportFile=/report.txt
test1File=/test1.txt
test2File=/test2.txt
test3File=/test3.txt

totalLineNo=`cat ${reportFile} | wc -l`
test1LineNo=`grep -n "Test1 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test2LineNo=`grep -n "Test2 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test3LineNo=`grep -n "Test3 file content :" ${reportFile} | grep -Eo '^[^:]+'`

exactTest1LineNo=`echo $(( ${test1LineNo} - 1 ))`
exactTest2LineNo=`echo $(( ${test2LineNo} -1 ))`
exactTest3LineNo=`echo $(( ${test3LineNo} -1 ))`

test1Content=`cat ${reportFile} | head -n ${exactTest1LineNo}`
test3Content=`cat ${reportFile} | tail -n ${exactTest3LineNo}`

echo -e "${test1Content}\r" >> ${test1File}
echo -e "${test3Content}\r" >> ${test3File}
</code>```

report.txt:

```<code>-------------------------------------

My Report:

Test1 file content:
1
2
3
4
5
6

Test2 file content:
7
8
9
10

Test3 file content:
11
12
13
14
15

Note: Find my report above.

-------------------------------------
</code>```

test1.txt (expected):

```<code>1
2
3
4
5
6
</code>```

test2.txt (expected):

```<code>7
8
9
10
</code>```

test3.txt (expected):

```<code>11
12
13
14
15
</code>```

答:
If I understand you correctly: you have a long file report.txt and you want to extract short files from it. The name of each file is followed by the string " file content:" in the file report.txt.

This is my solution:

```<code>#!/bin/bash
reportFile=report.txt

Files=`grep 'file content' $reportFile | sed 's/ .*$//'`

for F in $Files ; do
    f=${F,}.txt         # first letter lowercase and append .txt
    awk "/$F file content/,/^\$/ {print}" $reportFile |
        tail -n +2 |    # remove first line with "Test* file content:"
        head -n -1 > $f # remove last blank line
done
</code>```

Body:
I would like to get specific file contains from single file and put into separate files via bash. I have tried getting test1 file contain using below code and able to get it but i'm failed when getting everything in respected files.

Tried code:

reportFile=/report.txt
test1File=/test1.txt
test2File=/test2.txt
test3File=/test3.txt

totalLineNo=`cat ${reportFile} | wc -l`
test1LineNo=`grep -n "Test1 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test2LineNo=`grep -n "Test2 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test3LineNo=`grep -n "Test3 file content :" ${reportFile} | grep -Eo '^[^:]+'`

exactTest1LineNo=`echo $(( ${test1LineNo} - 1 ))`
exactTest2LineNo=`echo $(( ${test2LineNo} -1 ))`
exactTest3LineNo=`echo $(( ${test3LineNo} -1 ))`

test1Content=`cat ${reportFile} | head -n ${exactTest1LineNo}`
test3Content=`cat ${reportFile} | tail -n ${exactTest3LineNo}`

echo -e "${test1Content}\r" >> ${test1File}
echo -e "${test3Content}\r" >> ${test3File}

report.txt:

-------------------------------------

My Report:

Test1 file content:
1
2
3
4
5
6

Test2 file content:
7
8
9
10

Test3 file content:
11
12
13
14
15

Note: Find my report above.

-------------------------------------

test1.txt (expected):

1
2
3
4
5
6

test2.txt (expected):

7
8
9
10

test3.txt (expected):

11
12
13
14
15

Body:
If I understand you correctly: you have a long file report.txt and you want to extract short files from it. The name of each file is followed by the string " file content:" in the file report.txt.

This is my solution:

#!/bin/bash
reportFile=report.txt

Files=`grep 'file content' $reportFile | sed 's/ .*$//'`

for F in $Files ; do
    f=${F,}.txt         # first letter lowercase and append .txt
    awk "/$F file content/,/^\$/ {print}" $reportFile |
        tail -n +2 |    # remove first line with "Test* file content:"
        head -n -1 > $f # remove last blank line
done


问:
How to get index of duplicates in array?
I would like to know how to get the index of two or more objects that is a duplicate in an array. How would i do this in swift?

My array looks like this : [1, 2, 3, 1]
I would then like to return the index of 1, since they are duplicates.(0, 3)

I have tried to find any answers regarding this, but I could not find any answers. Therefore I hope I can get an answer.

答:
I did find a solution!

```<code>names = ["Shrek", "Shrek", "Pinocchio"]
for name in names{
        print(names.index(of: name))
    }
</code>```

Prints(0,0,2) because names has to duplicates

Body:
I did find a solution!

names = ["Shrek", "Shrek", "Pinocchio"]
for name in names{
        print(names.index(of: name))
    }

Prints(0,0,2) because names has to duplicates


问:
$ Variable (Dollar Sign) in Chrome?
I was working with the developer tools of google chrome on a page without jQuery (or any other library that uses the $ sign as a shortcut).
When I inspected $ by the console (by just typing it in and hitting enter), i got this:

```<code>$
function () { [native code] }
</code>```

So, chrome has some native function that can be referenced by $. Only chrome seems to have this one and i cannot access it via window['$'] nor via document['$'] or this['$'].

I was not able to find out what this function is. Do you know what it does and maybe have some background information on this?
Thanks in advance!

答:
This has changed yet again, even since just last year.

The devtools console provides $ as an alias to document.querySelector, along with many other things; here's an excerpted list:

$(selector) returns the reference to the first DOM element with the specified CSS selector. This function is an alias for the document.querySelector() function.

$$(selector) returns an array of elements that match the given CSS selector. This command is equivalent to calling document.querySelectorAll().

$_ returns the value of the most recently evaluated expression.

The $0, $1, $2, $3 and $4 commands work as a historical reference to the last five DOM elements inspected within the Elements panel or the last five JavaScript heap objects selected in the Profiles panel.

...and a bunch of others.

Note how it calls $ an alias of document.querySelector, but says $$ is "equivalent" to calling document.querySelectorAll. Neither seems to be literally true; $ === document.querySelector is false, and $$ returns an array, not a NodeList.

Title: $ Variable (Dollar Sign) in Chrome?

Body:
I was working with the developer tools of google chrome on a page without jQuery (or any other library that uses the $ sign as a shortcut).
When I inspected $ by the console (by just typing it in and hitting enter), i got this:

$
function () { [native code] }

So, chrome has some native function that can be referenced by $. Only chrome seems to have this one and i cannot access it via window['$'] nor via document['$'] or this['$'].

I was not able to find out what this function is. Do you know what it does and maybe have some background information on this?
Thanks in advance!


问:
Fuzzy match in proc sql, select minimum distance
I have a list with some fuzzy variables and a list with some clean variables. I want to want to (fuzzy) match both of them where the compged distance is lowest and some rules regarding their edit distances are satisfied (f.ex. compged < 100 and spedis < 50). I tried the following code

```<code>proc sql noprint;
create table out as
select min(compged(fuzzy.fuzzy_title,clean.cleaned_title,100))
as comp,
fuzzy.fuzzy_title, clean.cleaned_title
from fuzzy inner join clean
on (compged(fuzzy.fuzzy_title,clean.cleaned_title,100) < 100 and
spedis(clean.cleaned_title,fuzzy.fuzzy_title) < 50);
quit;
</code>```

The datasets fuzzy and clean basically just contain the titles that I want to match. The code I use just gives me the minimum compged score of the whole dataset and then some arbitrary match where my condition regarding the distances are satisfied. Is there a way to choose exactly the clean_title with the minimum compged score for a given fuzzy_title? I might have searched wrong, but I couldn't find the answer to this.

答:
I think you are looking for group by + having:

```<code>   proc sql;
    create table out as
    select
         compged(fuzzy.fuzzy_title,clean.cleaned_title,100)as comp
        ,fuzzy.fuzzy_title
        ,clean.cleaned_title
    from fuzzy inner join clean
        on (compged(fuzzy.fuzzy_title,clean.cleaned_title,100) < 100
        and spedis(clean.cleaned_title,fuzzy.fuzzy_title) < 50)
    group by fuzzy.fuzzy_title
    having calculated comp = min(compged(fuzzy.fuzzy_title,clean.cleaned_title,100))
    ;quit;
</code>```

If there are more fuzzy_title + cleaned_title pairs having the same comp value, all of them will be in the output. You can select only one of them in a single query. However, I think it's easier to keep those steps separated and select one row for each fuzzy_title in another query (e.g. using first data step variable).

Body:
I have a list with some fuzzy variables and a list with some clean variables. I want to want to (fuzzy) match both of them where the compged distance is lowest and some rules regarding their edit distances are satisfied (f.ex. compged < 100 and spedis < 50). I tried the following code

proc sql noprint;
create table out as
select min(compged(fuzzy.fuzzy_title,clean.cleaned_title,100))
as comp,
fuzzy.fuzzy_title, clean.cleaned_title
from fuzzy inner join clean
on (compged(fuzzy.fuzzy_title,clean.cleaned_title,100) < 100 and
spedis(clean.cleaned_title,fuzzy.fuzzy_title) < 50);
quit;

The datasets fuzzy and clean basically just contain the titles that I want to match. The code I use just gives me the minimum compged score of the whole dataset and then some arbitrary match where my condition regarding the distances are satisfied. Is there a way to choose exactly the clean_title with the minimum compged score for a given fuzzy_title? I might have searched wrong, but I couldn't find the answer to this.

Body:
I think you are looking for group by + having:

   proc sql;
    create table out as
    select
         compged(fuzzy.fuzzy_title,clean.cleaned_title,100)as comp
        ,fuzzy.fuzzy_title
        ,clean.cleaned_title
    from fuzzy inner join clean
        on (compged(fuzzy.fuzzy_title,clean.cleaned_title,100) < 100
        and spedis(clean.cleaned_title,fuzzy.fuzzy_title) < 50)
    group by fuzzy.fuzzy_title
    having calculated comp = min(compged(fuzzy.fuzzy_title,clean.cleaned_title,100))
    ;quit;

If there are more fuzzy_title + cleaned_title pairs having the same comp value, all of them will be in the output. You can select only one of them in a single query. However, I think it's easier to keep those steps separated and select one row for each fuzzy_title in another query (e.g. using first data step variable).


问:
Oracle SQL count group by day distinct in day and days before
I need help with this: I have this table:

```<code>DAY     WO
 1     1000
 1     1009
 1     2056
 2     1003
 2     1006
 2     1000
 3     1009
 3     6787
 4     7000
 4     7020
</code>```

I need to group by day distinct WO, but not only in the day I'm grouping, also distinct in the days before, to obtain this:

```<code>DAY    WO
 1      3 (1000,1009,2056)
 2      2 (1003,1006)
 3      1 (6787)
 4      2 (7000,7020)
</code>```

Thanks for your help

```<code>Sample 2:
DAY   WO
6   379157
9   379157
10  379404
10  379362
19  386118
24  386547
25  388711
25  386547
30  386547
</code>```

答:
You want to use LISTAGG to concatenate the values together, plus a little extra string concatenation for formatting:

-- START: table data mockup
with days as
(
    select 1 as "day", 1000 as "wo" from dual
    union all
    select 1 as "day", 1009 as "wo" from dual
    union all
    select 1 as "day", 2056 as "wo" from dual
    union all
    select 2 as "day", 1003 as "wo" from dual
    union all
    select 2 as "day", 1006 as "wo" from dual
    union all
    select 2 as "day", 1000 as "wo" from dual
    union all
    select 3 as "day", 1009 as "wo" from dual
    union all
    select 3 as "day", 6787 as "wo" from dual
    union all
    select 4 as "day", 7000 as "wo" from dual
    union all
    select 4 as "day", 7020 as "wo" from dual
)
-- END: table data mockup

select "day", count("wo") || ' (' || listagg("wo", ',') within group (order by "wo") || ')' "WO"
from days d1
where d1."wo" not in
(
    select d2."wo"
    from days d2
    where d2."day" < d1."day"
)
group by "day";
```

Body:
I need help with this: I have this table:

DAY     WO
 1     1000
 1     1009
 1     2056
 2     1003
 2     1006
 2     1000
 3     1009
 3     6787
 4     7000
 4     7020

I need to group by day distinct WO, but not only in the day I'm grouping, also distinct in the days before, to obtain this:

DAY    WO
 1      3 (1000,1009,2056)
 2      2 (1003,1006)
 3      1 (6787)
 4      2 (7000,7020)

Thanks for your help

Sample 2:
DAY   WO
6   379157
9   379157
10  379404
10  379362
19  386118
24  386547
25  388711
25  386547
30  386547


问:
Function that takes string as Input, evaluate it like a calculator and return the Integer answer
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

```<code>d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i
</code>```

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

答:
Since you are only catering for addition and subtraction, the below solution should work for any of your above mentioned examples:

```<code>def calculate(s):
   sWithAdd = s.replace('-', '+-')
   numbers = sWithAdd.split('+')
   return sum([int(i) for i in numbers if i != ''])

t = '1+2-32+64-71'
print(calculate(t)) #Prints -36, the correct answer
</code>```

The above code works in the following steps:

First, for all the - (minuses) in the string, we replace them with +-. The resulting string for our example becomes, 1+2+-32+64+-71. The reason we do this, is to convert our input into a series of addition of numbers

We then split the string on +, giving us just numbers that are simply meant to be added.

Finally, we sum all the numbers of the list using the sum function in python. You can use a custom for-loop for that purpose if required.

Body:
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

Body:
Since you are only catering for addition and subtraction, the below solution should work for any of your above mentioned examples:

def calculate(s):
   sWithAdd = s.replace('-', '+-')
   numbers = sWithAdd.split('+')
   return sum([int(i) for i in numbers if i != ''])

t = '1+2-32+64-71'
print(calculate(t)) #Prints -36, the correct answer

The above code works in the following steps:

First, for all the - (minuses) in the string, we replace them with +-. The resulting string for our example becomes, 1+2+-32+64+-71. The reason we do this, is to convert our input into a series of addition of numbers

We then split the string on +, giving us just numbers that are simply meant to be added.

Finally, we sum all the numbers of the list using the sum function in python. You can use a custom for-loop for that purpose if required.


问:
Name of this Java Swing component?

The above picture has a side panel type component that is perfect for what I need. Does anyone know what kind of component it is and where it is implemented from? I cannot find anything similar to the Swing documents.
I understand this is an oracle demo which should give source code, however, all the links to the source code so far have been to the .net site which has since been closed.

答:
Try JXTaskPaneContainerand JXTaskPane

Go through following reference might help you

http://www.oracle.com/technetwork/java/index.html?ssSourceSiteId=splash

https://docs.oracle.com/javase/8/docs/api/javax/swing/tree/TreeModel.html

Title: Name of this Java Swing component?


问:
VBA - MouseDown and MouseUp to trigger Macro
I've seen a few codes that work just fine to capture MouseDown and MouseUp events within TextBoxes, Shapes, CommandButtons, etc., such as the one below:

```<code>Private Sub CommandButton1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
'Do Stuff
End Sub
</code>```

Is there any way to capture MouseDown and MouseUp events on a Worksheet in order to trigger a macro?

答:
If you are talking about in the general userform, then you can use a format like this:

```<code>Private Sub UserForm_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
'Do things here
End Sub
</code>```

I don't believe it works with a worksheet though.

Body:
I've seen a few codes that work just fine to capture MouseDown and MouseUp events within TextBoxes, Shapes, CommandButtons, etc., such as the one below:

Private Sub CommandButton1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
'Do Stuff
End Sub

Is there any way to capture MouseDown and MouseUp events on a Worksheet in order to trigger a macro?

Body:
If you are talking about in the general userform, then you can use a format like this:

Private Sub UserForm_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
'Do things here
End Sub

I don't believe it works with a worksheet though.