问:
RecyclerView Items are not changing
I have a RecyclerView in a fragment which is repeating in TabLayout. I am having the problem of unchanged view in RecyclerView. I have a spinner on each tab. I want to change the data when spinner items get selected.

My cases:

when switching between tabs - items changed

when selecting another value in the spinner in the first tab -items not changed. (but data is changing in adapter class.Ie. First, it is not null then null during selection. But the first not nulled data is not appearing, its replacing with null. Found it using breakpoints).

Note: In this case, when switching the tab, the items get changed to
  the spinner selected items in the previous tab. And then it disappears
  and displaying the current items in the tab.

when selecting another value in the spinner in the last tab -items changed.

My view pager adapter class

```<code>public class StudentViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<StudentList> mFragmentList = new ArrayList<>();
    private final List<Clazz> mFragmentTitleList = new ArrayList<>();
    public StudentViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    public void addFragment(StudentList fragment,Clazz clazz){
        mFragmentList.add(fragment);
        mFragmentTitleList.add(clazz);
    }
    @Override
    public Fragment getItem(int position) {
        return StudentList.newInstance(mFragmentTitleList.get(position));
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position).getName();
    }
}
</code>```

my RecyclerView adapter class

```<code>public class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.MyViewHolder> implements View.OnClickListener {
    private List<Student> dataList;
    private Context context;
    private Clicker clicker;
    public PeopleAdapter(List<Student> data, Context context, Clicker clicker) {
        this.dataList = data;
        this.context = context;
        this.clicker = clicker;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.people_list_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Student data=dataList.get(position);
        holder.email.setText(data.getEmail());
        holder.name.setText(data.getName());
        holder.phone.setText(data.getPhone());
        Glide.with(context).load(Method.getImageUrl(MyConfiguration.STUDENT_IMAGE_URL,
                data.getStudentId())).asBitmap().into(holder.profilePic);
        holder.edit.setOnClickListener(this);
        holder.edit.setTag(position);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    @Override
    public void onClick(View v) {
        clicker.OnItemClicked((int) v.getTag(),null);
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.name)
        TextView name;
        @BindView(R.id.email)
        TextView email;
        @BindView(R.id.phone)
        TextView phone;
        @BindView(R.id.image)
        ImageView profilePic;
        @BindView(R.id.imageedit)
        ImageView edit;
    MyViewHolder(View view) {
        super(view);
        ButterKnife.bind(this,view);
    }
}

}
</code>```

tab fragments

```<code>    public class StudentList extends Fragment implements SectionChanger {
        @BindView(R.id.studentlist)
        RecyclerView mRecyclerview;
        CompositeDisposable disposable;
        private Unbinder unbinder;
        private Clazz clazz;
        private Requester requester;

        public StudentList() {
            StudentInformation.bindSectionChangeListener(this);
        }
        public static StudentList newInstance(Clazz clazz) {
            StudentList fragment=new StudentList();
            Bundle args = new Bundle();
            args.putSerializable(MyConfiguration.SECTIONS, clazz);
            fragment.setArguments(args);
            return fragment;
        }
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            unbinder.unbind();
            disposable.clear();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_student_list, container, false);
            unbinder = ButterKnife.bind(this, view);
            LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
            mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecyclerview.setLayoutManager(mLayoutManager);
            initializeRetrofit();
            if (getArguments() != null) {
                clazz = (Clazz) getArguments().getSerializable(MyConfiguration.SECTIONS);
                loadStudentJson(clazz != null ? clazz.getClassId() : null,
                        clazz != null ? clazz.getSections().get(0).getSectionId() : null);
            }
            return view;
        }

        /**
         * Load students list
         */
        public void loadStudentJson(String class_id,String section_id) {

            disposable = new CompositeDisposable(requester.getStudentsInSection(class_id,section_id)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(
                            this::handleResponse,
                            this::handleError
                    )
            );
        }

        private void handleResponse(List<Student> list) {
            PeopleAdapter adapter=new PeopleAdapter(list, getActivity(),
                    (position, name) -> Toast.makeText(getActivity(), position, Toast.LENGTH_LONG).show());
            mRecyclerview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

        private void handleError(Throwable error) {
            Toast.makeText(getActivity(), "Error " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void ChangeData(Section section) {
            loadStudentJson(section.getClassId(),section.getSectionId());
        }
        public void initializeRetrofit(){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            CookieHandler handler=new Cookies(getActivity());
            //ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .cookieJar(new JavaNetCookieJar(handler))
                    .build();

            requester = new Retrofit.Builder()
                    .baseUrl(MyConfiguration.BASE_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(JacksonConverterFactory.create())
                    .client(client)
                    .build().create(Requester.class);
        }
    }
</code>```

Viewpager setup fragment

```<code>public class StudentInformation extends Fragment implements TabLayout.OnTabSelectedListener, AdapterView.OnItemSelectedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private Unbinder unbinder;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    CompositeDisposable disposable;
    List<Section> sectionsList=new ArrayList<>();
    private OnConnectingFragments mListener;
    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.secSelector)
    Spinner spinner;
    @BindView(R.id.className)
    TextView className;
    private static SectionChanger sectionChanger;
    public StudentInformation() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment StudentInformation.
     */
    // TODO: Rename and change types and number of parameters
    public static StudentInformation newInstance(String param1, String param2) {
        StudentInformation fragment = new StudentInformation();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        disposable.clear();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_student_information, container, false);
        unbinder = ButterKnife.bind(this, view);
        LoadDataAndSetupViewPager();
        //setupViewPager(viewPager);
        mTabLayout.setupWithViewPager(viewPager);
        mTabLayout.addOnTabSelectedListener(this);
        spinner.setOnItemSelectedListener(this);
//        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, MyConfiguration.CLASS_SECTIONS);
//        spinner.setAdapter(arrayAdapter);

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Fragment fragment,String tag) {
        if (mListener != null) {
            mListener.onClickedMenu(fragment,tag);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnConnectingFragments) {
            mListener = (OnConnectingFragments) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    /*private void setupViewPager(ViewPager viewPager) {
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (String claz: MyConfiguration.CLASS)
            adapter.addFragment(new StudentList(), claz);
        viewPager.setAdapter(adapter);
    }*/
    @OnClick(R.id.add)
    public void OnClicked(LinearLayout view){
        onButtonPressed(new AddStudent(),"addStudent");
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        className.setText(String.format(getString(R.string.class_name), tab.getPosition()+1));
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

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

    }
    public void LoadDataAndSetupViewPager() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Requester requester=new Retrofit.Builder()
                .baseUrl(MyConfiguration.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .client(client)
                .build().create(Requester.class);
        disposable=new CompositeDisposable(requester.getClasses()    ////GETTING CLASSES////
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .flatMapIterable(clazzs -> clazzs)
                .flatMap(clazz -> requester.getDivision(clazz.getClassId())  ////GETTING SECTIONS////
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .flatMapIterable(sections -> sections)
                        .doOnNext(section -> {sectionsList.add(section);
                            Log.v("section_id",section.getSectionId());})
                        .takeLast(1)
                        .map(section -> clazz)
                )
                .doOnNext(clazz -> {clazz.setSections(sectionsList);
                    Log.v("List Size",sectionsList.size()+"");
                    sectionsList=new ArrayList<>();
                })
                .toList()
                .subscribe(this::SetupViewPager, throwable -> Log.e("retroerror",throwable.toString())));

    }
    public void SetupViewPager(List<Clazz> classList){
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (Clazz claz: classList){
            adapter.addFragment(new StudentList(), claz);
        }

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                List<Section>sections=classList.get(position).getSections();
                ArrayAdapter<Section> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, sections);
                spinner.setAdapter(arrayAdapter);
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Section section= (Section) parent.getItemAtPosition(position);
                sectionChanger.ChangeData(section);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public static void bindSectionChangeListener(SectionChanger changer){
        sectionChanger=changer;
    }
}
</code>```

The question is: Why the data get unchanged when selecting options in the spinner sometimes? (look my cases)

答:
When you work with recycleview rely only on your model class filed values. Do all the changes to model class and create row views based on this model class fields.

i.e, you have to create or change values or view state based on the value of the model class fields.

For ex: if you want to make a row (position 30) invisible, then i will set a flag in model class called visibility and set it to false.

in this case whenever view redraws in UI, we will have to check for the flag and set the visibility based on that model class field value.

Like this you can create flags, content values, serialized params from API etc in model class. This method will make your reclycleview more consistent through out user interactions and API changes.

Title: RecyclerView Items are not changing

Body:
I have a RecyclerView in a fragment which is repeating in TabLayout. I am having the problem of unchanged view in RecyclerView. I have a spinner on each tab. I want to change the data when spinner items get selected.

My cases:

when switching between tabs - items changed

when selecting another value in the spinner in the first tab -items not changed. (but data is changing in adapter class.Ie. First, it is not null then null during selection. But the first not nulled data is not appearing, its replacing with null. Found it using breakpoints).

Note: In this case, when switching the tab, the items get changed to
  the spinner selected items in the previous tab. And then it disappears
  and displaying the current items in the tab.

when selecting another value in the spinner in the last tab -items changed.

My view pager adapter class

