问:
getActivity returning Null Pointer Exception when called from Fragment setUserVisibleHint
I have an app with Main Activity calling 3 fragments. I am seeing null pointer exception on app launch at the stage where getActivity is accessed from the first fragment.

```<code> E/AndroidRuntime: FATAL EXCEPTION: main Process: com.inc.sr, PID: 3019
 java.lang.NullPointerException: Attempt to invoke virtual method
 'android.support.v7.app.ActionBar
 com.inc.sr.MainActivity.getSupportActionBar()' on a null object
 reference
     at com.inc.sr.fragments.SRFrag.setUserVisibleHint(SRFrag.java:148)
     at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:136)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1234)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
     at android.view.View.measure(View.java:18788)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:901)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
     at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
     at android.view.Choreographer.doCallbacks(Choreographer.java:670)
     at android.view.Choreographer.doFrame(Choreographer.java:606)
     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 12-04
 13:25:33.229 1261-2076/? E/SurfaceFlinger: ro.sf.lcd_density must be
 defined as a build property 12-04 13:25:33.237 3019-3042/com.inc.sr
 E/FA: Failed to send current screen to service 12-04 13:25:33.237
 3019-3042/com.inc.sr E/FA: Discarding data. Failed to send event to
 service 12-04 13:25:33.238 3019-3042/com.inc.sr E/FA: Failed to send
 current screen to service 12-04 13:26:22.703
 2452-2870/com.google.android.gms E/SQLiteCastStore: End saving paired
 guest mode devices 12-04 13:30:33.228 1634-3092/system_process
 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40be100 12-04
 13:30:33.239 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER
 TRANSACTION !!!  (parcel size = 104) 12-04 13:30:33.244
 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION
 !!!  (parcel size = 104)
</code>```

Main Activity:

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

private Toolbar toolbar;
private TabLayout tabLayout;
private CustomViewPager viewPager;
private MyAdapter mAdapter;
TextView mTitle;
String[] title = {"S screen", "Compare", "About US"};
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

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

    //FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    if (findViewById(R.id.fragment_container) != null) {
        if (savedInstanceState != null) {
            return;
        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        //getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
        mTitle.setText(title[0]);

        mAdapter = new MyAdapter(getSupportFragmentManager());
        //viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager = (CustomViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(mAdapter);
        viewPager.setPagingEnabled(false);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
        tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
        tabLayout.getTabAt(2).setIcon(R.mipmap.infou);

        tabLayout.setOnTabSelectedListener(
                new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {

                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        super.onTabSelected(tab);
                        int pos = tab.getPosition();

                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compares);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infos);
                                break;
                        }
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                        super.onTabUnselected(tab);
                        int pos = tab.getPosition();
                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchu);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infou);
                                break;
                        }
                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {
                        super.onTabReselected(tab);
                    }
                }
        );

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
                List<Fragment> fragments = fragmentManager.getFragments();
                if (fragments != null) {
                    for (Fragment fragment : fragments) {
                        if (fragment != null && fragment.isVisible()) {

                            switch (position) {
                                case 0:
                                    if (fragment.getClass().toString().contains("srFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("sresFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String state = fragment.getArguments().getString("STATES", "");
                                        String grade = fragment.getArguments().getString("GRADES", "");
                                        String title = state + " - " + grade + " Ranking";
                                        mTitle.setText(title);
                                    } else if (fragment.getClass().toString().contains("sdFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String title = fragment.getArguments().getString("SCNAME", "");
                                        mTitle.setText(title);
                                    }
                                    break;
                                case 1:
                                    if (fragment.getClass().toString().contains("CompareFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("CompareResultsFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        mTitle.setText("Compare Results");
                                    }
                                    break;
                                case 2:
                                    if (fragment.getClass().toString().contains("InfoFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    }
                                    break;
                            }
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_out");
            }
        }
    };

    mAuth = FirebaseAuth.getInstance();

    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    System.out.println("AUTH FirebaseAuth signInAnonymously:onComplete:" + task.isSuccessful());

                    if (!task.isSuccessful()) {
                        System.out.println("AUTH FirebaseAuth signInAnonymously" + task.getException());

                    }
                }
            });

}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        //finish(); // close this activity and return to preview activity (if there is any)
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

public void onBackPressed() {
    if (viewPager.getCurrentItem() == 0) {
        if (mAdapter.getItem(0) instanceof sresFrag) {
            ((sresFrag) mAdapter.getItem(0)).backPressed();
        } else if (mAdapter.getItem(0) instanceof sdFrag) {
            ((sdFrag) mAdapter.getItem(0)).backPressed();
        } else {
            this.moveTaskToBack(true);
        }
    } else if (viewPager.getCurrentItem() == 1) {
        if (mAdapter.getItem(1) instanceof CompareResultsFrag) {
            ((CompareResultsFrag) mAdapter.getItem(1)).backPressed();
        } else if (mAdapter.getItem(1) instanceof CompareFrag) {
            viewPager.setCurrentItem(0);
        }
    } else if (viewPager.getCurrentItem() == 2) {
        if (mAdapter.getItem(2) instanceof InfoFrag) {
            viewPager.setCurrentItem(1);
        }
    }
}

private static class MyAdapter extends FragmentPagerAdapter {

    private final class FirstPageListener implements
            FirstPageFragmentListener {
        public void onSwitchToNextFragment(String year, String state, String grade, SchoolItem item, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos0)
                    .commit();
            if (mFragmentAtPos0 instanceof srFrag) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sresFrag && !(backPressed)) {
                mFragmentAtPos0 = sdFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                args.putSerializable("ITEM", item);
                args.putString("SCNAME", item.Name);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sdFrag && (backPressed)) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                System.out.println(year + state + grade);
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else { // Instance of NextFragment
                mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                System.out.println("UNI00 A");
            }

            notifyDataSetChanged();
        }
    }

    private final class SecondPageListener implements
            SecondPageFragmentListener {
        public void onSwitchToNextFragment(ArrayList<SchoolItem> schoolList, SchoolItem[] compareList, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos1)
                    .commit();
            if (mFragmentAtPos1 instanceof CompareFrag) {
                mFragmentAtPos1 = CompareResultsFrag.createInstance(SecondListener);
            } else { // Instance of NextFragment
                mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
            }

            Bundle args = new Bundle();
            args.putSerializable("SCLIST", schoolList);
            args.putSerializable("CMLIST", compareList);
            mFragmentAtPos1.setArguments(args);

            notifyDataSetChanged();
        }
    }

    private final class ThirdPageListener implements
            ThirdPageFragmentListener {
        public void onSwitchToNextFragment() {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos2)
                    .commit();
            mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);

            notifyDataSetChanged();
        }
    }

    private String[] titles = {"Search", "Compare", " Info"};
    private final FragmentManager mFragmentManager;
    public Fragment mFragmentAtPos0;
    public Fragment mFragmentAtPos1;
    public Fragment mFragmentAtPos2;
    private Context context;
    FirstPageListener FirstListener = new FirstPageListener();
    SecondPageListener SecondListener = new SecondPageListener();
    ThirdPageListener ThirdListener = new ThirdPageListener();

    public MyAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
        mFragmentManager = fragmentManager;
        System.out.println("UNI00 B");
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: // Fragment # 0
                if (mFragmentAtPos0 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                    System.out.println("UNI00 1");
                }
                System.out.println(mFragmentAtPos0.toString());
                return mFragmentAtPos0;
            case 1: // Fragment # 1
                if (mFragmentAtPos1 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
                    System.out.println("UNI00 2");
                }
                //return new BuyMainFrag();
                return mFragmentAtPos1;
            case 2:// Fragment # 2
                if (mFragmentAtPos2 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);
                    System.out.println("UNI00 3");
                }
                return mFragmentAtPos2;
            //return new SellMainFrag();
        }
        System.out.println("UNI00 4");
        return null;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof srFrag &&
                mFragmentAtPos0 instanceof sresFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof sdFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sdFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareFrag &&
                mFragmentAtPos1 instanceof CompareResultsFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareResultsFrag &&
                mFragmentAtPos1 instanceof CompareFrag) {
            return POSITION_NONE;
        }
        if (object instanceof InfoFrag) {
            return POSITION_NONE;
        }
        return POSITION_UNCHANGED;
    }

}