public class StudentViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<StudentList> mFragmentList = new ArrayList<>();
    private final List<Clazz> mFragmentTitleList = new ArrayList<>();
    public StudentViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    public void addFragment(StudentList fragment,Clazz clazz){
        mFragmentList.add(fragment);
        mFragmentTitleList.add(clazz);
    }
    @Override
    public Fragment getItem(int position) {
        return StudentList.newInstance(mFragmentTitleList.get(position));
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position).getName();
    }
}

my RecyclerView adapter class

public class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.MyViewHolder> implements View.OnClickListener {
    private List<Student> dataList;
    private Context context;
    private Clicker clicker;
    public PeopleAdapter(List<Student> data, Context context, Clicker clicker) {
        this.dataList = data;
        this.context = context;
        this.clicker = clicker;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.people_list_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Student data=dataList.get(position);
        holder.email.setText(data.getEmail());
        holder.name.setText(data.getName());
        holder.phone.setText(data.getPhone());
        Glide.with(context).load(Method.getImageUrl(MyConfiguration.STUDENT_IMAGE_URL,
                data.getStudentId())).asBitmap().into(holder.profilePic);
        holder.edit.setOnClickListener(this);
        holder.edit.setTag(position);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    @Override
    public void onClick(View v) {
        clicker.OnItemClicked((int) v.getTag(),null);
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.name)
        TextView name;
        @BindView(R.id.email)
        TextView email;
        @BindView(R.id.phone)
        TextView phone;
        @BindView(R.id.image)
        ImageView profilePic;
        @BindView(R.id.imageedit)
        ImageView edit;
    MyViewHolder(View view) {
        super(view);
        ButterKnife.bind(this,view);
    }
}

}

tab fragments

    public class StudentList extends Fragment implements SectionChanger {
        @BindView(R.id.studentlist)
        RecyclerView mRecyclerview;
        CompositeDisposable disposable;
        private Unbinder unbinder;
        private Clazz clazz;
        private Requester requester;

        public StudentList() {
            StudentInformation.bindSectionChangeListener(this);
        }
        public static StudentList newInstance(Clazz clazz) {
            StudentList fragment=new StudentList();
            Bundle args = new Bundle();
            args.putSerializable(MyConfiguration.SECTIONS, clazz);
            fragment.setArguments(args);
            return fragment;
        }
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            unbinder.unbind();
            disposable.clear();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_student_list, container, false);
            unbinder = ButterKnife.bind(this, view);
            LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
            mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecyclerview.setLayoutManager(mLayoutManager);
            initializeRetrofit();
            if (getArguments() != null) {
                clazz = (Clazz) getArguments().getSerializable(MyConfiguration.SECTIONS);
                loadStudentJson(clazz != null ? clazz.getClassId() : null,
                        clazz != null ? clazz.getSections().get(0).getSectionId() : null);
            }
            return view;
        }

        /**
         * Load students list
         */
        public void loadStudentJson(String class_id,String section_id) {

            disposable = new CompositeDisposable(requester.getStudentsInSection(class_id,section_id)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(
                            this::handleResponse,
                            this::handleError
                    )
            );
        }

        private void handleResponse(List<Student> list) {
            PeopleAdapter adapter=new PeopleAdapter(list, getActivity(),
                    (position, name) -> Toast.makeText(getActivity(), position, Toast.LENGTH_LONG).show());
            mRecyclerview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

        private void handleError(Throwable error) {
            Toast.makeText(getActivity(), "Error " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void ChangeData(Section section) {
            loadStudentJson(section.getClassId(),section.getSectionId());
        }
        public void initializeRetrofit(){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            CookieHandler handler=new Cookies(getActivity());
            //ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .cookieJar(new JavaNetCookieJar(handler))
                    .build();

            requester = new Retrofit.Builder()
                    .baseUrl(MyConfiguration.BASE_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(JacksonConverterFactory.create())
                    .client(client)
                    .build().create(Requester.class);
        }
    }

Viewpager setup fragment

public class StudentInformation extends Fragment implements TabLayout.OnTabSelectedListener, AdapterView.OnItemSelectedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private Unbinder unbinder;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    CompositeDisposable disposable;
    List
 sectionsList=new ArrayList<>();
    private OnConnectingFragments mListener;
    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.secSelector)
    Spinner spinner;
    @BindView(R.id.className)
    TextView className;
    private static SectionChanger sectionChanger;
    public StudentInformation() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment StudentInformation.
     */
    // TODO: Rename and change types and number of parameters
    public static StudentInformation newInstance(String param1, String param2) {
        StudentInformation fragment = new StudentInformation();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        disposable.clear();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_student_information, container, false);
        unbinder = ButterKnife.bind(this, view);
        LoadDataAndSetupViewPager();
        //setupViewPager(viewPager);
        mTabLayout.setupWithViewPager(viewPager);
        mTabLayout.addOnTabSelectedListener(this);
        spinner.setOnItemSelectedListener(this);
//        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, MyConfiguration.CLASS_SECTIONS);
//        spinner.setAdapter(arrayAdapter);

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Fragment fragment,String tag) {
        if (mListener != null) {
            mListener.onClickedMenu(fragment,tag);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnConnectingFragments) {
            mListener = (OnConnectingFragments) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    /*private void setupViewPager(ViewPager viewPager) {
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (String claz: MyConfiguration.CLASS)
            adapter.addFragment(new StudentList(), claz);
        viewPager.setAdapter(adapter);
    }*/
    @OnClick(R.id.add)
    public void OnClicked(LinearLayout view){
        onButtonPressed(new AddStudent(),"addStudent");
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        className.setText(String.format(getString(R.string.class_name), tab.getPosition()+1));
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

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

    }
    public void LoadDataAndSetupViewPager() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Requester requester=new Retrofit.Builder()
                .baseUrl(MyConfiguration.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .client(client)
                .build().create(Requester.class);
        disposable=new CompositeDisposable(requester.getClasses()    ////GETTING CLASSES////
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .flatMapIterable(clazzs -> clazzs)
                .flatMap(clazz -> requester.getDivision(clazz.getClassId())  ////GETTING SECTIONS////
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .flatMapIterable(sections -> sections)
                        .doOnNext(section -> {sectionsList.add(section);
                            Log.v("section_id",section.getSectionId());})
                        .takeLast(1)
                        .map(section -> clazz)
                )
                .doOnNext(clazz -> {clazz.setSections(sectionsList);
                    Log.v("List Size",sectionsList.size()+"");
                    sectionsList=new ArrayList<>();
                })
                .toList()
                .subscribe(this::SetupViewPager, throwable -> Log.e("retroerror",throwable.toString())));

    }
    public void SetupViewPager(List<Clazz> classList){
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (Clazz claz: classList){
            adapter.addFragment(new StudentList(), claz);
        }

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                List
sections=classList.get(position).getSections();
                ArrayAdapter
 arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, sections);
                spinner.setAdapter(arrayAdapter);
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Section section= (Section) parent.getItemAtPosition(position);
                sectionChanger.ChangeData(section);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public static void bindSectionChangeListener(SectionChanger changer){
        sectionChanger=changer;
    }
}

The question is: Why the data get unchanged when selecting options in the spinner sometimes? (look my cases)


来源: stackexchange

问:
How to extract substrings from each line in text file?
I have a text file in the following format (1 line):

[NN] ||| transplant ||| transplantation ||| PPDB2.0Score=5.24981 PPDB1.0Score=3.295900 -logp(LHS|e1)=0.18597 -logp(LHS|e2)=0.14031 -logp(e1|LHS)=11.83583 -logp(e1|e2)=1.80507 -logp(e1|e2,LHS)=1.46728 -logp(e2|LHS)=11.47593 -logp(e2|e1)=1.49083 -logp(e2|e1,LHS)=1.10738 AGigaSim=0.63439 Abstract=0 Adjacent=0 CharCountDiff=5 CharLogCR=0.40547 ContainsX=0 Equivalence=0.371472 Exclusion=0.000344 GlueRule=0 GoogleNgramSim=0.03067 Identity=0 Independent=0.078161 Lex(e1|e2)=9.64663 Lex(e2|e1)=59.48919 Lexical=1 LogCount=4.67283 MVLSASim=NA Monotonic=1 OtherRelated=0.372735 PhrasePenalty=1 RarityPenalty=0 ForwardEntailment=0.177287 SourceTerminalsButNoTarget=0 SourceWords=1 TargetComplexity=0.98821 TargetFormality=0.98464 TargetTerminalsButNoSource=0 TargetWords=1 UnalignedSource=0 UnalignedTarget=0 WordCountDiff=0 WordLenDiff=5.00000 WordLogCR=0 ||| 0-0 ||| OtherRelated

What I want is to extract transplant and transplantation. How would you do that? Each line in the text file is varying in length for the values between the ||| separator. To illustrate, here is a second example:

[VBZ] ||| reflects ||| understand ||| PPDB2.0Score=3.50769 PPDB1.0Score=21.844910 -logp(LHS|e1)=0.01251 -logp(LHS|e2)=10.87470 -logp(e1|LHS)=6.91653 -logp(e1|e2)=11.53225 -logp(e1|e2,LHS)=4.29729 -logp(e2|LHS)=16.55913 -logp(e2|e1)=10.31266 -logp(e2|e1,LHS)=13.93988 AGigaSim=0.54532 Abstract=0 Adjacent=0 CharCountDiff=2 CharLogCR=0.22314 ContainsX=0 Equivalence=0.006535 Exclusion=0.022332 GlueRule=0 GoogleNgramSim=0 Identity=0 Independent=0.456621 Lex(e1|e2)=62.90141 Lex(e2|e1)=62.90141 Lexical=1 LogCount=0 MVLSASim=NA Monotonic=1 OtherRelated=0.404562 PhrasePenalty=1 RarityPenalty=0.36788 ForwardEntailment=0.109950 SourceTerminalsButNoTarget=0 SourceWords=1 TargetComplexity=0.99354 TargetFormality=1.00000 TargetTerminalsButNoSource=0 TargetWords=1 UnalignedSource=0 UnalignedTarget=0 WordCountDiff=0 WordLenDiff=2.00000 WordLogCR=0 ||| 0-0 ||| Independent

The target words here are reflects and understands.

答:
Split by ' ||| '?

your_text.split(' ||| ') Would give you a list of elements separated by ' ||| '

So

your_text.split(' ||| ')[1:3] would return ['reflects','understands']

ContentLicense: CC BY-SA 3.0


问:
html/jquery how to hover div with its child when mouseenter
my idea is to create this:
https://blog.hubspot.com/hs-fs/hubfs/dubsat-contact-us-cities.gif?t=1490783992392&width=690&height=585&name=dubsat-contact-us-cities.gif

but the text has to be in div's with a picture not just fading in and fading out pictures. heres my shot:

#first{
    position: absolute;

}
#second{
    position: absolute;

    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
    position: absolute;
}
.text-box {
    position: absolute;
    height: 100%;
    text-align: center;
    width: 100%;
}
.text-box:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>

    </head>
    <h1 id="third">Kontaktai</h1>
    <!-- <div class="image">-->

    <div id="first" onmouseenter="showSecondImage()" onmouseleave="hideSecondImage()">
        <h4 class="text-box ">whyyyy</h4>
        <img class="img-responsive" src="http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/H-P/photoark-lion.png.adapt.945.1.jpg" >
    </div>

    <div id="second">
        <h4 class="text-box">why its not working</h4>
        <img class="img-responsive" src="http://i.dailymail.co.uk/i/pix/2015/06/09/16/03BB5E5A0000044D-3117010-image-a-25_1433862086692.jpg" >
    </div>
    <script>
        $(".unbinded").unbind();
        function  showSecondImage() {
            document.getElementById('second').style.opacity=1;
        }
        function  hideSecondImage() {
            document.getElementById('second').style.opacity=0;
        }
    </script></code>```

why is not not working properly? i though i need to unbind onmouseenter and onmouseleave eventlisteners and bind the picture to listen when mouse enters..  any answers appreciated, im new to this.

答:
Like Coker says, You can do it only with CSS, and the pseudo-selector :hover.

            div
            {
                width:500px;
                height: 200px;
                cursor: pointer;
                background-size: cover;
                transition: background-image .6s ease-in-out;
            }
            .first
            {
                background-image: url("http://apopka.uhcpqdoe6fq4wtztv.netdna-cdn.com/wp-content/uploads/2016/03/spring-daffodils_2845661b.jpg");
            }
            .second
            {
                background-image: url("http://www.twitrcovers.com/wp-content/uploads/2012/11/Winter-snow-l.jpg");
            }
            .first:hover
            {
                background-image: url("http://trucosparadecorar.com/wp-content/uploads/2016/09/oto%C3%B1o2.jpg");
            }
            .second:hover
            {
                background-image: url("http://cadenaser00.epimg.net/ser/imagenes/2016/06/20/sociedad/1466419875_801497_1466420115_noticia_normal.jpg");
            }
            div p
            {
                color: white;
                text-align: center;
                font-size: 24px;
                position: relative;
                text-shadow: 1px 1px 10px black;
                top: 43%;
            }
            div:hover .hidden
            {
                display:block;
            }
            .hidden
            {
                display:none;
                font-size: 14px;
            }
            .shadow:hover
            {
                background: rgba(0,0,0,0.3);
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Hola</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <div class="first">
            <div class="shadow">
                <p>Spring of Field</p>
                <p class="hidden">Spring is wonderful, unless for allergic people that die each year by.</p>
            </div>
        </div>
        <div class="second">
            <div class="shadow">
                <p>Snow world</p>
                <p class="hidden">Go in winter, after the snow doesn't exist anymore.</p>
            </div>
        </div>
    </body>
</html></code>```