public void setToolBarTitle(String title) {
    mTitle.setText(title);
}
}
</code>```

First Fragment:

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

Spinner spinnerYear, spinnerState, spinnerGrade;
static FirstPageFragmentListener firstPageListener;
private String year = "", state = "", grade = "";
String FragTitle = "s screen";
private SchoolItem notUsed;

public static srFrag createInstance(FirstPageFragmentListener listener) {
    srFrag frag = new srFrag();
    firstPageListener = listener;
    return frag;
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.s_r, container, false);

    spinnerYear = (Spinner) view.findViewById(R.id.spinnerYear);
    ArrayAdapter<CharSequence> adapterYear = ArrayAdapter
            .createFromResource(view.getContext(), R.array.year, R.layout.spinner_row);
    spinnerYear.setAdapter(adapterYear);

    spinnerState = (Spinner) view.findViewById(R.id.spinnerState);
    ArrayAdapter<CharSequence> adapterState = ArrayAdapter
            .createFromResource(view.getContext(), R.array.state, R.layout.spinner_row);
    spinnerState.setAdapter(adapterState);

    spinnerGrade = (Spinner) view.findViewById(R.id.spinnerGrade);
    ArrayAdapter<CharSequence> adapterGrade = ArrayAdapter
            .createFromResource(view.getContext(), R.array.grade, R.layout.spinner_row);
    spinnerGrade.setAdapter(adapterGrade);

    spinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            year = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("YEARS", year);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            state = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("STATES", state);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerGrade.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            grade = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("GRADES", grade);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    Button button = (Button) view.findViewById(R.id.search_button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            firstPageListener.onSwitchToNextFragment(year, state, grade, notUsed, false);
        }
    });

    return view;
}

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

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
        ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
        ((MainActivity) getActivity()).setToolBarTitle(FragTitle);

    }
}
}
</code>```

答:
getActivity will return null if fragment not attached to Activity. So you need check this value will null or check fragment attached to activity or after onAttach().

```<code> boolean isAttached = false;
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    isAttached=true;
    // save the context here if needed
}

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(getActivity()!=null){// Or use the context saved in onAttach()
        // Do your stuff
    }
}
</code>```

I had faced the same issue because setUserVisibleHint not getting fired on second instance when getActivity() return context.
So managing is with a Listener is better way. Use ViewPager.OnPageChangeListener to notify your current fragment.

Body:
I have an app with Main Activity calling 3 fragments. I am seeing null pointer exception on app launch at the stage where getActivity is accessed from the first fragment.

 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.inc.sr, PID: 3019
 java.lang.NullPointerException: Attempt to invoke virtual method
 'android.support.v7.app.ActionBar
 com.inc.sr.MainActivity.getSupportActionBar()' on a null object
 reference
     at com.inc.sr.fragments.SRFrag.setUserVisibleHint(SRFrag.java:148)
     at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:136)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1234)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
     at android.view.View.measure(View.java:18788)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:901)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
     at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
     at android.view.Choreographer.doCallbacks(Choreographer.java:670)
     at android.view.Choreographer.doFrame(Choreographer.java:606)
     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 12-04
 13:25:33.229 1261-2076/? E/SurfaceFlinger: ro.sf.lcd_density must be
 defined as a build property 12-04 13:25:33.237 3019-3042/com.inc.sr
 E/FA: Failed to send current screen to service 12-04 13:25:33.237
 3019-3042/com.inc.sr E/FA: Discarding data. Failed to send event to
 service 12-04 13:25:33.238 3019-3042/com.inc.sr E/FA: Failed to send
 current screen to service 12-04 13:26:22.703
 2452-2870/com.google.android.gms E/SQLiteCastStore: End saving paired
 guest mode devices 12-04 13:30:33.228 1634-3092/system_process
 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40be100 12-04
 13:30:33.239 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER
 TRANSACTION !!!  (parcel size = 104) 12-04 13:30:33.244
 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION
 !!!  (parcel size = 104)

Main Activity:

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private CustomViewPager viewPager;
private MyAdapter mAdapter;
TextView mTitle;
String[] title = {"S screen", "Compare", "About US"};
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

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

    //FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    if (findViewById(R.id.fragment_container) != null) {
        if (savedInstanceState != null) {
            return;
        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        //getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
        mTitle.setText(title[0]);

        mAdapter = new MyAdapter(getSupportFragmentManager());
        //viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager = (CustomViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(mAdapter);
        viewPager.setPagingEnabled(false);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
        tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
        tabLayout.getTabAt(2).setIcon(R.mipmap.infou);

        tabLayout.setOnTabSelectedListener(
                new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {

                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        super.onTabSelected(tab);
                        int pos = tab.getPosition();

                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compares);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infos);
                                break;
                        }
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                        super.onTabUnselected(tab);
                        int pos = tab.getPosition();
                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchu);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infou);
                                break;
                        }
                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {
                        super.onTabReselected(tab);
                    }
                }
        );

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
                List<Fragment> fragments = fragmentManager.getFragments();
                if (fragments != null) {
                    for (Fragment fragment : fragments) {
                        if (fragment != null && fragment.isVisible()) {

                            switch (position) {
                                case 0:
                                    if (fragment.getClass().toString().contains("srFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("sresFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String state = fragment.getArguments().getString("STATES", "");
                                        String grade = fragment.getArguments().getString("GRADES", "");
                                        String title = state + " - " + grade + " Ranking";
                                        mTitle.setText(title);
                                    } else if (fragment.getClass().toString().contains("sdFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String title = fragment.getArguments().getString("SCNAME", "");
                                        mTitle.setText(title);
                                    }
                                    break;
                                case 1:
                                    if (fragment.getClass().toString().contains("CompareFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("CompareResultsFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        mTitle.setText("Compare Results");
                                    }
                                    break;
                                case 2:
                                    if (fragment.getClass().toString().contains("InfoFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    }
                                    break;
                            }
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_out");
            }
        }
    };

    mAuth = FirebaseAuth.getInstance();

    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    System.out.println("AUTH FirebaseAuth signInAnonymously:onComplete:" + task.isSuccessful());

                    if (!task.isSuccessful()) {
                        System.out.println("AUTH FirebaseAuth signInAnonymously" + task.getException());

                    }
                }
            });

}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        //finish(); // close this activity and return to preview activity (if there is any)
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

public void onBackPressed() {
    if (viewPager.getCurrentItem() == 0) {
        if (mAdapter.getItem(0) instanceof sresFrag) {
            ((sresFrag) mAdapter.getItem(0)).backPressed();
        } else if (mAdapter.getItem(0) instanceof sdFrag) {
            ((sdFrag) mAdapter.getItem(0)).backPressed();
        } else {
            this.moveTaskToBack(true);
        }
    } else if (viewPager.getCurrentItem() == 1) {
        if (mAdapter.getItem(1) instanceof CompareResultsFrag) {
            ((CompareResultsFrag) mAdapter.getItem(1)).backPressed();
        } else if (mAdapter.getItem(1) instanceof CompareFrag) {
            viewPager.setCurrentItem(0);
        }
    } else if (viewPager.getCurrentItem() == 2) {
        if (mAdapter.getItem(2) instanceof InfoFrag) {
            viewPager.setCurrentItem(1);
        }
    }
}

private static class MyAdapter extends FragmentPagerAdapter {

    private final class FirstPageListener implements
            FirstPageFragmentListener {
        public void onSwitchToNextFragment(String year, String state, String grade, SchoolItem item, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos0)
                    .commit();
            if (mFragmentAtPos0 instanceof srFrag) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sresFrag && !(backPressed)) {
                mFragmentAtPos0 = sdFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                args.putSerializable("ITEM", item);
                args.putString("SCNAME", item.Name);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sdFrag && (backPressed)) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                System.out.println(year + state + grade);
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else { // Instance of NextFragment
                mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                System.out.println("UNI00 A");
            }

            notifyDataSetChanged();
        }
    }

    private final class SecondPageListener implements
            SecondPageFragmentListener {
        public void onSwitchToNextFragment(ArrayList<SchoolItem> schoolList, SchoolItem[] compareList, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos1)
                    .commit();
            if (mFragmentAtPos1 instanceof CompareFrag) {
                mFragmentAtPos1 = CompareResultsFrag.createInstance(SecondListener);
            } else { // Instance of NextFragment
                mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
            }

            Bundle args = new Bundle();
            args.putSerializable("SCLIST", schoolList);
            args.putSerializable("CMLIST", compareList);
            mFragmentAtPos1.setArguments(args);

            notifyDataSetChanged();
        }
    }

    private final class ThirdPageListener implements
            ThirdPageFragmentListener {
        public void onSwitchToNextFragment() {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos2)
                    .commit();
            mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);

            notifyDataSetChanged();
        }
    }

    private String[] titles = {"Search", "Compare", " Info"};
    private final FragmentManager mFragmentManager;
    public Fragment mFragmentAtPos0;
    public Fragment mFragmentAtPos1;
    public Fragment mFragmentAtPos2;
    private Context context;
    FirstPageListener FirstListener = new FirstPageListener();
    SecondPageListener SecondListener = new SecondPageListener();
    ThirdPageListener ThirdListener = new ThirdPageListener();

    public MyAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
        mFragmentManager = fragmentManager;
        System.out.println("UNI00 B");
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: // Fragment # 0
                if (mFragmentAtPos0 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                    System.out.println("UNI00 1");
                }
                System.out.println(mFragmentAtPos0.toString());
                return mFragmentAtPos0;
            case 1: // Fragment # 1
                if (mFragmentAtPos1 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
                    System.out.println("UNI00 2");
                }
                //return new BuyMainFrag();
                return mFragmentAtPos1;
            case 2:// Fragment # 2
                if (mFragmentAtPos2 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);
                    System.out.println("UNI00 3");
                }
                return mFragmentAtPos2;
            //return new SellMainFrag();
        }
        System.out.println("UNI00 4");
        return null;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof srFrag &&
                mFragmentAtPos0 instanceof sresFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof sdFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sdFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareFrag &&
                mFragmentAtPos1 instanceof CompareResultsFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareResultsFrag &&
                mFragmentAtPos1 instanceof CompareFrag) {
            return POSITION_NONE;
        }
        if (object instanceof InfoFrag) {
            return POSITION_NONE;
        }
        return POSITION_UNCHANGED;
    }

}

public void setToolBarTitle(String title) {
    mTitle.setText(title);
}
}

First Fragment:

public class srFrag extends Fragment {

Spinner spinnerYear, spinnerState, spinnerGrade;
static FirstPageFragmentListener firstPageListener;
private String year = "", state = "", grade = "";
String FragTitle = "s screen";
private SchoolItem notUsed;

public static srFrag createInstance(FirstPageFragmentListener listener) {
    srFrag frag = new srFrag();
    firstPageListener = listener;
    return frag;
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.s_r, container, false);

    spinnerYear = (Spinner) view.findViewById(R.id.spinnerYear);
    ArrayAdapter<CharSequence> adapterYear = ArrayAdapter
            .createFromResource(view.getContext(), R.array.year, R.layout.spinner_row);
    spinnerYear.setAdapter(adapterYear);

    spinnerState = (Spinner) view.findViewById(R.id.spinnerState);
    ArrayAdapter<CharSequence> adapterState = ArrayAdapter
            .createFromResource(view.getContext(), R.array.state, R.layout.spinner_row);
    spinnerState.setAdapter(adapterState);

    spinnerGrade = (Spinner) view.findViewById(R.id.spinnerGrade);
    ArrayAdapter<CharSequence> adapterGrade = ArrayAdapter
            .createFromResource(view.getContext(), R.array.grade, R.layout.spinner_row);
    spinnerGrade.setAdapter(adapterGrade);

    spinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            year = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("YEARS", year);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            state = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("STATES", state);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerGrade.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            grade = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("GRADES", grade);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    Button button = (Button) view.findViewById(R.id.search_button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            firstPageListener.onSwitchToNextFragment(year, state, grade, notUsed, false);
        }
    });

    return view;
}

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

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
        ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
        ((MainActivity) getActivity()).setToolBarTitle(FragTitle);

    }
}
}

Body:
getActivity will return null if fragment not attached to Activity. So you need check this value will null or check fragment attached to activity or after onAttach().

 boolean isAttached = false;
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    isAttached=true;
    // save the context here if needed
}

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(getActivity()!=null){// Or use the context saved in onAttach()
        // Do your stuff
    }
}

I had faced the same issue because setUserVisibleHint not getting fired on second instance when getActivity() return context.
So managing is with a Listener is better way. Use ViewPager.OnPageChangeListener to notify your current fragment.


来源: stackexchange

问:
jhipster how to specify angular/cli version when generate client only
When I use below command to generate client only project using angular 4:

jhipster --skip-server --db mysql --auth jwt

all work except in generated package.json file:
the @angular/cli version is 1.4.2
and the @angular/common version is 4.3.2

However when I use angular cli to generate angular project, the cli version is
1.5.0 and other angular module version is 5.0.0

My question is:
How to use latest version of angular module and angular cli, or specify different version of such modules when use jhipster?

Note:

My global angular cli version is:1.5.0
my jhipster version is: 4.11.1
nodejs version is 6.11.3
windows version is: Windows 10, 64 bit

答:
You can't choose a specific version of Angular, when using JHipster. You need to modify yourself the version in package.json after generating.
But I'm not sure everything will work well but you can try.

The migration to Angular5 is coming. See https://github.com/jhipster/generator-jhipster/pull/6789

A lot of work has been done for that. It's not just changing the version in package.json

ContentLicense: CC BY-SA 3.0


问:
Sending emails from .Net core 2.0 with MailKit
I am receiving this error:

A connection attempt failed because the connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond xxx.xxx.xx.xx:25

Any ideas?

Note: The credentials are good.
Also, if I use MailKit with .net core 1.0 its working just fine but the project needs upgrading to .net 2.

Thank you very much.

答:
The account is the same. What I noticed is that I get the same error message if I put bogus credentials instead of good ones.
It's the credentials that are not passed the right way. But I cannot explain why the same code is working in the .Net Core 1.0 project. Regarding the code used is just a simple call to smtp server from MailKit samples                  </p>

```<code>`client.LocalDomain = _domain;
 client.Connect(_smtpServer, 25, SecureSocketOptions.None);
 client.AuthenticationMechanisms.Remove("XOAUTH2");
 client.Authenticate(credentials);
 client.Send(Message);`
</code>```