Body:
my idea is to create this:
https://blog.hubspot.com/hs-fs/hubfs/dubsat-contact-us-cities.gif?t=1490783992392&width=690&height=585&name=dubsat-contact-us-cities.gif

but the text has to be in div's with a picture not just fading in and fading out pictures. heres my shot:

#first{
    position: absolute;

}
#second{
    position: absolute;

    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
    position: absolute;
}
.text-box {
    position: absolute;
    height: 100%;
    text-align: center;
    width: 100%;
}
.text-box:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

Kontaktai

whyyyy

why its not working

why is not not working properly? i though i need to unbind onmouseenter and onmouseleave eventlisteners and bind the picture to listen when mouse enters..  any answers appreciated, im new to this.

Body:
Like Coker says, You can do it only with CSS, and the pseudo-selector :hover.

            div
            {
                width:500px;
                height: 200px;
                cursor: pointer;
                background-size: cover;
                transition: background-image .6s ease-in-out;
            }
            .first
            {
                background-image: url("http://apopka.uhcpqdoe6fq4wtztv.netdna-cdn.com/wp-content/uploads/2016/03/spring-daffodils_2845661b.jpg");
            }
            .second
            {
                background-image: url("http://www.twitrcovers.com/wp-content/uploads/2012/11/Winter-snow-l.jpg");
            }
            .first:hover
            {
                background-image: url("http://trucosparadecorar.com/wp-content/uploads/2016/09/oto%C3%B1o2.jpg");
            }
            .second:hover
            {
                background-image: url("http://cadenaser00.epimg.net/ser/imagenes/2016/06/20/sociedad/1466419875_801497_1466420115_noticia_normal.jpg");
            }
            div p
            {
                color: white;
                text-align: center;
                font-size: 24px;
                position: relative;
                text-shadow: 1px 1px 10px black;
                top: 43%;
            }
            div:hover .hidden
            {
                display:block;
            }
            .hidden
            {
                display:none;
                font-size: 14px;
            }
            .shadow:hover
            {
                background: rgba(0,0,0,0.3);
            }

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Hola</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <div class="first">
            <div class="shadow">
                <p>Spring of Field</p>
                <p class="hidden">Spring is wonderful, unless for allergic people that die each year by.</p>
            </div>
        </div>
        <div class="second">
            <div class="shadow">
                <p>Snow world</p>
                <p class="hidden">Go in winter, after the snow doesn't exist anymore.</p>
            </div>
        </div>
    </body>
</html>


问:
Loading a table of texture from unity folder scripting while running on android device
i can load images from external urls and save them into my unity project folder when i run it on my pc (unity player scene) it works perfectly i can load the images located in my project into a table of textures and display it but it's not working while running on android device .it won't load images into texture

```<code>DirectoryInfo info = new DirectoryInfo(@"Assets\Photos\");
    int nbImage;

    nbImage = info.GetFiles("*.jpg").Length;
    Debug.Log(nbImage);
    Textures = new Texture2D[nbImage];
    for (int i = 0; i < nbImage; i++)
    {
        string e = Application.streamingAssetsPath + "/" + i + ".jpg";
        byte[] bytes;
        bytes = System.IO.File.ReadAllBytes(e);
        load_s01_texture = new Texture2D(1, 1);
        load_s01_texture.LoadImage(bytes);
        Textures[i] = load_s01_texture as Texture2D;

    }
</code>```

this how it looks on my pc
and this how it looks on my phone

答:
The directory "Assets\Photos" exists when you are running the project in the Editor, but it doesn't exist on the Android phone.

If you want to load images or other resources at run time, you have to use the resources folder.

Here's a useful example of how to use it

Body:
i can load images from external urls and save them into my unity project folder when i run it on my pc (unity player scene) it works perfectly i can load the images located in my project into a table of textures and display it but it's not working while running on android device .it won't load images into texture

DirectoryInfo info = new DirectoryInfo(@"Assets\Photos\");
    int nbImage;

    nbImage = info.GetFiles("*.jpg").Length;
    Debug.Log(nbImage);
    Textures = new Texture2D[nbImage];
    for (int i = 0; i < nbImage; i++)
    {
        string e = Application.streamingAssetsPath + "/" + i + ".jpg";
        byte[] bytes;
        bytes = System.IO.File.ReadAllBytes(e);
        load_s01_texture = new Texture2D(1, 1);
        load_s01_texture.LoadImage(bytes);
        Textures[i] = load_s01_texture as Texture2D;

    }

this how it looks on my pc
and this how it looks on my phone


问:
How to remove the error from the powershell report
i have created a powershell script to run image validation remotely and when any of the service found in stopped state this will fail the script.I am getting below error while failing the script.Is there anyway so that I can hide these error from the report?

```<code>+ Invoke-Command  -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], RuntimeException
    + FullyQualifiedErrorId : ScriptHalted
</code>```

This is the script i used to fail when the service is in stopped state.

```<code>$EMService = get-wmiobject win32_service | where-object {($_.Name -eq 'HP12cAgent') -or ($_.Name -eq 'HPagent12c2Agent') -or ($_.Name -eq 'HPagent10gAgent') -or ($_.Name -eq 'FarmEM10gAgent') -or ($_.Name -eq 'FarmEM11gAgent')} | format-list name | Out-String
$Servicename = $EMService.Split(":")[1].Trim()

$EMStatus1 = get-wmiobject win32_service | where-object {$_.Name -eq $Servicename} | format-list state | Out-String
$ServiceStatus = $EMStatus1.Split(":")[1].Trim()

if ($Servicename -eq $null)

{
$Servicename = "Unavailable"

}
else
{

$Servicename = "$Servicename"

}

if ($ServiceStatus -eq "Stopped")

{

throw

}

Else

{
exit 0
}
</code>```

答:
You can always try wrapping stuff in a try/catch block.</p>

```<code>try {  some powershell stuff }
catch { Write-Host $_ ; or do nothing }
</code>```

Body:
i have created a powershell script to run image validation remotely and when any of the service found in stopped state this will fail the script.I am getting below error while failing the script.Is there anyway so that I can hide these error from the report?

+ Invoke-Command  -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], RuntimeException
    + FullyQualifiedErrorId : ScriptHalted

This is the script i used to fail when the service is in stopped state.

$EMService = get-wmiobject win32_service | where-object {($_.Name -eq 'HP12cAgent') -or ($_.Name -eq 'HPagent12c2Agent') -or ($_.Name -eq 'HPagent10gAgent') -or ($_.Name -eq 'FarmEM10gAgent') -or ($_.Name -eq 'FarmEM11gAgent')} | format-list name | Out-String
$Servicename = $EMService.Split(":")[1].Trim()

$EMStatus1 = get-wmiobject win32_service | where-object {$_.Name -eq $Servicename} | format-list state | Out-String
$ServiceStatus = $EMStatus1.Split(":")[1].Trim()

if ($Servicename -eq $null)

{
$Servicename = "Unavailable"

}
else
{

$Servicename = "$Servicename"

}

if ($ServiceStatus -eq "Stopped")

{

throw

}

Else

{
exit 0
}

Body:
You can always try wrapping stuff in a try/catch block.

try {  some powershell stuff }
catch { Write-Host $_ ; or do nothing }


问:
Get folder location for windows dynamically in python 3.5
I am creating a small script that removes unwanted browser trackers from the C:\Users\username\AppData\Local\Microsoft\Windows\INetCache location. The problem is I cant seem to get to AppData\Local.

when running this:

```<code>os.getenv('APPDATA')
</code>```

I get this output: C:\Users\username\AppData\Roaming

I need to remove \Roaming so that i can get lower in the \Local tree. How do I dynamically get to the above location exclusively on windows 10 and 7 using python 3.5?

答:
It seems like you should be able to do this using os.path.dirname:

```<code>roaming = os.getenv('APPDATA')
app_data = os.path.dirname(roaming)
</code>```

If you can't be sure to trust the environment variable, but are sure that the path you want will always end in AppData, then you can keep removing path parts until you find the part you want:

```<code>app_data = os.getenv('APPDATA')
while app_data and not app_data.endswith('AppData'):
    app_data = os.path.dirname(app_data)
</code>```

Body:
I am creating a small script that removes unwanted browser trackers from the C:\Users\username\AppData\Local\Microsoft\Windows\INetCache location. The problem is I cant seem to get to AppData\Local.

when running this:

os.getenv('APPDATA')

I get this output: C:\Users\username\AppData\Roaming

I need to remove \Roaming so that i can get lower in the \Local tree. How do I dynamically get to the above location exclusively on windows 10 and 7 using python 3.5?

Body:
It seems like you should be able to do this using os.path.dirname:

roaming = os.getenv('APPDATA')
app_data = os.path.dirname(roaming)

If you can't be sure to trust the environment variable, but are sure that the path you want will always end in AppData, then you can keep removing path parts until you find the part you want:

app_data = os.getenv('APPDATA')
while app_data and not app_data.endswith('AppData'):
    app_data = os.path.dirname(app_data)


问:
Add marker to Google Map on Click
I'm struggling to find a very simple example of how to add a marker(s) to a Google Map when a user left clicks on the map.</p>

答:
In 2017, the solution is:

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    map.panTo(position);
}
```

ContentLicense: CC BY-SA 4.0

Title: Add marker to Google Map on Click


问:
C# How to wrap date string in single quote inside the string's double quotes
I am trying to wrap my DateTime's date format in single quotes

e.g. DateTime.Now().ToString("yyyy-MM-dd") output will be like "2017-03-30"

My question, Is there anyway of producing the result like "'2017-03-30'" (i-e single quotes within the double quotes)?

答:
Try it with string.Format:

```<code>string.Format("'{0:yyyy-MM-dd}'", DateTime.Now)
</code>```

Body:
Try it with string.Format:

string.Format("'{0:yyyy-MM-dd}'", DateTime.Now)


问:
Why doesnt this xPath (c#) work?
Got this xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

And this xpath:

```<code>videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;
</code>```

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...

答:
Your XML contains namespace specification, you need to modify your source to take that into consideration.

Example:

```<code>XmlDocument doc = new XmlDocument();
doc.Load("doc.xml");
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("ns", "UploadXSD");