Body:
The account is the same. What I noticed is that I get the same error message if I put bogus credentials instead of good ones.
It's the credentials that are not passed the right way. But I cannot explain why the same code is working in the .Net Core 1.0 project. Regarding the code used is just a simple call to smtp server from MailKit samples

`client.LocalDomain = _domain;
 client.Connect(_smtpServer, 25, SecureSocketOptions.None);
 client.AuthenticationMechanisms.Remove("XOAUTH2");
 client.Authenticate(credentials);
 client.Send(Message);`


问:
Lockless list help!
Hi im trying to write a lockless list i got the adding part working it think but the code that extracts objects from the list does not work to good :(

Well the list is not a normal list.. i have the Interface IWorkItem

```<code>interface IWorkItem
{
    DateTime ExecuteTime { get; }
    bool Cancelled { get; }
    void Execute(DateTime now);
}
</code>```

and well i have a list where i can add this :P and the idear is when i run Get(); on the list it should loop it until it finds a IWorkItem that

```<code>If (item.ExecuteTime < DateTime.Now)
</code>```

and remove it from the list and return it..
i have ran tests with many threads on my dual core cpu and it seems that Add works never failed so far but the Get function looses some workitems some where i have no idear whats wrong.....

ps if i get this working any one is free to use the code :) well you are any way but i dont se the point when its bugged :P

The code is here http://www.easy-share.com/1903474734/LinkedList.zip and if you try to run it you will see that it will some times not be able to get as many workitems as it did put in the list...

Edit: I have got a lockless list working it was faster than using the lock(obj) statment but i have a lock object that uses Interlocked that was still outpreforming the lockless list, im going to try to make a lockless arraylist and se if i get the same results there when im done ill upload the result here..

答: So are you sure that it needs to be lockless? Depending on your work load the non-blocking solution can sometimes be slower. Check out this MSDN article for a little more. Also proving that a lockless data structure is correct can be very difficult.</p>

ContentLicense: CC BY-SA 2.5

Title: Lockless list help!

Body:
Hi im trying to write a lockless list i got the adding part working it think but the code that extracts objects from the list does not work to good :(

Well the list is not a normal list.. i have the Interface IWorkItem

interface IWorkItem
{
    DateTime ExecuteTime { get; }
    bool Cancelled { get; }
    void Execute(DateTime now);
}

and well i have a list where i can add this :P and the idear is when i run Get(); on the list it should loop it until it finds a IWorkItem that

If (item.ExecuteTime < DateTime.Now)

and remove it from the list and return it..
i have ran tests with many threads on my dual core cpu and it seems that Add works never failed so far but the Get function looses some workitems some where i have no idear whats wrong.....

ps if i get this working any one is free to use the code :) well you are any way but i dont se the point when its bugged :P

The code is here http://www.easy-share.com/1903474734/LinkedList.zip and if you try to run it you will see that it will some times not be able to get as many workitems as it did put in the list...

Edit: I have got a lockless list working it was faster than using the lock(obj) statment but i have a lock object that uses Interlocked that was still outpreforming the lockless list, im going to try to make a lockless arraylist and se if i get the same results there when im done ill upload the result here..

LastEditorDisplayName: Petoj

OwnerDisplayName: Steve

LastEditorDisplayName: Steve


问:
How to get jobid inside derived BackgroundJob class?
How to get current job id inside derived class of BackgroundJob?
In constructor or Execute method.
Any way.

Update1

I'm adding background job another way. The approach that suggested on ASP.NET Boilerplate documentation. Like this:

```<code>await _backgroundJobManager.EnqueueAsync<ImportContactListJob, ImportContactListJobArgs>(
        new ImportContactListJobArgs(){someargs});
</code>```

Then my method starts from overriding method Execute in BackgroundJob inheritance class.

```<code>public override void Execute(ImportContactListJobArgs args)
 {

    // job here
}

</code>```

I can't pass null value in EnqueueAsync because there is no overloaded method for this.

答:
There's no built-in way of doing this.

But you can use ABP's Hangfire Integration and do this:

For achieving your goal, just add PerformContext to your job method:

```<code>public void SendEmail(string name, PerformContext context)
{
   string jobId = context.BackgroundJob.Id;
}
</code>```

And pass null for it when enqueuing a job:

```<code>BackgroundJob.Enqueue(() => SendEmail(name, null));
</code>```

It will be substituted with a correct context when the job is actually performed.

Update

I can't pass null value in EnqueueAsync because there is no overloaded method for this.

Put PerformContext in the constructor of ImportContactListJob.

Related: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/4444

ContentLicense: CC BY-SA 4.0

Body:
How to get current job id inside derived class of BackgroundJob?
In constructor or Execute method.
Any way.

Update1

I'm adding background job another way. The approach that suggested on ASP.NET Boilerplate documentation. Like this:

await _backgroundJobManager.EnqueueAsync<ImportContactListJob, ImportContactListJobArgs>(
        new ImportContactListJobArgs(){someargs});

Then my method starts from overriding method Execute in BackgroundJob inheritance class.

public override void Execute(ImportContactListJobArgs args)
 {

    // job here
}

I can't pass null value in EnqueueAsync because there is no overloaded method for this.

Body:
There's no built-in way of doing this.

But you can use ABP's Hangfire Integration and do this:

For achieving your goal, just add PerformContext to your job method:

public void SendEmail(string name, PerformContext context)
{
   string jobId = context.BackgroundJob.Id;
}

And pass null for it when enqueuing a job:

BackgroundJob.Enqueue(() => SendEmail(name, null));

It will be substituted with a correct context when the job is actually performed.

Update

I can't pass null value in EnqueueAsync because there is no overloaded method for this.

Put PerformContext in the constructor of ImportContactListJob.

Related: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/4444


问:
Regex to remove only white spaces from left and right side of array and object brackets
I want to remove white spaces from left and right side of array and objects.
for example:</p>

```<code>[ **remove space**{**remove space** "test t":"asd asd" **remove space**} **remove space**]
</code>```

答:
Using a regular expression literal.

str = '[      {      "test t":"asd asd"      }      ]';
str = str.replace( / *([\[|\]|\{|\}]) */g, "$1");
console.log( str );```

Body:
I want to remove white spaces from left and right side of array and objects.
for example:

[ **remove space**{**remove space** "test t":"asd asd" **remove space**} **remove space**]


答:
I hope I'm not missing anything in the OP's question. I focused on the very last example data, given under "Last Edit". Using that data, the below code yields the desired output.

Code:

```<code>data = '' # <the OP's dataframe here>

def my_grouper(df):
    df = df[df['Type'] == 'Data']
    return df.groupby(['Receiver'])['Retry'].sum()