videoToAdd.Title = doc.SelectSingleNode(@"/ns:video/ns:title", xmlnsManager).InnerXml;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Why doesnt this xPath (c#) work?

Body:
Got this xml:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

And this xpath:

videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...

Body:
Your XML contains namespace specification, you need to modify your source to take that into consideration.

Example:

XmlDocument doc = new XmlDocument();
doc.Load("doc.xml");
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("ns", "UploadXSD");

videoToAdd.Title = doc.SelectSingleNode(@"/ns:video/ns:title", xmlnsManager).InnerXml;


问:
syntax for reusable function types in function declarations
This is how you annotate a variable / constant as holding a function of a particular type:

```<code>declare type TFunction = () => any;
const foo: TFunction = function foo() {};
</code>```

What is the syntax when one declares a function:

```<code>function boo() {}
</code>```

?

答:
There's no way to put: TFunction on your function boo() declaration.  However, you can flow check it by writing the no-op statement (boo: TFunction); afterward.  The only drawback is this evaluates boo at runtime.

Probably the best way to do it though is to not worry about explicitly declaring that boo is a TFunction, and instead just rely on Flow to check it any time you use boo where a TFunction is expected.

Here's a more concrete example of what I mean: (Try flow link)

```<code>/* @flow */

type ArithmeticOperation = (a: number, b: number) => number;

function add(a: number, b: number): number {
  return a + b;
}

function concat(a: string, b: string): string {
  return a + b;
}

function fold(array: Array<number>, operation: ArithmeticOperation): number {
  return array.reduce(operation);
}

fold([1, 2, 3], add); // ok because add matches ArithmeticOperation
fold([1, 2, 3], concat); // flow error because concat doesn't match
</code>```

Body:
This is how you annotate a variable / constant as holding a function of a particular type:

declare type TFunction = () => any;
const foo: TFunction = function foo() {};

What is the syntax when one declares a function:

function boo() {}

?

Body:
There's no way to put: TFunction on your function boo() declaration.  However, you can flow check it by writing the no-op statement (boo: TFunction); afterward.  The only drawback is this evaluates boo at runtime.

Probably the best way to do it though is to not worry about explicitly declaring that boo is a TFunction, and instead just rely on Flow to check it any time you use boo where a TFunction is expected.

Here's a more concrete example of what I mean: (Try flow link)

/* @flow */

type ArithmeticOperation = (a: number, b: number) => number;

function add(a: number, b: number): number {
  return a + b;
}

function concat(a: string, b: string): string {
  return a + b;
}

function fold(array: Array<number>, operation: ArithmeticOperation): number {
  return array.reduce(operation);
}

fold([1, 2, 3], add); // ok because add matches ArithmeticOperation
fold([1, 2, 3], concat); // flow error because concat doesn't match


问:
react setState does not update the state us expected
I have a react component that looks like this:

```<code>class MyComponent extends Component {
  incrementQty = () => {
    // calls this.setState({....})
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}
</code>```

My problem is that the state does not be updated until the last call in the loop, I knew that setState is asynchronous and I can't use redux here to rerender the component after an action is dispatched.

Has anyone has a solution, and thanks.

答:
Internal state changing does not happen synchronously, you're right. Any change to internal state is queued up until at least after the current function call. So what's happening is your several calls to setState are merged into one big increment.

What is it that you need to access state again before a re-render? Rather than just incrementing the quantity, it might be better to just set the quantity initially in component state, rather than using a for loop. If you then want to increment up one value at a time, use the lifecycle methods - perhaps componentDidUpdate - to increment a second counter once each render until the correct value for qty is reached.

Body:
I have a react component that looks like this:

class MyComponent extends Component {
  incrementQty = () => {
    // calls this.setState({....})
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}

My problem is that the state does not be updated until the last call in the loop, I knew that setState is asynchronous and I can't use redux here to rerender the component after an action is dispatched.

Has anyone has a solution, and thanks.


问:
Javascript shorthand loading time
I was playing around so I ran into a JS shorthands. I know they, of course, do not change code however do they lower loading time since there is less data?

Testing codes such as one below in Chrome DOM inspector did not give me an answer (probably because they are one-line codes so it does not make any difference).

```<code>if (x == 0) {x=1} else {x=2}
x == 0 ? x = 1 : x = 2;
</code>```

答:
If your goal is to optimize the speed with which your page loads by minimizing the size of your JS payload, there are lots of tools that will automatically rebuild your files into a single bundle that is compressed (i.e., all unnecessary whitespace removed, variables/functions renamed to shorter lengths, etc.). When it comes to writing code, you should always value readability first.

Write code that other people can easily understand. Then, when you're ready to deploy, look into a tool like UglifyJS2, which will enable you to take code like this:

```<code>function square(numToSquare) {
    var squareProduct = numToSquare * numToSquare;

    return squareProduct;
}

square(15);
</code>```

..and turn it into this:

```<code>function square(r){return r*r}square(15);
</code>```

Title: Javascript shorthand loading time

Body:
I was playing around so I ran into a JS shorthands. I know they, of course, do not change code however do they lower loading time since there is less data?

Testing codes such as one below in Chrome DOM inspector did not give me an answer (probably because they are one-line codes so it does not make any difference).

if (x == 0) {x=1} else {x=2}
x == 0 ? x = 1 : x = 2;

Body:
If your goal is to optimize the speed with which your page loads by minimizing the size of your JS payload, there are lots of tools that will automatically rebuild your files into a single bundle that is compressed (i.e., all unnecessary whitespace removed, variables/functions renamed to shorter lengths, etc.). When it comes to writing code, you should always value readability first.

Write code that other people can easily understand. Then, when you're ready to deploy, look into a tool like UglifyJS2, which will enable you to take code like this:

function square(numToSquare) {
    var squareProduct = numToSquare * numToSquare;

    return squareProduct;
}

square(15);

..and turn it into this:

function square(r){return r*r}square(15);


问:
who is responsible for symbolic reference linker or loader
I have read a lot of article about linker or loader but<br>
I am confuse who is responsible to replace absolute reference in an object module by symbolic  references to location in other object modules.
Does linker replace symbolic reference in other object module or loader make this at program loading time in main memory </p>

答: Resolving symbol dependencies between object modules has traditionally been the responsibility of the linker. The linker examines all object files and resolves all symbolic references and builds a monolithic executable. However, this approach breaks down when we introduce shared libraries, i.e. object modules that can be shared between different executables and that are linked to the program at load time. To make this work some parts of the linker is moved into the loader, making the resolution of dependencies as shared responsibility. The linker resolves dependencies between the object files and static libraries while the loader resolves dependencies between the executable and any shared library.</p>

Body:
I have read a lot of article about linker or loader but

I am confuse who is responsible to replace absolute reference in an object module by symbolic  references to location in other object modules.
Does linker replace symbolic reference in other object module or loader make this at program loading time in main memory


问:
Android Push Notifications: Icon not displaying in notification, white square shown instead
My app generates a notification, but the icon I set for that notification is not being displayed. Instead, I get a white square.

I have tried resizing the png of the icon (dimensions 720x720, 66x66, 44x44, 22x22). Curiously, when using smaller dimensions the white square is smaller.

I have googled this problem, as well as the correct way of generating notifications, and from what I've read my code should be correct. Sadly things are not as they should be.

My phone is a Nexus 5 with Android 5.1.1. The problem is also present on emulators, a Samsung Galaxy s4 with Android 5.0.1 and a Motorola Moto G with Android 5.0.1 (both of which I borrowed, and don't have right now)

The code for notifications follows, and two screenshots. If you require more information, please feel free to ask for it.

Thank you all.

```<code>@SuppressLint("NewApi") private void sendNotification(String msg, String title, String link, Bundle bundle) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.putExtras(bundle);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            resultIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    Notification notification;
    Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound);
    notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.lg_logo)
                .setContentTitle(title)
                .setStyle(new Notification.BigTextStyle().bigText(msg))
                .setAutoCancel(true)
                .setContentText(msg)
                .setContentIntent(contentIntent)
                .setSound(sound)
                .build();
    notificationManager.notify(0, notification);
}
</code>```

答:
Finally I've got the solution for this issue.

This issue occurs only when the app is not at all running. (neither in  the background nor in the foreground). When the app runs on either foreground or background the notification icon is displayed properly.(not the white square)

So what we've to set is the same configuration for notification icon in Backend APIs as that of Frontend.

In the frontend we've used React Native and for push notification we've used react-native-fcm npm package.

```<code>FCM.on("notification", notif => {
   FCM.presentLocalNotification({
       body: notif.fcm.body,
       title: notif.fcm.title,
       big_text: notif.fcm.body,
       priority: "high",
       large_icon: "notification_icon", // notification icon
       icon: "notification_icon",
       show_in_foreground: true,
       color: '#8bc34b',
       vibrate: 300,
       lights: true,
       status: notif.status
   });
});
</code>```

We've used fcm-push npm package using Node.js as a backend for push notification and set the payload structure as follows.

```<code>{
  to: '/topics/user', // required
  data: {
    id:212,
    message: 'test message',
    title: 'test title'
  },
  notification: {
    title: 'test title',
    body: 'test message',
    icon : 'notification_icon', // same name as mentioned in the front end
    color : '#8bc34b',
    click_action : "BROADCAST"
  }
}
</code>```

What it basically searches for the notification_icon image stored locally in our Android system.

Body:
My app generates a notification, but the icon I set for that notification is not being displayed. Instead, I get a white square.

I have tried resizing the png of the icon (dimensions 720x720, 66x66, 44x44, 22x22). Curiously, when using smaller dimensions the white square is smaller.

I have googled this problem, as well as the correct way of generating notifications, and from what I've read my code should be correct. Sadly things are not as they should be.

My phone is a Nexus 5 with Android 5.1.1. The problem is also present on emulators, a Samsung Galaxy s4 with Android 5.0.1 and a Motorola Moto G with Android 5.0.1 (both of which I borrowed, and don't have right now)

The code for notifications follows, and two screenshots. If you require more information, please feel free to ask for it.

Thank you all.

@SuppressLint("NewApi") private void sendNotification(String msg, String title, String link, Bundle bundle) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.putExtras(bundle);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            resultIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    Notification notification;
    Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound);
    notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.lg_logo)
                .setContentTitle(title)
                .setStyle(new Notification.BigTextStyle().bigText(msg))
                .setAutoCancel(true)
                .setContentText(msg)
                .setContentIntent(contentIntent)
                .setSound(sound)
                .build();
    notificationManager.notify(0, notification);
}

Body:
Finally I've got the solution for this issue.

This issue occurs only when the app is not at all running. (neither in  the background nor in the foreground). When the app runs on either foreground or background the notification icon is displayed properly.(not the white square)

So what we've to set is the same configuration for notification icon in Backend APIs as that of Frontend.

In the frontend we've used React Native and for push notification we've used react-native-fcm npm package.

FCM.on("notification", notif => {
   FCM.presentLocalNotification({
       body: notif.fcm.body,
       title: notif.fcm.title,
       big_text: notif.fcm.body,
       priority: "high",
       large_icon: "notification_icon", // notification icon
       icon: "notification_icon",
       show_in_foreground: true,
       color: '#8bc34b',
       vibrate: 300,
       lights: true,
       status: notif.status
   });
});

We've used fcm-push npm package using Node.js as a backend for push notification and set the payload structure as follows.

{
  to: '/topics/user', // required
  data: {
    id:212,
    message: 'test message',
    title: 'test title'
  },
  notification: {
    title: 'test title',
    body: 'test message',
    icon : 'notification_icon', // same name as mentioned in the front end
    color : '#8bc34b',
    click_action : "BROADCAST"
  }
}

What it basically searches for the notification_icon image stored locally in our Android system.


问:
COMMTIMEOUT and Thread not timming out on serial port Read function
I am calling a function that operates an I/o board through a serial port to check that it is communicating in an instance of my main class.

I know that this is risky but unfortunately this is an old section of code that has been used for a while so I am unable to alter the functionality while I have been asked to improve it.

If there is no communication issue the application will start up, use the function and continue with no issue.

The problem arises when there is a communication fault with the I/o board, I have found that the read function is hanging and stopping the app from starting for the majority of the time. On occasion the app will load and will report that there is a communication fault.

What I am trying to achieve is for the application to load successfully every time when there is a communication fault.

The comport is set up with COMMTIMEOUTs originally which I expected would timeout the port when there has been nothing to read. I have attempted to alter the timings but with no avail.

I have also attempted to use a thread for the read function so that it would not block the start up but still it hangs.

Currently the port is set up synchronously.

Has anybody got any suggestions? I can put some code examples up if required.

Main.cpp

```<code>extern COMPort comPort;
BOOL Main::InitInstance()
{
 int i = comPort.DoorLatchOff();
 If(i<0) printf("Error checksum. COM port?\n");
 else printf("checksum ok.\n");
}
</code>```

COMPort.h

```<code>class CCOMPort
{
  public:
   CCOMPort (COM_PORT port = NULL_COM, DCB * state = NULL);
   BOOL SetPortNumber (COM_PORT port = NULL_COM, DCB * state = NULL);
   void Read(BYTE* buff, int count);
   int DoorLatchOff(void);
  protected:
   HANDLE    m_hPort;
};
static HANDLE    m_hPortThreaded;
typedef struct readParam{BYTE* readBuff;int readCount;}RP, *PRP;

DWORD WINAPI ThreadedRead( LPVOID lpParam );
</code>```

COMPort.cpp

```<code>CCOMPort::CCOMPort (COM_PORT port, DCB * state) : m_portNum (port), m_hPort(INVALID_HANDLE_VALUE)
{
 SetPortNumber (port, state);
}
BOOL CCOMPort::SetPortNumber (COM_PORT port, DCB * state)
{
  if (m_hPort != INVALID_HANDLE_VALUE){
    ::CloseHandle (m_hPort);
    m_hPort = INVALID_HANDLE_VALUE;
  }

   m_portNum     = port;
   m_currState   = m_defState;
   m_originState = m_defState;

  if (m_portNum != NULL_COM){
  stringstream ssPortName;
  ssPortName << "COM" << (m_portNum + 1) << ":" << flush;

  m_hPort = ::CreateFile (ssPortName.str().c_str(),
                         GENERIC_READ | GENERIC_WRITE,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
                          NULL);

  if (m_hPort == INVALID_HANDLE_VALUE)
    return FALSE;
  else
    {
      GetState (& m_originState);

     if (state)
      m_currState = * state;
     SetState (& m_currState);

     GetCommTimeouts(m_hPort, &timeouts);

     timeouts.ReadIntervalTimeout = 75; //15
     timeouts.ReadTotalTimeoutMultiplier = 5;       //1
     timeouts.ReadTotalTimeoutConstant = 1250;      //250
     timeouts.WriteTotalTimeoutMultiplier = 5;      //1
     timeouts.WriteTotalTimeoutConstant = 1250;     //250
     SetCommTimeouts(m_hPort, &timeouts);
     FlushOutput ();
     FlushInput ();
     PurgeOutput ();
     PurgeInput ();
    }
  }

  return TRUE;
}
void CCOMPort::Read(BYTE* buff, int count)
{
  PRP pReadArray[1];
  DWORD dwThreadArray[1];
  HANDLE hThreadArray[1];
  m_hPortThreaded = m_hPort;

  pReadArray[0] = (PRP) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RP));

  if(pReadArray[0] == NULL){
    ExitProcess(2);
  }

  pReadArray[0]->readBuff = buff;
  pReadArray[0]->readCount = count;
  hThreadArray[0] = CreateThread(NULL,
                                    0,
                         ThreadedRead,
                        pReadArray[0],
                                    0,
                   &dwThreadArray[0]);

  if(hThreadArray[0] == NULL){
    ExitProcess(3);
  }

  WaitForSingleObject(hThreadArray[0],500/*INFINITE*/);
  CloseHandle(hThreadArray[0]);

  if(pReadArray[0] != NULL){
    HeapFree(GetProcessHeap(), 0, pReadArray[0]);
    pReadArray[0] = NULL;
  }
}

DWORD WINAPI ThreadedRead(LPVOID lpParam)
{
  BOOL bDone = FALSE, bResult;
  //int buff_idx = 0;
  DWORD dwCommModemStatus;
  DWORD dwBytesTransfered;

  PRP pReadArray;
  pReadArray = (PRP)lpParam;
  SetCommMask(m_hPortThreaded, EV_RXCHAR);
  while(!bDone){
    WaitCommEvent(m_hPortThreaded, &dwCommModemStatus, 0);
    if(dwCommModemStatus == 0){
    bDone = TRUE;
    break;
    }
    if(dwCommModemStatus & EV_RXCHAR){
      bResult = ReadFile(m_hPortThreaded, pReadArray[0].readBuff, pReadArray[0].readCount, &dwBytesTransfered, 0);
      bDone = TRUE;
    }
  }
  return(bResult);

}
int COMPort::DoorLatchOff(void)
{
  unsigned char comm_str[10];
  int chksum, chksum1;
  DWORD count = 6;

  WriteComm(21, 7, 0);
  comm.Read(comm_str, count);

  chksum = comm_str[0] + comm_str[2] + comm_str[3];
  chksum1 = comm_str[4];
  chksum1 = (chksum1 << 8) | comm_str[5];

  if(chksum == chksum1)
   return(0);
  else
   return(-1);
}
</code>```

答:
Please, could you try to remove the WaitCommEvent function from ThreadedRead and see if it still hangs?</p>

```<code>DWORD WINAPI ThreadedRead(LPVOID lpParam)
{
    BOOL bResult;
    DWORD dwBytesTransfered = 0;

    PRP pReadArray;
    pReadArray = (PRP)lpParam;

    while (dwBytesTransfered == 0) {
        bResult = ReadFile(m_hPortThreaded, pReadArray[0].readBuff, pReadArray[0].readCount, &dwBytesTransfered, 0);

        Sleep(250);
    }

    return(bResult);
}
</code>```

Body:
I am calling a function that operates an I/o board through a serial port to check that it is communicating in an instance of my main class.

I know that this is risky but unfortunately this is an old section of code that has been used for a while so I am unable to alter the functionality while I have been asked to improve it.

If there is no communication issue the application will start up, use the function and continue with no issue.

The problem arises when there is a communication fault with the I/o board, I have found that the read function is hanging and stopping the app from starting for the majority of the time. On occasion the app will load and will report that there is a communication fault.

What I am trying to achieve is for the application to load successfully every time when there is a communication fault.

The comport is set up with COMMTIMEOUTs originally which I expected would timeout the port when there has been nothing to read. I have attempted to alter the timings but with no avail.

I have also attempted to use a thread for the read function so that it would not block the start up but still it hangs.

Currently the port is set up synchronously.

Has anybody got any suggestions? I can put some code examples up if required.

Main.cpp

extern COMPort comPort;
BOOL Main::InitInstance()
{
 int i = comPort.DoorLatchOff();
 If(i<0) printf("Error checksum. COM port?\n");
 else printf("checksum ok.\n");
}

COMPort.h

class CCOMPort
{
  public:
   CCOMPort (COM_PORT port = NULL_COM, DCB * state = NULL);
   BOOL SetPortNumber (COM_PORT port = NULL_COM, DCB * state = NULL);
   void Read(BYTE* buff, int count);
   int DoorLatchOff(void);
  protected:
   HANDLE    m_hPort;
};
static HANDLE    m_hPortThreaded;
typedef struct readParam{BYTE* readBuff;int readCount;}RP, *PRP;

DWORD WINAPI ThreadedRead( LPVOID lpParam );

COMPort.cpp

CCOMPort::CCOMPort (COM_PORT port, DCB * state) : m_portNum (port), m_hPort(INVALID_HANDLE_VALUE)
{
 SetPortNumber (port, state);
}
BOOL CCOMPort::SetPortNumber (COM_PORT port, DCB * state)
{
  if (m_hPort != INVALID_HANDLE_VALUE){
    ::CloseHandle (m_hPort);
    m_hPort = INVALID_HANDLE_VALUE;
  }

   m_portNum     = port;
   m_currState   = m_defState;
   m_originState = m_defState;

  if (m_portNum != NULL_COM){
  stringstream ssPortName;
  ssPortName << "COM" << (m_portNum + 1) << ":" << flush;

  m_hPort = ::CreateFile (ssPortName.str().c_str(),
                         GENERIC_READ | GENERIC_WRITE,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
                          NULL);

  if (m_hPort == INVALID_HANDLE_VALUE)
    return FALSE;
  else
    {
      GetState (& m_originState);

     if (state)
      m_currState = * state;
     SetState (& m_currState);

     GetCommTimeouts(m_hPort, &timeouts);

     timeouts.ReadIntervalTimeout = 75; //15
     timeouts.ReadTotalTimeoutMultiplier = 5;       //1
     timeouts.ReadTotalTimeoutConstant = 1250;      //250
     timeouts.WriteTotalTimeoutMultiplier = 5;      //1
     timeouts.WriteTotalTimeoutConstant = 1250;     //250
     SetCommTimeouts(m_hPort, &timeouts);
     FlushOutput ();
     FlushInput ();
     PurgeOutput ();
     PurgeInput ();
    }
  }

  return TRUE;
}
void CCOMPort::Read(BYTE* buff, int count)
{
  PRP pReadArray[1];
  DWORD dwThreadArray[1];
  HANDLE hThreadArray[1];
  m_hPortThreaded = m_hPort;

  pReadArray[0] = (PRP) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RP));

  if(pReadArray[0] == NULL){
    ExitProcess(2);
  }

  pReadArray[0]->readBuff = buff;
  pReadArray[0]->readCount = count;
  hThreadArray[0] = CreateThread(NULL,
                                    0,
                         ThreadedRead,
                        pReadArray[0],
                                    0,
                   &dwThreadArray[0]);

  if(hThreadArray[0] == NULL){
    ExitProcess(3);
  }

  WaitForSingleObject(hThreadArray[0],500/*INFINITE*/);
  CloseHandle(hThreadArray[0]);

  if(pReadArray[0] != NULL){
    HeapFree(GetProcessHeap(), 0, pReadArray[0]);
    pReadArray[0] = NULL;
  }
}