grouped_data = data.groupby(pd.Grouper(freq='1S')).apply(my_grouper)
grouped_data = pd.DataFrame(grouped_data).unstack(1).fillna(0)
grouped_data.columns = grouped_data.columns.droplevel(0)
print(grouped_data)
</code>```

Output:

```<code>Receiver             R1  R2
Index
1970-01-01 00:00:00   1   0
1970-01-01 00:00:01   0   1
1970-01-01 00:00:02   1   2
1970-01-01 00:00:03   0   1
</code>```

Title: Using pandas' TimeGrouper() to find column counts by intervals of 1 second

Body:
Consider the dataframe "data" indexed by Timestamp as follow:

Index                                Receiver     Type         Retry
1970-01-01 00:00:00.000000000         R1          Data         1
1970-01-01 00:00:00.800000000         R1          Non-Data     1
1970-01-01 00:00:01.000287000         R2          Data         0
1970-01-01 00:00:01.600896000         R2          Data         1
1970-01-01 00:00:02.001388000         R1          Data         1
1970-01-01 00:00:02.004698000         R1          Non-Data     1
1970-01-01 00:00:02.006706000         R2          Data         1
1970-01-01 00:00:02.501351000         R2          Data         1
1970-01-01 00:00:02.810382000         R1          Data         0
1970-01-01 00:00:03.001981000         R1          Data         0
1970-01-01 00:00:03.377116000         R1          Data         0
1970-01-01 00:00:03.701811000         R2          Data         1
1970-01-01 00:00:03.910326000         R2          Data         0
1970-01-01 00:00:03.951355000         R2          Non-Data     1

I want to find all rows where Type is "Data" and Retry equals 1 and then group the index in intervals of 1 second to find counts for each Receiver type.

Desired Output as df2:

Index                        R1   R2
1970-01-01 00:00:00          1    0
1970-01-01 00:00:01          0    1
1970-01-01 00:00:02          1    2
1970-01-01 00:00:03          0    1

Body:
I hope I'm not missing anything in the OP's question. I focused on the very last example data, given under "Last Edit". Using that data, the below code yields the desired output.

Code:

data = '' # <the OP's dataframe here>

def my_grouper(df):
    df = df[df['Type'] == 'Data']
    return df.groupby(['Receiver'])['Retry'].sum()

grouped_data = data.groupby(pd.Grouper(freq='1S')).apply(my_grouper)
grouped_data = pd.DataFrame(grouped_data).unstack(1).fillna(0)
grouped_data.columns = grouped_data.columns.droplevel(0)
print(grouped_data)

Output:

Receiver             R1  R2
Index
1970-01-01 00:00:00   1   0
1970-01-01 00:00:01   0   1
1970-01-01 00:00:02   1   2
1970-01-01 00:00:03   0   1


问:
Android: how can fragment take a global variable of Activity
I have an activity with a global variable int x, how can a fragment get the current value of variable x of its activity ?</p>

答:
```<code>***In your Activity
==================
Bundle args = new Bundle();
args.putInt("something", Whatever you want to pass);
fragA.setArguments(args);

In your Fragment
==================
 Bundle args = getArguments();
//whatever you want to get ,get it here.
//for example integer given
    int index = args.getInt("index", 0);
</code>```


问:
Behaviour of threads when entering background in iOS multitasking
While running some tests I've noticed that when an app (with no background privileges, i.e. voip, gps, etc) enters the background state, any background threads (or concurrent NSOperations) running at the time seem to be paused (not terminated), and they continue when the app enters the foreground.

I can't see this thread behaviour documented anywhere. Does anyone know if this behaviour is defined and can be counted on?

It would be useful to not have to cancel tasks or get involved in task completion if the thread can safely continue when the app is re-opened. Especially for complicated operations.

Any info would be great. Thanks!

答: When a non-multitasking app is quit, it is frozen in its current state and left in memory. However, if memory is low, the user closes it from the multitasking bar, or the device is shut down, the app will be terminated without warning. You can trust that an application returning from the background will continue as it was before, but you should save the state when entering the background in case the app is shut down.</p>


问:
UWP c# xdocument add XElement to Root
I have used this Code all throughout my project and now that there has been an update it has stopped working. I cant find anything online this is the format I'm trying to get my XML

```<code>   <?xml version="1.0" encoding="utf-8" ?>
    <CATALOG>
      <ITEM>
        <UIElementIndex>GRID</UIElementIndex>
        <Left>0</Left>
        <Top>0</Top>
        <Width>595</Width>
        <Height>60</Height>
        <Name>Header</Name>
        <PlaceHolder></PlaceHolder>
        <R>170</R>
        <G>170</G>
        <B>170</B>
      </ITEM>
    </CATALOG>
</code>```

I have been using this code, am i doing something Wrong

```<code>    using (var stream = await PDFCRFileReader.Instance.MainFile.OpenStreamForWriteAsync())
    {
        foreach (PDFCRElement element in PDFCRFileReader.Instance.documentElements)
        {
            XDocument document = XDocument.Load(stream);

            XElement xmlElemnt = new XElement("ITEM",
            new XAttribute("ID", "NIT " + element.Name + ((element.Left * element.Top) * element.Width).ToString()),
            new XElement("UIElementIndex", element.UIElementIndex),
            new XElement("Left", element.Left),
            new XElement("Top", element.Top),
            new XElement("Width", element.Width),
            new XElement("Height", element.Height),
            new XElement("Name", element.Name),
            new XElement("PlaceholderText", element.PlaceholderText),
            new XElement("R", element.R),
            new XElement("B", element.B),
            new XElement("G", element.G));

            document.Root.Element("CATALOG").Add(xmlElemnt);

            document.Save(stream);
            var dialog = new MessageDialog("FIle Saved!", "FILE SAVE STATUS");
            await dialog.ShowAsync();
        }
        stream.Flush();
    }
</code>```

I am getting the error, it makes no sense that this was working yesterday

System.NullReferenceException: 'Object reference not set to an
  instance of an object.'

答:
The problem is because the Root element "CATALOG" cannot be find which raised this issue. I used the following code then find that the result is null:

```<code>    var root = document.Root;
    var cataroot = root.Element("CATALOG");
</code>```

To solve this from your own code, use the following directly:

```<code>    document.Root.Add(xmlElemnt);
</code>```

And maybe you can report/consult it to here. Maybe the rule has been changed in this API. By the way, I think the change is reasonable. Here the root is already the CATALOG, root.Element("CATALOG") is trying to find the CATALOG node from the root.

Title: UWP c# xdocument add XElement to Root

Body:
I have used this Code all throughout my project and now that there has been an update it has stopped working. I cant find anything online this is the format I'm trying to get my XML

   <?xml version="1.0" encoding="utf-8" ?>
    <CATALOG>
      <ITEM>
        <UIElementIndex>GRID</UIElementIndex>
        <Left>0</Left>
        <Top>0</Top>
        <Width>595</Width>
        <Height>60</Height>
        <Name>Header</Name>
        <PlaceHolder></PlaceHolder>
        <R>170</R>
        <G>170</G>
        170
      </ITEM>
    </CATALOG>

I have been using this code, am i doing something Wrong

    using (var stream = await PDFCRFileReader.Instance.MainFile.OpenStreamForWriteAsync())
    {
        foreach (PDFCRElement element in PDFCRFileReader.Instance.documentElements)
        {
            XDocument document = XDocument.Load(stream);

            XElement xmlElemnt = new XElement("ITEM",
            new XAttribute("ID", "NIT " + element.Name + ((element.Left * element.Top) * element.Width).ToString()),
            new XElement("UIElementIndex", element.UIElementIndex),
            new XElement("Left", element.Left),
            new XElement("Top", element.Top),
            new XElement("Width", element.Width),
            new XElement("Height", element.Height),
            new XElement("Name", element.Name),
            new XElement("PlaceholderText", element.PlaceholderText),
            new XElement("R", element.R),
            new XElement("B", element.B),
            new XElement("G", element.G));

            document.Root.Element("CATALOG").Add(xmlElemnt);

            document.Save(stream);
            var dialog = new MessageDialog("FIle Saved!", "FILE SAVE STATUS");
            await dialog.ShowAsync();
        }
        stream.Flush();
    }

I am getting the error, it makes no sense that this was working yesterday

System.NullReferenceException: 'Object reference not set to an
  instance of an object.'

Body:
The problem is because the Root element "CATALOG" cannot be find which raised this issue. I used the following code then find that the result is null:

    var root = document.Root;
    var cataroot = root.Element("CATALOG");

To solve this from your own code, use the following directly:

    document.Root.Add(xmlElemnt);

And maybe you can report/consult it to here. Maybe the rule has been changed in this API. By the way, I think the change is reasonable. Here the root is already the CATALOG, root.Element("CATALOG") is trying to find the CATALOG node from the root.


问:
Javac not recognised
I tried typing the name of the bat file (makejar.bat) from the containing direcory from the command line. It gives several errors all containing "'javac' is not recognised as an internal or external command."  </p>

答:
On CMD--> type--> PATH="c:\Program Files\Java\jdk1.8.0_144\bin";
and then check java path by type "java -version" on cmd
and also check on YouTube : -https://www.youtube.com/watch?v=mzAAmJj-W6w  </p>

Title: Javac not recognised


问:
How to combine two Jar files
Is it possible to combine two jar files such that in an applet tag I can simply do something like

```<code>archive="jarjar.jar/jar1.jar"...  ...archive="jarjar.jar/jar2.jar"... instead of
archive="jar1.jar"... ...archive="jar2.jar"...
</code>```

I need to only have one jar file so putting two jar files in a folder will not help me.

答:
```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="zip-test" default="zip" basedir=".">

    <target name="zip">
        <zip destfile="out.jar">
            <zipgroupfileset dir="." includes="*.jar"/>
        </zip>
    </target>