DWORD WINAPI ThreadedRead(LPVOID lpParam)
{
  BOOL bDone = FALSE, bResult;
  //int buff_idx = 0;
  DWORD dwCommModemStatus;
  DWORD dwBytesTransfered;

  PRP pReadArray;
  pReadArray = (PRP)lpParam;
  SetCommMask(m_hPortThreaded, EV_RXCHAR);
  while(!bDone){
    WaitCommEvent(m_hPortThreaded, &dwCommModemStatus, 0);
    if(dwCommModemStatus == 0){
    bDone = TRUE;
    break;
    }
    if(dwCommModemStatus & EV_RXCHAR){
      bResult = ReadFile(m_hPortThreaded, pReadArray[0].readBuff, pReadArray[0].readCount, &dwBytesTransfered, 0);
      bDone = TRUE;
    }
  }
  return(bResult);

}
int COMPort::DoorLatchOff(void)
{
  unsigned char comm_str[10];
  int chksum, chksum1;
  DWORD count = 6;

  WriteComm(21, 7, 0);
  comm.Read(comm_str, count);

  chksum = comm_str[0] + comm_str[2] + comm_str[3];
  chksum1 = comm_str[4];
  chksum1 = (chksum1 << 8) | comm_str[5];

  if(chksum == chksum1)
   return(0);
  else
   return(-1);
}