</project>
</code>```

save this code in build.xml file and keep it in same folder where all the jar files to be combined are kept. Open cmd, give path of folder and run command : ant zip.

It will generate out.jar which is combination of all jars.

Title: How to combine two Jar files

Body:
Is it possible to combine two jar files such that in an applet tag I can simply do something like

archive="jarjar.jar/jar1.jar"...  ...archive="jarjar.jar/jar2.jar"... instead of
archive="jar1.jar"... ...archive="jar2.jar"...

I need to only have one jar file so putting two jar files in a folder will not help me.

Body:
<?xml version="1.0" encoding="UTF-8"?>
<project name="zip-test" default="zip" basedir=".">

    <target name="zip">
        <zip destfile="out.jar">
            <zipgroupfileset dir="." includes="*.jar"/>
        </zip>
    </target>
</project>

save this code in build.xml file and keep it in same folder where all the jar files to be combined are kept. Open cmd, give path of folder and run command : ant zip.

It will generate out.jar which is combination of all jars.


问:
problems of substituting localhost by true IP in ionic service.js
I am trying to deploy my ionic v1 application， which requires change baseURL from localhost:3000 to myip:3000.

before:(works)

```<code>angular.module('conFusion.services', ['ngResource'])
        .constant("baseURL","http://localhost:3000/")
        .service('menuFactory', ['$http', '$resource', 'baseURL', function($http, $resource,baseURL) {
</code>```

Before(error):

```<code>angular.module('conFusion.services', ['ngResource'])
        .constant("baseURL","http://160.39.xxx.xxx:3000/")
        .service('menuFactory', ['$http', '$resource', 'baseURL', function($http, $resource,baseURL) {
</code>```

However, after the change, the post request no longer works, the error I got is

WebSocket connection to 'ws://localhost:35729/livereload' failed:

Error in connection establishment: net::ERR_CONNECTION_REFUSED

exports.Connector.Connector.connect @ livereload.js:74 (anonymous) @

livereload.js:55 (anonymous) @ livereload.js:1152

any idea on how to change my localhost into my ip so that my Mac can serve as a server for other remote devices to use?

答:
Try setting src in config.xml in the following line :</p>

```<code><content src="http://160.39.xxx.xxx:8100" original-src="index.html"/>
</code>```

Body:
I am trying to deploy my ionic v1 application， which requires change baseURL from localhost:3000 to myip:3000.

before:(works)

angular.module('conFusion.services', ['ngResource'])
        .constant("baseURL","http://localhost:3000/")
        .service('menuFactory', ['$http', '$resource', 'baseURL', function($http, $resource,baseURL) {

Before(error):

angular.module('conFusion.services', ['ngResource'])
        .constant("baseURL","http://160.39.xxx.xxx:3000/")
        .service('menuFactory', ['$http', '$resource', 'baseURL', function($http, $resource,baseURL) {

However, after the change, the post request no longer works, the error I got is

WebSocket connection to 'ws://localhost:35729/livereload' failed:

Error in connection establishment: net::ERR_CONNECTION_REFUSED

exports.Connector.Connector.connect @ livereload.js:74 (anonymous) @

livereload.js:55 (anonymous) @ livereload.js:1152

any idea on how to change my localhost into my ip so that my Mac can serve as a server for other remote devices to use?

Body:
Try setting src in config.xml in the following line :

<content src="http://160.39.xxx.xxx:8100" original-src="index.html"/>


问:
Makefile change variable inside a loop
I am trying to change a variable inside a loop but I am failing with some errors. Here is the part of my makefile.

```<code>export CLOCK_PERIOD = 30;
syn_clock:
    for number in 1 2 3 4 ; do \
        echo $$CLOCK_PERIOD; \
        echo $$number; \
        $$CLOCK_PERIOD = $$number; \
    done
</code>```

The outcome of the make syn_clock is failing with the following lines:

```<code>bash-4.2$ make syn_clock
for number in 1 2 3 4 ; do \
        echo $CLOCK_PERIOD; \
        echo $number; \
        $CLOCK_PERIOD = $number; \
done
30
1
/bin/sh: line 3: 30: command not found
30
2
/bin/sh: line 3: 30: command not found
30
3
/bin/sh: line 3: 30: command not found
30
4
/bin/sh: line 3: 30: command not found
make: *** [syn_clock] Error 127
</code>```

I am expecting the CLOCK_PERIOD to change from 1 to 4 during the loop cycle.

What am I doing wrong?

答:
As already suggested in this comment, when assigning to a variable in the Bash shell, remove the spaces surrounding the assignment operator and the trailing $ in the name of the variable to be assigned. That is, CLOCK_PERIOD=$$number instead of $$CLOCK_PERIOD = $$number.

Since export CLOCK_PERIOD = 30; in your Makefile will be run by make, and not the shell, the result may not be what you expect (the value of CLOCK_PERIOD will be 30; instead of 30). So, I also removed the trailing semicolon as suggested in this comment.

The proposed solution is:

```<code>export CLOCK_PERIOD = 30
syn_clock:
    for number in 1 2 3 4 ; do \
        echo $$CLOCK_PERIOD; \
        echo $$number; \
        CLOCK_PERIOD=$$number; \
    done
</code>```

The first $ in the double $ of $$number is actually related to the Makefile: it is for escaping the second $ inside the Makefile, so that the shell receives a $, otherwise, if just $number were written, make would interpret it as ${n}umber, i.e.: make would expand the value of the variable n and this result would be concatenated with umber. That would be what the shell would receive.

Title: Makefile change variable inside a loop

Body:
I am trying to change a variable inside a loop but I am failing with some errors. Here is the part of my makefile.

export CLOCK_PERIOD = 30;
syn_clock:
    for number in 1 2 3 4 ; do \
        echo $$CLOCK_PERIOD; \
        echo $$number; \
        $$CLOCK_PERIOD = $$number; \
    done

The outcome of the make syn_clock is failing with the following lines:

bash-4.2$ make syn_clock
for number in 1 2 3 4 ; do \
        echo $CLOCK_PERIOD; \
        echo $number; \
        $CLOCK_PERIOD = $number; \
done
30
1
/bin/sh: line 3: 30: command not found
30
2
/bin/sh: line 3: 30: command not found
30
3
/bin/sh: line 3: 30: command not found
30
4
/bin/sh: line 3: 30: command not found
make: *** [syn_clock] Error 127

I am expecting the CLOCK_PERIOD to change from 1 to 4 during the loop cycle.

What am I doing wrong?

Body:
As already suggested in this comment, when assigning to a variable in the Bash shell, remove the spaces surrounding the assignment operator and the trailing $ in the name of the variable to be assigned. That is, CLOCK_PERIOD=$$number instead of $$CLOCK_PERIOD = $$number.

Since export CLOCK_PERIOD = 30; in your Makefile will be run by make, and not the shell, the result may not be what you expect (the value of CLOCK_PERIOD will be 30; instead of 30). So, I also removed the trailing semicolon as suggested in this comment.

The proposed solution is:

export CLOCK_PERIOD = 30
syn_clock:
    for number in 1 2 3 4 ; do \
        echo $$CLOCK_PERIOD; \
        echo $$number; \
        CLOCK_PERIOD=$$number; \
    done

The first $ in the double $ of $$number is actually related to the Makefile: it is for escaping the second $ inside the Makefile, so that the shell receives a $, otherwise, if just $number were written, make would interpret it as ${n}umber, i.e.: make would expand the value of the variable n and this result would be concatenated with umber. That would be what the shell would receive.


问:
Entity framework Modify multiple records with common data
I have an "Apps" Table which consists of multiple apps data
Now I wanted to delete (soft delete means making isDelete = true)

I'm deleting records by the following code.

```<code>var deletingISVCSPRecord = await db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ToListAsync();
foreach (var item in deletingISVCSPRecord)
{
    item.IsDeleted = true;
    await db.SaveChangesAsync();
}
</code>```

is there any good way to do this.

Appreciate your help.

答:
What I have been doing is to use transaction scope and only save once after all the updates. This has worked fine enough for me on my projects so far, you might want to do a comparison on whichever is more efficient tho.</p>

```<code>using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
     db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ForEach(item =>
     {
          item.IsDeleted = true;
     });
     await db.SaveChangesAsync();
     scope.Complete();
}
</code>```

Body:
I have an "Apps" Table which consists of multiple apps data
Now I wanted to delete (soft delete means making isDelete = true)

I'm deleting records by the following code.

var deletingISVCSPRecord = await db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ToListAsync();
foreach (var item in deletingISVCSPRecord)
{
    item.IsDeleted = true;
    await db.SaveChangesAsync();
}

is there any good way to do this.

Appreciate your help.

Body:
What I have been doing is to use transaction scope and only save once after all the updates. This has worked fine enough for me on my projects so far, you might want to do a comparison on whichever is more efficient tho.

using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
     db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ForEach(item =>
     {
          item.IsDeleted = true;
     });
     await db.SaveChangesAsync();
     scope.Complete();
}


问:
Ruby class, arguments being passed around methods, instance variable?
I'm having this problem which I think it might be a code smell, I have a class that receives an argument in its initialiser and contains one public and several private methods - everything normal. Example:

```<code>class Foo
  def initialize(a)
    @a = a
  end

  def apply?(examples)
    foo_1(examples)
  end

  private

  def foo_1(examples)
    foo_2(examples) ? 1 : 2
  end

  def foo_2(examples)
    examples.size > @a
  end
end
</code>```

My problem here, is 'examples' that is received by the public method being carried around over and over the private methods, it doesn't look pretty and it seems like a code smell, what's the best approach here? Make it an instance variable inside the public method?

Thanks

答:
Another option is to use block:</p>

```<code>class Foo
  def initialize(a)
    @a = a
  end

  def apply?(examples)
    foo_1 { examples }
  end

  private

  def foo_1
    v = foo_2 { yield.size }
    v ? 1 : 2
  end

  def foo_2
    yield > @a
  end
end
</code>```

Body:
I'm having this problem which I think it might be a code smell, I have a class that receives an argument in its initialiser and contains one public and several private methods - everything normal. Example:

class Foo
  def initialize(a)
    @a = a
  end

  def apply?(examples)
    foo_1(examples)
  end

  private

  def foo_1(examples)
    foo_2(examples) ? 1 : 2
  end

  def foo_2(examples)
    examples.size > @a
  end
end

My problem here, is 'examples' that is received by the public method being carried around over and over the private methods, it doesn't look pretty and it seems like a code smell, what's the best approach here? Make it an instance variable inside the public method?

Thanks

Body:
Another option is to use block:

class Foo
  def initialize(a)
    @a = a
  end

  def apply?(examples)
    foo_1 { examples }
  end

  private

  def foo_1
    v = foo_2 { yield.size }
    v ? 1 : 2
  end

  def foo_2
    yield > @a
  end
end


问:
What is the memory address of my code?
Hi I am trying to find the memory address of where my data gets stored.

This is the assembly code of the function.

```<code>   0x08048b20 <+0>:     push   %ebp
   0x08048b21 <+1>:     mov    %esp,%ebp
   0x08048b23 <+3>:     sub    $0x28,%esp
   0x08048b26 <+6>:     lea    -0x14(%ebp),%eax
   0x08048b29 <+9>:     mov    %eax,(%esp)
   0x08048b2c <+12>:    call   0x8048990 <Gets>
   0x08048b31 <+17>:    mov    $0x1,%eax
   0x08048b36 <+22>:    leave
   0x08048b37 <+23>:    ret
</code>```

My data which is a string gets stored at -0x14(%ebp) - (pretty positive). And I know the return address should be at 4(%ebp). What I am trying to do is set the return address to point at my code. And I can't use assembly to do this. I need to know the exact memory location of my where my function starts (which I know it stored at -0x14(%ebp)). Can anyone help me on how to get the memory location of that position?

The address on this line

```<code>0x08048b20 <+0>:     push   %ebp
</code>```

The 0x08048b20 is the memory location for the function I am in, not %ebp right? My thinking is that if I get the memory location for %ebp, I can calculate the memory location of where my function starts.

I am using gdb, and I don't know how to get the memory address of it?
Please, any help would be appreciated.
Thank you.

EDIT:
When I am standing at line <+6> in the assembly code, I print the values of %ebp and %esp, and they have an exact difference of 0x28 like they should. So I assumed that the address of %ebp is the value I get when I print it in gdb.

However, when I subtract 0x14 from this value (0xbfffb5d8) to give 0xbfffb5c4; it doesn't know where to jump to. If I have stored my string (which is actually byte code of disassembled code) at -0x14(%ebp), and I want to run that code; shouldn't I be putting the return address to -0x14(%ebp) or am I thinking completely wrongly?

答: Put a label before the first line of your function. Then referencing the label will give you the address of the first opcode in your compiled function. Unfortunately I don't understand your question enough to help you any more than that.</p>

Title: What is the memory address of my code?

Body:
Hi I am trying to find the memory address of where my data gets stored.

This is the assembly code of the function.

   0x08048b20 <+0>:     push   %ebp
   0x08048b21 <+1>:     mov    %esp,%ebp
   0x08048b23 <+3>:     sub    $0x28,%esp
   0x08048b26 <+6>:     lea    -0x14(%ebp),%eax
   0x08048b29 <+9>:     mov    %eax,(%esp)
   0x08048b2c <+12>:    call   0x8048990 <Gets>
   0x08048b31 <+17>:    mov    $0x1,%eax
   0x08048b36 <+22>:    leave
   0x08048b37 <+23>:    ret

My data which is a string gets stored at -0x14(%ebp) - (pretty positive). And I know the return address should be at 4(%ebp). What I am trying to do is set the return address to point at my code. And I can't use assembly to do this. I need to know the exact memory location of my where my function starts (which I know it stored at -0x14(%ebp)). Can anyone help me on how to get the memory location of that position?

The address on this line

0x08048b20 <+0>:     push   %ebp

The 0x08048b20 is the memory location for the function I am in, not %ebp right? My thinking is that if I get the memory location for %ebp, I can calculate the memory location of where my function starts.

I am using gdb, and I don't know how to get the memory address of it?
Please, any help would be appreciated.
Thank you.

EDIT:
When I am standing at line <+6> in the assembly code, I print the values of %ebp and %esp, and they have an exact difference of 0x28 like they should. So I assumed that the address of %ebp is the value I get when I print it in gdb.

However, when I subtract 0x14 from this value (0xbfffb5d8) to give 0xbfffb5c4; it doesn't know where to jump to. If I have stored my string (which is actually byte code of disassembled code) at -0x14(%ebp), and I want to run that code; shouldn't I be putting the return address to -0x14(%ebp) or am I thinking completely wrongly?


问:
Which lifecycle event is called when a screen appears?
Suppose I have two screens:

Screen A

Screen B

I am initially landed on Screen A. When I click on a Button I navigate to Screen B. When I press Back Button, I am again navigated to Screen A.

I want to call an action creator when I am navigated to Screen A as mentioned in above scenario.

I just want to know that which lifecycle event will be called every time when a screen is presented.

Isn't there some event like componentWillAppear()?

Note: I am using react-native with react-navigation for navigation.

答:
When you navigate from one screen to another, the first screen will not be unmounted, but still on the stack, just hide in the background.

What you need might be componentDidFocus, but it's currently in design not avaiable yet, see react-native open issue #51.

You can try this alternative way: react-navigation-addons. With this you can have events focus & blur which may suit your needs.


问:
Best way to close the socket and streams
In eclipse in one of the classes SonarLint and sonarqube server saying socket is not closed, even I closed it.

FYR:

What is the best way to close the socket? Could anyone please guide me.

Note: I don't get this error if I don't have out = new ObjectOutputStream(...)  code in the same try block.

答:
Use try-with-resources Statement something like:</p>

```<code>            try (ObjectOutputStream out =
                           new ObjectOutputStream(socket.getOutputStream()) {
               .....
            }
</code>```

Body:
Use try-with-resources Statement something like:

            try (ObjectOutputStream out =
                           new ObjectOutputStream(socket.getOutputStream()) {
               .....
            }


问:
Adding tooltips to a table with fixed header and left columns
I am trying to add tooltips to a scrollable table that has fixed headers and left columns.  When I add the tooltip the cell no longer hides behind the fixed headers and columns when the table is scrolled.

```<code><HTML>
<HEAD>
<STYLE>
.gradebooktable {
  overflow: auto;
  height: 100px;
  width: 400px
}

table {
  table-layout: fixed;
  border-width: 0;
  border-spacing: 0;
}

td {
  padding: 3px;
  white-space: nowrap;
  border-right: 1px solid #ccc;
}

th {
  background: #999;
}

th.pinned {
  position: relative;
  z-index: 20;
  background: #ccc;
}

td.pinned {
  background: #eee;
}

.tooltip{
  position:relative;
}

.tooltipcomment{
  display:none;
  position:absolute;
  z-index:10;
  border:1px;
  background-color:white;
  border-style:solid;
  border-width:1px;
  border-color:blue;
  padding:3px;
  color:red;
  top:20px;
  left:20px;
}

.tooltip:hover span.tooltipcomment{
  display:block;
}

</style>
</STYLE>
</HEAD>
<BODY>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<SCRIPT>
$( function() {
$('#gradebooktable').scroll( function() {
      var translate = "translate(0," + this.scrollTop + "px)";
      $("table thead th:not(.pinned)").css('transform', translate);

      translate = "translate(" + this.scrollLeft + "px,0)";
      $("table tbody .pinned").css('transform', translate);

      translate = "translate(" + this.scrollLeft + "px," + this.scrollTop + "px)";
      $("table thead th.pinned").css('transform', translate);
    }
);
});
</SCRIPT>
  <div id="gradebooktable" class="gradebooktable">
    <table>
      <thead>
        <tr>
          <th class="pinned">Col 0</th>
          <th class="pinned">Col 1</th>
          <th>Col 2</th>
          <th>Col 3</th>
          <th>Col 4</th>
          <th>Col 5</th>
          <th>Col 6</th>
          <th>Col 7</th>
          <th>Col 8</th>
          <th>Col 9</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
         <td class="tooltip">Another Cell
                  <span class="tooltipcomment">Here is a comment</span></td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
      </tbody>
    </table>
    </div>
</BODY>
</HTML>
</code>```

There is a fiddle showing the problem here:

https://jsfiddle.net/6jh60sgs/9/

What do I need to do to make the cell with the tooltip scroll behind the fixed headers and columns?

答:
I fixed it:  https://jsfiddle.net/k42myms3/1/</p>

```<code>.gradebooktable {
  overflow: auto;
  height: 200px;
  width: 400px
}

table {
  table-layout: fixed;
  border-width: 0;
  border-spacing: 0;
}

td {
  position:relative;
  padding: 3px;
  white-space: nowrap;
  border-right: 1px solid #ccc;
}

th {
  position:relative;
  z-index:20;
  background: #999;
}

th.pinned {
  position: relative;
  z-index: 40;
  background: #ccc;
}

td.pinned {
  position: relative;
  z-index: 30;
  background: #eee;
}

.tooltip{
  position:relative;
}

.tooltiptext{
  display:none;
  position:absolute;
  z-index:10;
  border:1px;
  background-color:#eee;
  border-style:solid;
  border-width:1px;
  border-color:blue;
  border-radius: 6px;
  padding:3px;
  color:blue;
  top:20px;
  left:20px;
}

.tooltip:hover span.tooltiptext{
  display:block;
}
</code>```

Body:
I am trying to add tooltips to a scrollable table that has fixed headers and left columns.  When I add the tooltip the cell no longer hides behind the fixed headers and columns when the table is scrolled.

</STYLE>

          Col 0
          Col 1
          Col 2
          Col 3
          Col 4
          Col 5
          Col 6
          Col 7
          Col 8
          Col 9

          First Cell
          Second Cell
         Another Cell
                  Here is a comment
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

There is a fiddle showing the problem here:

https://jsfiddle.net/6jh60sgs/9/

What do I need to do to make the cell with the tooltip scroll behind the fixed headers and columns?

Body:
I fixed it:  https://jsfiddle.net/k42myms3/1/

.gradebooktable {
  overflow: auto;
  height: 200px;
  width: 400px
}

table {
  table-layout: fixed;
  border-width: 0;
  border-spacing: 0;
}

td {
  position:relative;
  padding: 3px;
  white-space: nowrap;
  border-right: 1px solid #ccc;
}

th {
  position:relative;
  z-index:20;
  background: #999;
}

th.pinned {
  position: relative;
  z-index: 40;
  background: #ccc;
}

td.pinned {
  position: relative;
  z-index: 30;
  background: #eee;
}

.tooltip{
  position:relative;
}

.tooltiptext{
  display:none;
  position:absolute;
  z-index:10;
  border:1px;
  background-color:#eee;
  border-style:solid;
  border-width:1px;
  border-color:blue;
  border-radius: 6px;
  padding:3px;
  color:blue;
  top:20px;
  left:20px;
}

.tooltip:hover span.tooltiptext{
  display:block;
}