Body:
Please, could you try to remove the WaitCommEvent function from ThreadedRead and see if it still hangs?

DWORD WINAPI ThreadedRead(LPVOID lpParam)
{
    BOOL bResult;
    DWORD dwBytesTransfered = 0;

    PRP pReadArray;
    pReadArray = (PRP)lpParam;

    while (dwBytesTransfered == 0) {
        bResult = ReadFile(m_hPortThreaded, pReadArray[0].readBuff, pReadArray[0].readCount, &dwBytesTransfered, 0);

        Sleep(250);
    }

    return(bResult);
}


问:
Redhat openJDK 1.9 (Windows) - "Illegal char" in "java.activation"?
This is just a 'hello world sort of spring app. I am getting the error:

```<code>Information:java: Errors occurred while compiling module 'restjpademo'
Information:javac 9.0.0.1-redhatea was used to compile java sources
Information:30/03/2017 09:01 - Compilation completed with 1 error and 0 warnings in 3s 181ms
Error:java: Illegal char <:> at index 3: jrt:\C:\Program Files\RedHat\java-1.9.0-openjdk-1.9.0.0-1!\java.activation
</code>```

This is with a fresh install from the openjdk msi download, in intelli-j idea 2017.1, on windows 10 Educational edition (basically 10 Pro but with no Cortana).

This appears to be related to intelli-j's jdk.table.xml configuration file which it autogenerates when you select openJDK 1.9:

it begins:

```<code><application>
  <component name="ProjectJdkTable">
    <jdk version="2">
      <name value="9.0" />
      <type value="JavaSDK" />
      <version value="java version "9.0.0.1-redhatea"" />
      <homePath value="C:/Program Files/RedHat/java-1.9.0-openjdk-1.9.0.0-1" />
      <roots>
        <annotationsPath>
          <root type="composite">
            <root type="simple" url="jar://$APPLICATION_HOME_DIR$/lib/jdkAnnotations.jar!/" />
          </root>
        </annotationsPath>
        <classPath>
          <root type="composite">
            <root type="simple" url="jrt://C:/Program Files/RedHat/java-1.9.0-openjdk-1.9.0.0-1!/java.activation" />
</code>```

答:
It's a bug in IntelliJ IDEA 2017.1:

IDEA-170307 Cannot compile any plugin in IDEA 2017.1 and JDK9ea

Body:
This is just a 'hello world sort of spring app. I am getting the error:

Information:java: Errors occurred while compiling module 'restjpademo'
Information:javac 9.0.0.1-redhatea was used to compile java sources
Information:30/03/2017 09:01 - Compilation completed with 1 error and 0 warnings in 3s 181ms
Error:java: Illegal char <:> at index 3: jrt:\C:\Program Files\RedHat\java-1.9.0-openjdk-1.9.0.0-1!\java.activation

This is with a fresh install from the openjdk msi download, in intelli-j idea 2017.1, on windows 10 Educational edition (basically 10 Pro but with no Cortana).

This appears to be related to intelli-j's jdk.table.xml configuration file which it autogenerates when you select openJDK 1.9:

it begins:

<application>
  <component name="ProjectJdkTable">
    <jdk version="2">
      <name value="9.0" />
      <type value="JavaSDK" />
      <version value="java version "9.0.0.1-redhatea"" />
      <homePath value="C:/Program Files/RedHat/java-1.9.0-openjdk-1.9.0.0-1" />
      <roots>
        <annotationsPath>
          <root type="composite">
            <root type="simple" url="jar://$APPLICATION_HOME_DIR$/lib/jdkAnnotations.jar!/" />
          </root>
        </annotationsPath>
        <classPath>
          <root type="composite">
            <root type="simple" url="jrt://C:/Program Files/RedHat/java-1.9.0-openjdk-1.9.0.0-1!/java.activation" />


问:
Adding XML Node to all Rows in a Table
I have a table with a column ID and a column XMLData. Unfortunately, the XML data column does not currently have any reference to the ID inside the XML itself, so if I export this column only and parse it, I would not be able to tie it back to the ID.

I am trying to added a node to the XML similar to below:

```<code><AddedNode>
    <Id>10862832</Id>
</AddedNode>
</code>```

Which would allow for the ID to be parsed from the XML itself, and be connected back. I tried adding the data via the below method:

```<code>With Test_CTE (Id, XMLData, AddedXML)
As
(
select Id, XMLData, cast('<AddedNode>
            <Id>' + cast(Id as varchar(20)) + '</Id>
        </AddedNode>' as varchar(max)) as AddedXML
from dbo.TestTable
)

update T
set XMLData.modify('insert ' + CTE.AddedXML + '
        as last into (/RootNode[1])
')
from dbo.TestTable T
inner join Test_CTE CTE on CTE.Id = T.Id
</code>```

But I receive the error "The argument 1 of the XML data type method "modify" must be a string literal."

I'm sure this has to do with me trying to pull the insert node via a column of data, but could anyone tell me how to fix it?

NOTE: I realize that I could also complete this via a while loop over entire table using variables, but there are ~2.5 million rows in the table and it would take longer than I want.

答:
If I get this correctly, this can be done much easier:

```<code>DECLARE @testtable TABLE(ID INT IDENTITY, XMLData XML);
INSERT INTO @testtable VALUES('<root><a>test</a></root>')
                            ,('<root><a>test</a><b>Some other</b></root>');

UPDATE @testtable SET XMLData.modify(N'insert <AddedNode><Id>{sql:column("ID")}</Id></AddedNode> as first into (/root)[1]');

SELECT * FROM @testtable;
</code>```

The result

```<code>ID  XMLData
1   <root>
      <AddedNode>
        <Id>1</Id>
      </AddedNode>
      <a>test</a>
    </root>

2   <root>
      <AddedNode>
        <Id>2</Id>
      </AddedNode>
      <a>test</a>
      <b>Some other</b>
    </root>
</code>```

UPDATE

Your own approach might be corrected to this (never build XML via string concatenation!):

```<code>WITH Test_CTE AS
(
    SELECT XMLData
         ,(SELECT ID AS [Id] FOR XML PATH('AddedNode'),TYPE)  as AddedXML
    FROM dbo.TestTable
)
UPDATE Test_CTE SET XMLData.modify(N'insert sql:column("AddedXML") as first into (/root)[1]');

SELECT * FROM dbo.TestTable;
</code>```

Title: Adding XML Node to all Rows in a Table

Body:
I have a table with a column ID and a column XMLData. Unfortunately, the XML data column does not currently have any reference to the ID inside the XML itself, so if I export this column only and parse it, I would not be able to tie it back to the ID.

I am trying to added a node to the XML similar to below:

<AddedNode>
    <Id>10862832</Id>
</AddedNode>

Which would allow for the ID to be parsed from the XML itself, and be connected back. I tried adding the data via the below method:

With Test_CTE (Id, XMLData, AddedXML)
As
(
select Id, XMLData, cast('<AddedNode>
            <Id>' + cast(Id as varchar(20)) + '</Id>
        </AddedNode>' as varchar(max)) as AddedXML
from dbo.TestTable
)

update T
set XMLData.modify('insert ' + CTE.AddedXML + '
        as last into (/RootNode[1])
')
from dbo.TestTable T
inner join Test_CTE CTE on CTE.Id = T.Id

But I receive the error "The argument 1 of the XML data type method "modify" must be a string literal."

I'm sure this has to do with me trying to pull the insert node via a column of data, but could anyone tell me how to fix it?

NOTE: I realize that I could also complete this via a while loop over entire table using variables, but there are ~2.5 million rows in the table and it would take longer than I want.

Body:
If I get this correctly, this can be done much easier:

DECLARE @testtable TABLE(ID INT IDENTITY, XMLData XML);
INSERT INTO @testtable VALUES('<root><a>test</a></root>')
                            ,('<root><a>test</a><b>Some other</b></root>');

UPDATE @testtable SET XMLData.modify(N'insert <AddedNode><Id>{sql:column("ID")}</Id></AddedNode> as first into (/root)[1]');

SELECT * FROM @testtable;

The result

ID  XMLData
1   <root>
      <AddedNode>
        <Id>1</Id>
      </AddedNode>
      <a>test</a>
    </root>

2   <root>
      <AddedNode>
        <Id>2</Id>
      </AddedNode>
      <a>test</a>
      <b>Some other</b>
    </root>

UPDATE

Your own approach might be corrected to this (never build XML via string concatenation!):

WITH Test_CTE AS
(
    SELECT XMLData
         ,(SELECT ID AS [Id] FOR XML PATH('AddedNode'),TYPE)  as AddedXML
    FROM dbo.TestTable
)
UPDATE Test_CTE SET XMLData.modify(N'insert sql:column("AddedXML") as first into (/root)[1]');

SELECT * FROM dbo.TestTable;


问:
Insert a field with value whenever new instance of modal is created
I want to insert a field with value whenever new row is created for a modal.

Ex:  Suppose this is my user.php modal

```<code>class User extends Authenticatable
{
 protected $guarded = ['id'];
}
</code>```

What i want is in my application anywhere when i insert a row in user table, then i want to insert an extra column code with its value in user table.

Ex: If i do below in my application

```<code>User::create(['name'=>'xyz', 'password' => 'kajsndjk']);
</code>```

then it should insert an extra column code =>'Qwedf' also in my table.

In my application there are many places where i am creating the users, so i don't want to remember every time to insert code column.

Please suggest how can i achieve it.

答:
Overriding the static create function on the User class is the only thing that will work in my opinion.

```<code>public static function create(array $attributes = [])
{
   $object = parent::create($attributes);
   $object->code = 'some text';
   $object->save();

   return $object;
}
</code>```

I've tested and like I expected, oseintow's answer will not work, because it would work only if you directly modified code variable, which you obviously are not doing.

Body:
I want to insert a field with value whenever new row is created for a modal.

Ex:  Suppose this is my user.php modal

class User extends Authenticatable
{
 protected $guarded = ['id'];
}

What i want is in my application anywhere when i insert a row in user table, then i want to insert an extra column code with its value in user table.

Ex: If i do below in my application

User::create(['name'=>'xyz', 'password' => 'kajsndjk']);

then it should insert an extra column code =>'Qwedf' also in my table.

In my application there are many places where i am creating the users, so i don't want to remember every time to insert code column.

Please suggest how can i achieve it.

Body:
Overriding the static create function on the User class is the only thing that will work in my opinion.

public static function create(array $attributes = [])
{
   $object = parent::create($attributes);
   $object->code = 'some text';
   $object->save();

   return $object;
}

I've tested and like I expected, oseintow's answer will not work, because it would work only if you directly modified code variable, which you obviously are not doing.


问:
Python Recursive Example Explanation
So currently working through MIT's OpenCourseWare computer science course online and I am having trouble trying to understand one of the recursive examples.

```<code>def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            return f(e)
return result
</code>```

When the following input is given:

```<code>print f([1, [[2, 'a'], ['a','b']], (3, 4)])
</code>```

The output is:

```<code>[2, 'a']
</code>```

I am having trouble trying to understand how this function actually works or what it is doing. Shouldn't the function eventually be adding every string or int into the result list? I just need help with trying to understand how this function "winds up" and "unwinds"

I feel like the output should be:

```<code>[1,2,'a','a','b',3,4]
</code>```

Any help would be appreciated thanks!

答:
The function f returns a (shallow) copy of the first flat list it encounters with depth first search.

Why? Well first let us take a look at the base case: a list that contains no lists. Like [1,'a',2,5]. In that case the the if statement will always succeed, and therefore all elements of e will be added to the result and the result is returned.

Now what about the recursive case. This means there is an element that is a list. Like for instance [1,['a',2],5]. Now for the first element, the if succeeds, so 1 is added to the result list. But for the second element ['a',2] the if fails. This means we perform a recursive call on f with ['a',2]. Now since that list does not contain any sublists, we know it will return a copy of that list.

Note however that we immediately return the result of that recursive call. So from the moment we take the else branch, the result is of no importance anymore: we will return what that f(e) returns.

If we make the assumption we cannot construct a loop of infinite deep sublists (actually we can, but in that case we will get a stack overflow exception), we will eventually obtain a flat list and obtain that copy.

Example: If we take your sample input [1, [[2, 'a'], ['a','b']], (3, 4)]. We can trace the calls. So we first call f on that list, it will generate the following "trace":

```<code># **trace** of an example function call
f([1, [[2, 'a'], ['a','b']], (3, 4)]):
    result = []
    # for 1 in L:
    # if type(1) == list: # fails
    # else
    result.append(1) # result is now [1]
    # for [[2,'a'],['a','b']] in L:
    # if type([[2,'a'],['a','b']]) == list: succeeds
    <b>return</b> f([[2,'a'],['a','b']])
                      result = []
                      # for [2,'a'] in L:
                      # if type([2,'a']) == list: succeeds
                      <b>return</b> f([2,'a'])
                                        result = []
                                        # for 2 in L:
                                        # if type(2) == list: fails
                                        # else:
                                        result.append(2) # result is now [2]
                                        # for 'a' in [2,'a']:
                                        # if type('a') == list: fails
                                        # else:
                                        result.append('a') # result is now [2,'a']
                                        <b>return</b> [2,'a']
                      <b>return</b> [2,'a']
    <b>return</b> [2,'a']</code>```

Flattening:

Given you wanted to flatten the list instead of returning the first flat list, you can rewrite the code to:

```<code>def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            <b>result +=</b> f(e)
    return result</code>```

Note that this will only flatten lists (and not even subclasses of lists).

Title: Python Recursive Example Explanation

Body:
So currently working through MIT's OpenCourseWare computer science course online and I am having trouble trying to understand one of the recursive examples.

def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            return f(e)
return result

When the following input is given:

print f([1, [[2, 'a'], ['a','b']], (3, 4)])

The output is:

[2, 'a']

I am having trouble trying to understand how this function actually works or what it is doing. Shouldn't the function eventually be adding every string or int into the result list? I just need help with trying to understand how this function "winds up" and "unwinds"

I feel like the output should be:

[1,2,'a','a','b',3,4]

Any help would be appreciated thanks!

Body:
The function f returns a (shallow) copy of the first flat list it encounters with depth first search.

Why? Well first let us take a look at the base case: a list that contains no lists. Like [1,'a',2,5]. In that case the the if statement will always succeed, and therefore all elements of e will be added to the result and the result is returned.

Now what about the recursive case. This means there is an element that is a list. Like for instance [1,['a',2],5]. Now for the first element, the if succeeds, so 1 is added to the result list. But for the second element ['a',2] the if fails. This means we perform a recursive call on f with ['a',2]. Now since that list does not contain any sublists, we know it will return a copy of that list.

Note however that we immediately return the result of that recursive call. So from the moment we take the else branch, the result is of no importance anymore: we will return what that f(e) returns.

If we make the assumption we cannot construct a loop of infinite deep sublists (actually we can, but in that case we will get a stack overflow exception), we will eventually obtain a flat list and obtain that copy.

Example: If we take your sample input [1, [[2, 'a'], ['a','b']], (3, 4)]. We can trace the calls. So we first call f on that list, it will generate the following "trace":

# **trace** of an example function call
f([1, [[2, 'a'], ['a','b']], (3, 4)]):
    result = []
    # for 1 in L:
    # if type(1) == list: # fails
    # else
    result.append(1) # result is now [1]
    # for [[2,'a'],['a','b']] in L:
    # if type([[2,'a'],['a','b']]) == list: succeeds
    return f([[2,'a'],['a','b']])
                      result = []
                      # for [2,'a'] in L:
                      # if type([2,'a']) == list: succeeds
                      return f([2,'a'])
                                        result = []
                                        # for 2 in L:
                                        # if type(2) == list: fails
                                        # else:
                                        result.append(2) # result is now [2]
                                        # for 'a' in [2,'a']:
                                        # if type('a') == list: fails
                                        # else:
                                        result.append('a') # result is now [2,'a']
                                        return [2,'a']
                      return [2,'a']
    return [2,'a']

Flattening:

Given you wanted to flatten the list instead of returning the first flat list, you can rewrite the code to:

def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            result += f(e)
    return result

Note that this will only flatten lists (and not even subclasses of lists).