问:
How do I fix this null pointer exception?
I'm a newbie to Android, and I'm using a ListView. No problem when scrolling the ListView slowly. But when I scroll it quickly, app crash occurs.

Can anyone help me?

Stack trace:

```<code> FATAL EXCEPTION: main
  Process: com.beco.ibeco, PID: 1764
  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      at com.beco.ibeco.app.account.ProfileFragmentNew$HelpListAdapter.getView(ProfileFragmentNew.java:417)
      at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
      at android.widget.AbsListView.obtainView(AbsListView.java:2346)
      at android.widget.ListView.makeAndAddView(ListView.java:1876)
      at android.widget.ListView.fillDown(ListView.java:702)
      at android.widget.ListView.fillGap(ListView.java:666)
      at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5106)
      at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3463)
      at android.widget.AbsListView.onTouchMove(AbsListView.java:3878)
      at android.widget.AbsListView.onTouchEvent(AbsListView.java:3691)
      at android.view.View.dispatchTouchEvent(View.java:9306)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2548)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2241)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2405)
      at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
      at android.app.Activity.dispatchTouchEvent(Activity.java:2820)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2366)
      at android.view.View.dispatchPointerEvent(View.java:9526)
      at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4262)
      at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4128)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
      at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3814)
      at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3696)
      at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3871)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
    at android.view.ViewRootI
</code>```

Code:

```<code>private class HelpListAdapter extends ArrayAdapter {

    private Holder holder;
    private Context context;

    public HelpListAdapter(Context context, int resource) {
        super(context, resource);
        this.context = context;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            holder = new Holder();
            if (position == 3) {
                view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
                holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
                holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
            } else {
                view = View.inflate(getContext(), R.layout.list_item_text, null);
                holder.textView = (TextView) view.findViewById(R.id.text);
            }
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (position != 3) {
            holder.textView.setText(mHelpLabels.get(position));
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

            };
            holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

        } else {
            holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
            holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
                setListViewHeight(parentExpand, groupPosition);
                return false;
            });
        }

        return view;
    }

    class Holder {
        TextView textView;
        ExpandableListView expandableListView;
        LinearLayout containerList;
    }

    private void setListViewHeight(ExpandableListView listView, int group) {

        ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
        int height = 0;
        int groupCount = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        View groupItem = listAdapter.getGroupView(groupCount, false, null, listView);
        groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        height += groupItem.getMeasuredHeight();

        if (((listView.isGroupExpanded(groupCount)) && (groupCount != group))
                || ((!listView.isGroupExpanded(groupCount)) && (groupCount == group))) {
            for (int j = 0; j < listAdapter.getChildrenCount(groupCount); j++) {
                View listItem = listAdapter.getChildView(groupCount, j, false, null, listView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        if (height < 10)
            height = 200;
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    class ExpandableListAdapter extends BaseExpandableListAdapter {

        Context context;
        String title;
        View viewParent;

        ExpandableListAdapter(Context context, String title, View view) {
            this.context = context;
            this.title = title;
            this.viewParent = view;
        }

        @Override
        public String getChild(int groupPosition, int childPosititon) {
            return mContactLabels.get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(), R.drawable.ic_email, R.color.beco_icon_tint_color, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_phone_black, R.color.beco_icon_tint_color, PorterDuff.Mode.DST_IN)};

            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText(mContactLabels.get(childPosition));
            textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[childPosition], null, null, null);
            textView.setOnClickListener(v -> {
                switch (childPosition) {
                    case 0:
                        Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
                        intentEmail.setData(Uri.fromParts("mailto", mContactLabels.get(childPosition), null));
                        intentEmail.putExtra(Intent.EXTRA_SUBJECT, "Contact beCo");
                        startActivity(intentEmail);
                        break;
                    case 1:
                        Intent intentCall = new Intent(Intent.ACTION_DIAL);
                        intentCall.setData(Uri.parse("tel:" + mContactLabels.get(childPosition)));
                        startActivity(intentCall);
                        break;
                }
            });

            return view;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mContactLabels.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mContactLabels.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return 1;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            TextView contact = (TextView) view.findViewById(R.id.text);
            contact.setText(title);
            Drawable iconLeft = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_contact_blue, R.color.beco_white, PorterDuff.Mode.DST_IN);
            contact.setCompoundDrawablesWithIntrinsicBounds(null,null,iconLeft,null);

            LinearLayout border = (LinearLayout) viewParent.findViewById(R.id.container_expandable_list);

            Drawable iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_down_black, R.color.beco_black, PorterDuff.Mode.DST_IN);

            if (isExpanded) {
                border.setBackgroundResource(R.drawable.border);
                iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_up_black, R.color.beco_black, PorterDuff.Mode.DST_IN);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_primary));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);

            } else {
                border.setBackgroundResource(0);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_label_color));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);
            }

            return view;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}
</code>```

答:
The problem is probably arising due to setting the listview height programmatically; when it does that, the views from the items are redrawed while holding the viewholders. In the case of position 3, the viewholder of a position 4 will have null reference to the textview, causing it to crash.

I suggest you to not use different layouts for items in a ListView (or GridView). I once had the same problem you had, causing the layouts to appear broken. Instead, use only one layout; if you need to hide some elements, like a TextView, you can do it programmatically:

```<code>holder.textview.setVisibility(View.INVISIBLE); //or View.GONE
</code>```

There are some good tutorials related to ExpandableListViews too:

http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/

http://theopentutorials.com/tutorials/android/listview/android-expandable-list-view-example/

Body:
I'm a newbie to Android, and I'm using a ListView. No problem when scrolling the ListView slowly. But when I scroll it quickly, app crash occurs.

Can anyone help me?

Stack trace:

 FATAL EXCEPTION: main
  Process: com.beco.ibeco, PID: 1764
  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      at com.beco.ibeco.app.account.ProfileFragmentNew$HelpListAdapter.getView(ProfileFragmentNew.java:417)
      at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
      at android.widget.AbsListView.obtainView(AbsListView.java:2346)
      at android.widget.ListView.makeAndAddView(ListView.java:1876)
      at android.widget.ListView.fillDown(ListView.java:702)
      at android.widget.ListView.fillGap(ListView.java:666)
      at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5106)
      at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3463)
      at android.widget.AbsListView.onTouchMove(AbsListView.java:3878)
      at android.widget.AbsListView.onTouchEvent(AbsListView.java:3691)
      at android.view.View.dispatchTouchEvent(View.java:9306)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2548)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2241)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2405)
      at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
      at android.app.Activity.dispatchTouchEvent(Activity.java:2820)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2366)
      at android.view.View.dispatchPointerEvent(View.java:9526)
      at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4262)
      at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4128)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
      at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3814)
      at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3696)
      at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3871)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
    at android.view.ViewRootI

Code:

private class HelpListAdapter extends ArrayAdapter {

    private Holder holder;
    private Context context;

    public HelpListAdapter(Context context, int resource) {
        super(context, resource);
        this.context = context;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            holder = new Holder();
            if (position == 3) {
                view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
                holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
                holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
            } else {
                view = View.inflate(getContext(), R.layout.list_item_text, null);
                holder.textView = (TextView) view.findViewById(R.id.text);
            }
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (position != 3) {
            holder.textView.setText(mHelpLabels.get(position));
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

            };
            holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

        } else {
            holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
            holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
                setListViewHeight(parentExpand, groupPosition);
                return false;
            });
        }

        return view;
    }

    class Holder {
        TextView textView;
        ExpandableListView expandableListView;
        LinearLayout containerList;
    }

    private void setListViewHeight(ExpandableListView listView, int group) {

        ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
        int height = 0;
        int groupCount = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        View groupItem = listAdapter.getGroupView(groupCount, false, null, listView);
        groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        height += groupItem.getMeasuredHeight();

        if (((listView.isGroupExpanded(groupCount)) && (groupCount != group))
                || ((!listView.isGroupExpanded(groupCount)) && (groupCount == group))) {
            for (int j = 0; j < listAdapter.getChildrenCount(groupCount); j++) {
                View listItem = listAdapter.getChildView(groupCount, j, false, null, listView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        if (height < 10)
            height = 200;
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    class ExpandableListAdapter extends BaseExpandableListAdapter {

        Context context;
        String title;
        View viewParent;

        ExpandableListAdapter(Context context, String title, View view) {
            this.context = context;
            this.title = title;
            this.viewParent = view;
        }

        @Override
        public String getChild(int groupPosition, int childPosititon) {
            return mContactLabels.get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(), R.drawable.ic_email, R.color.beco_icon_tint_color, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_phone_black, R.color.beco_icon_tint_color, PorterDuff.Mode.DST_IN)};

            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText(mContactLabels.get(childPosition));
            textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[childPosition], null, null, null);
            textView.setOnClickListener(v -> {
                switch (childPosition) {
                    case 0:
                        Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
                        intentEmail.setData(Uri.fromParts("mailto", mContactLabels.get(childPosition), null));
                        intentEmail.putExtra(Intent.EXTRA_SUBJECT, "Contact beCo");
                        startActivity(intentEmail);
                        break;
                    case 1:
                        Intent intentCall = new Intent(Intent.ACTION_DIAL);
                        intentCall.setData(Uri.parse("tel:" + mContactLabels.get(childPosition)));
                        startActivity(intentCall);
                        break;
                }
            });

            return view;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mContactLabels.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mContactLabels.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return 1;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            TextView contact = (TextView) view.findViewById(R.id.text);
            contact.setText(title);
            Drawable iconLeft = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_contact_blue, R.color.beco_white, PorterDuff.Mode.DST_IN);
            contact.setCompoundDrawablesWithIntrinsicBounds(null,null,iconLeft,null);

            LinearLayout border = (LinearLayout) viewParent.findViewById(R.id.container_expandable_list);

            Drawable iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_down_black, R.color.beco_black, PorterDuff.Mode.DST_IN);

            if (isExpanded) {
                border.setBackgroundResource(R.drawable.border);
                iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_up_black, R.color.beco_black, PorterDuff.Mode.DST_IN);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_primary));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);

            } else {
                border.setBackgroundResource(0);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_label_color));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);
            }

            return view;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}

Body:
The problem is probably arising due to setting the listview height programmatically; when it does that, the views from the items are redrawed while holding the viewholders. In the case of position 3, the viewholder of a position 4 will have null reference to the textview, causing it to crash.

I suggest you to not use different layouts for items in a ListView (or GridView). I once had the same problem you had, causing the layouts to appear broken. Instead, use only one layout; if you need to hide some elements, like a TextView, you can do it programmatically:

holder.textview.setVisibility(View.INVISIBLE); //or View.GONE

There are some good tutorials related to ExpandableListViews too:

http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/

http://theopentutorials.com/tutorials/android/listview/android-expandable-list-view-example/


来源: stackexchange

问:
all the data is gone in the form when i put ng-model angularjs
I want to load data of a selected row in a form in order to update it. I successfully had the data loaded in the form, the but the problem is when I use ng model to save the data all the stuff have been put in the form fields disappear.

```<code><div class="panel-body pan" ng-if="loadedpr">
<form action="#">
    <div class="form-body pal">
        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    <label for="refprojet" class="control-label">
                        Référence Projet *</label>
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="ref_projet"/>
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="intitulefr" class="control-label">
                        Intitulé *</label>
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="intitule_fr" />
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="ctot" class="control-label"> Coût Total (TND) *</label>
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="cout_total" class="form-control" disabled ng-model="cout_total" />
                </div>
            </div>
        </div>

        <div class="form-group">
            <label for="description" class="control-label">
                Description</label><textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="description" class="form-control"></textarea>
        </div>
        <div class="form-actions text-center pal">
            <button type="submit" class="btn btn-primary" ng-click="upadateProjet()">Valider</button>
        </div>
    </div>
</form>
</code>```

this is the angularjs method:

```<code>$scope.updateProjet= function(){
    $scope.projet={'ref_projet':$scope.refprojet,'intitule_fr':$scope.intitule_fr,'description':$scope.description,cout_total':$scope.cout_total};
    $http.put("/editprojet", $scope.projet)
    .success(function(data,status,headers,config){

    });

}
</code>```

rest controller

```<code>@RequestMapping(value="/editprojet",method=RequestMethod.PUT)
public Projet editProjet(@RequestBody Projet p) {
    return projetMetier.editProjet(p);
}
</code>```

答:
$scope.updateProjet= function(projData){

    $http.put("/editprojet", projData)
    .success(function(data,status,headers,config){

    }).error(function(data){
    console.log(data)
    });

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel-body pan" ng-if="loadedpr">
<form action="#">
    <div class="form-body pal">
        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    <label for="refprojet" class="control-label">
                        Référence Projet *</label>
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="proj.ref_projet"/>
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="intitulefr" class="control-label">
                        Intitulé *</label>
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="proj.intitule_fr" />
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="ctot" class="control-label"> Coût Total (TND) *</label>
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="proj.cout_total" class="form-control" disabled ng-model="proj.cout_total" />
                </div>
            </div>
        </div>

        <div class="form-group">
            <label for="description" class="control-label">
                Description</label><textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="proj.description" class="form-control"></textarea>
        </div>
        <div class="form-actions text-center pal">
            <button type="button" class="btn btn-primary" ng-click="upadateProjet(proj)">Valider</button>
        </div>
    </div>
</form>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to load data of a selected row in a form in order to update it. I successfully had the data loaded in the form, the but the problem is when I use ng model to save the data all the stuff have been put in the form fields disappear.

<form action="#">

                        Référence Projet *
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="ref_projet"/>

                        Intitulé *
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="intitule_fr" />

                     Coût Total (TND) *
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="cout_total" class="form-control" disabled ng-model="cout_total" />

                Description<textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="description" class="form-control"></textarea>

            <button type="submit" class="btn btn-primary" ng-click="upadateProjet()">Valider</button>

</form>

this is the angularjs method:

$scope.updateProjet= function(){
    $scope.projet={'ref_projet':$scope.refprojet,'intitule_fr':$scope.intitule_fr,'description':$scope.description,cout_total':$scope.cout_total};
    $http.put("/editprojet", $scope.projet)
    .success(function(data,status,headers,config){

    });

}

rest controller

@RequestMapping(value="/editprojet",method=RequestMethod.PUT)
public Projet editProjet(@RequestBody Projet p) {
    return projetMetier.editProjet(p);
}

Body:
$scope.updateProjet= function(projData){

    $http.put("/editprojet", projData)
    .success(function(data,status,headers,config){

    }).error(function(data){
    console.log(data)
    });

}

<div class="panel-body pan" ng-if="loadedpr">
<form action="#">
    <div class="form-body pal">
        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    <label for="refprojet" class="control-label">
                        Référence Projet *</label>
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="proj.ref_projet"/>
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="intitulefr" class="control-label">
                        Intitulé *</label>
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="proj.intitule_fr" />
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="ctot" class="control-label"> Coût Total (TND) *</label>
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="proj.cout_total" class="form-control" disabled ng-model="proj.cout_total" />
                </div>
            </div>
        </div>

        <div class="form-group">
            <label for="description" class="control-label">
                Description</label><textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="proj.description" class="form-control"></textarea>
        </div>
        <div class="form-actions text-center pal">
            <button type="button" class="btn btn-primary" ng-click="upadateProjet(proj)">Valider</button>
        </div>
    </div>
</form>
</div>


问:
Unit testing a menu in ASP.NET MVC 2
I have done some reading on unit testing and want to start with my first test.  I am using ASP.NET MVC 2.

We determine the type of user by getting the staff number and checking it against the Roles table.  If the user exists in this table then the UserType property is set.

We have a menu for each type of user, and each of the menu items are different for each type of user.

How would a test look like for this displaying the menu items for each type of user?

答:
If you have written your application, according to some you'll now be working with "Legacy code" (based on the Michael Feather's book Working Effectively With Legacy Code - by "Legacy Code" Feathers means any system that isn't adequately covered by unit tests).

As @bAN mentions, you will have to do a lot of work to isolate the methods you will be calling by using factory methods that you can replace with "stubs" using interfaces or by using override. Without this, you will be doing integration testing (as you will also be testing the integration between different atoms of functionality). But, a 1-to-1 ratio of test methods to production methods will not give enough coverage in almost all cases.

Depending on your version of Visual Studio, the amount of testing tools will vary.  NUnit is a very popular testing framework: http://www.nunit.org/, if you aren't using the Visual Studio tools.

To get testing, you can:

Create a new project of type Test Project called YourProjectUnderTestName.Tests.Unit.

You will see that a Test Class has the attribute [TestClass] and test methods have the attribute [TestMethod].

You will also have to look at the Assert classes and their static methods http://msdn.microsoft.com/en-us/library/ms182530.aspx

You should follow the Arrange, Act, Assert pattern in your tests. Get everything you need to run the code you want to test in isolation, then run the code under test, then use Asserts to test against expected behaviour.

You will at some point also need to find out about [SetUp]/[TearDown] methods (in MSUnit) these have the attributes:

[ClassInitialize()],[TestInitialize()], and

[TestCleanup()],[ClassCleanup()]

The ClassInitialize runs before when any tests are started, TestInitialize runs before each test in the class, TestCleanup runs after each test in the class and ClassCleanup runs after all of the tests are finished.

As @bAN says have a look through the http://artofunittesting.com/ site and seriously consider getting the book. It's one of the ones I would grab if the office was on fire, along with Code Complete.

As @bAN and @Oliver Hanappi have mentioned TDD is a very good way to make sure you do "proper" unit testing and get good coverage.

Good luck!

ContentLicense: CC BY-SA 2.5

Title: Unit testing a menu in ASP.NET MVC 2


问:
JavaScript transfering one element to another (multiple times) by using event
I want to transfer multiple times after click on "przenieś" the whole li from one div class="listContainer two" to another, and back again (and again) using JavaScript. How should I prepare the JavaScript code for the most efficient way?

Item 1 z listy 1 Przenieś

Item 2 z listy 1 Przenieś

Item 1 z listy 2 Przenieś

Item 2 z listy 2 Przenieś

```

答:
One approach, taking advantage of ES6 and an experimental JavaScript feature (present in both Chrome and Firefox) closest(), is the following:

```<code>// 'e' is the Event Object, passed from the later use of
// EventTarget.addEventListener():
function moveBetween(e) {

  // we prevent the default action of clicking an <a>
  // Element:
  e.preventDefault();

  // cache a reference to the clicked element (the 'this'
  // is passed from the EventTarget.addEventListener()):
  let clicked = this,

    // here we use document.querySelectorAll() to retrieve a
    // NodeList of all elements matching the supplied CSS
    // selector, and Array.from() converts that Array-like
    // NodeList into an Array, to allow us to use Array
    // methods:
    lists = Array.from(document.querySelectorAll('ul')),

    // here we use Array.prototype.filter() to remove those
    // Array elements that do not match the passed argument:
    other = lists.filter(

      // this is an Arrow function syntax, and passes the
      // current Array element (the <ul>) of the Array of
      // elements to the assessment.
      // If the closest ancestor 'ul' is not equal to the
      // current <ul> we retain that <ul>, if the closest
      // <ul> is equal to (and therefore *is*) the current
      // <ul> then we discard that <ul> from the Array:
      list => clicked.closest('ul') !== list
    );

  // if the other Array exists (and is truthy) and it
  // has a length property other than zero (so is also
  // truthy):
  if (other && other.length) {

    // we retrieve the first element of that Array,
    // a <ul> element and use Node.appendChild() to
    // to append the closest ancestor <li> of the
    // clicked element to that <ul>:
    other[0].appendChild(clicked.closest('li'));
  }
}

let buttons = Array.from(document.querySelectorAll('.moveBtn'));

buttons.forEach(
  button => button.addEventListener('click', moveBetween)
);
</code>```

function moveBetween(e) {
  e.preventDefault();
  let clicked = this,
    lists = Array.from(document.querySelectorAll('ul')),
    other = lists.filter(
      list => clicked.closest('ul') !== list
    );

  if (other && other.length) {
    other[0].appendChild(clicked.closest('li'));
  }
}

let buttons = Array.from(document.querySelectorAll('.moveBtn'));

buttons.forEach(
  button => button.addEventListener('click', moveBetween)
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

li {
  line-height: 2em;
}

.moveBtn {
  color: #f90;
}</code>```

Item 1 z listy 1 Przenieś

Item 2 z listy 1 Przenieś

Item 1 z listy 2 Przenieś

Item 2 z listy 2 Przenieś

```

Body:
One approach, taking advantage of ES6 and an experimental JavaScript feature (present in both Chrome and Firefox) closest(), is the following:

// 'e' is the Event Object, passed from the later use of
// EventTarget.addEventListener():
function moveBetween(e) {

  // we prevent the default action of clicking an <a>
  // Element:
  e.preventDefault();

  // cache a reference to the clicked element (the 'this'
  // is passed from the EventTarget.addEventListener()):
  let clicked = this,

    // here we use document.querySelectorAll() to retrieve a
    // NodeList of all elements matching the supplied CSS
    // selector, and Array.from() converts that Array-like
    // NodeList into an Array, to allow us to use Array
    // methods:
    lists = Array.from(document.querySelectorAll('ul')),

    // here we use Array.prototype.filter() to remove those
    // Array elements that do not match the passed argument:
    other = lists.filter(

      // this is an Arrow function syntax, and passes the
      // current Array element (the <ul>) of the Array of
      // elements to the assessment.
      // If the closest ancestor 'ul' is not equal to the
      // current <ul> we retain that <ul>, if the closest
      // <ul> is equal to (and therefore *is*) the current
      // <ul> then we discard that <ul> from the Array:
      list => clicked.closest('ul') !== list
    );

  // if the other Array exists (and is truthy) and it
  // has a length property other than zero (so is also
  // truthy):
  if (other && other.length) {

    // we retrieve the first element of that Array,
    // a <ul> element and use Node.appendChild() to
    // to append the closest ancestor <li> of the
    // clicked element to that <ul>:
    other[0].appendChild(clicked.closest('li'));
  }
}

let buttons = Array.from(document.querySelectorAll('.moveBtn'));

buttons.forEach(
  button => button.addEventListener('click', moveBetween)
);

function moveBetween(e) {
  e.preventDefault();
  let clicked = this,
    lists = Array.from(document.querySelectorAll('ul')),
    other = lists.filter(
      list => clicked.closest('ul') !== list
    );

  if (other && other.length) {
    other[0].appendChild(clicked.closest('li'));
  }
}

let buttons = Array.from(document.querySelectorAll('.moveBtn'));

buttons.forEach(
  button => button.addEventListener('click', moveBetween)
);

* {
  box-sizing: border-box;
}

li {
  line-height: 2em;
}

.moveBtn {
  color: #f90;
}

<div class="listContainer two">
  <ul id="list1">
    <li>Item 1 z listy 1 <a class="moveBtn">Przenieś</a></li>
    <li>Item 2 z listy 1 <a class="moveBtn">Przenieś</a></li>
  </ul>
</div>

<div class="listContainer two">
  <ul id="list2">
    <li>Item 1 z listy 2 <a class="moveBtn">Przenieś</a></li>
    <li>Item 2 z listy 2 <a class="moveBtn">Przenieś</a></li>
  </ul>
</div>


问:
does android ndk accelerates hardware?
I am developing an android app that processes images. I tried android ndk before so i can code natively to speed up performance. But I discontinued using it because I can't fully understand the C language.

So I continue my app dev using Java code. I searched for easier and better solution to speed up the performance of my app without using native code and it was a success.

After sometime, i realized that the ndk wasn't remove from my project. I removed it and recompile my code so i can remove the cpp folder too. But when I test my app, it became very slowwwwww... I linked the ndk again and now the image processing is fast again.

My question is, how did that happen???

答:
For processing images, usually C/C++ gives better image output than Java in desktop.

While programming in Android also i saw C/C++ Android NDK code gives better image output and faster than Android Java code.

This may be because of C/C++ code directly complies to native code where else java compiles to byte code and from byte code complies to native code by JNI.

And in NDK, .so files are created by Application Binary Interface(ABI) by that application machine code is directly interacted with the system at run time.

Title: does android ndk accelerates hardware?


问:
Create aggregate root in the context of another aggregate root
i'm currently struggling with the creation of instances in the ddd context.
i have read and searched alot and sometimes thought that i have found the answer only to realize that it doesnt feel right while programming it.

This is my situation:

I have two aggregate roots Scenarioand Step. I made those AR
because they encapsulate related elements of the domain and each AR
should be in a consistent state.

Multiple Steps can exist in the
context of a Scenario. They can not exist on their own.

The "name/natural id" of each Step in the context of its Scenario has to be unique. Changes in Scenario do not automatically influence its Steps and
vice versa (e.g. Step doesnt care if Scenario changes some
descriptions or images).

Different Steps of a Scenario can be used, edited, etc. at the same time.

At the moment, each Step holds a reference to its Scenario by the corresponding natural identifier. The Scenario class doesnt know anything about its Steps, so it does not hold a collection with Step references.

How would i create a new Stepfor a given Scenario?

Should i load the Scenario and call something like
createNewStep(...) on it? That would not enforce the uniqueness
constraint (that is in fact a business constraint and not a
technical one), because Scenario doesnt know about its Steps. I would  probably have to go with some kind of a "disconnected domain model" then or pass a repsoitory or service to the method to perform the checks.

Should i use a domain service that enforces the constraint, queries the repository, and finally creates and returns the Step?

Should Scenario simply know about its Steps? I think i would like to avoid this one, since that would create a ugly-to-maintain bidirectional relationship.

One could imagine other use cases like a Step shall be classified by options that are provided by the specific Scenario. In this case and if there would be no constraints regarding the "collection" of Steps, i would probably go with the first "solution". Then again: if the classification is changed afterwards, the access to the scenario would be necessary to check for the allowed classifications. That brings me to a possible 4th solution:

Using some kind of "combination" of some possible solutions. Would it be a good idea to create the domain service (accessing everything needed) and use it as an argument of the method that needs it? The method would then call the service where needed and the "domain logic" stays in the entity/model.

Thank you in advance!

I'll just edit instead of copy paste answering ;)

Thank you all for your responses! :)

Pushing the steps back into the scenario would lead to some pretty big objects which i'm trying to avoid (the current running application really suffers from this). It seems that its pretty much alike the Scrum-Example of Vaughns "Effective Aggregate Design" where he is using DomainServices to get smaller aggregates (i really dont know why i'm so uncertain about using domain services). Looks like i'll have to use domainservices or split the aggregates up into "StepName" and "StepDetails" as suggested.

答:
For background, you should read what Greg Young has to say about set validation (via WaybackMachine).  In particular, you really need to evaluate, in the context of your solution, what is the business impact of having a failure?

Accept the failure and escalate is by far your easiest option.  In what follows, I assume that the business impact of the failure is large, so we need to prevent it from happening.

The "name/natural id" of each Step in the context of its Scenario has to be unique

That's a classic set validation concern.

The first thing to do is challenge the assumptions in your model

Is your model the book of record for "name"?  If your model isn't the authority, you have to be very cautious about introducing constraints.  Understanding the boundaries of your model's authority is really important.

Is there an invariant that couples the name of a step to any other part of its state?  Aggregate design discipline says that two pieces of state coupled by an invariant need to be in the same aggregate, but its silent about properties that don't participate in an invariant.

Is it reasonable to reject a name change while accepting other changes to a step?  This is really a variation of the previous -- can tasks be split into two different commands (one involving name, one not) that can succeed or fail independently?

In short, the invariant may be telling you that "step name", as a piece of state, belongs in the scenario aggregate rather than in the step aggregate.

If you think about the problem from the perspective of a relational model, we're looking at a tuple (scenarioId, name, stepId), and the constraint says that (scenarioId, name) form a unique key.  That's a hint that step name belongs to the scenario.  In code, that signature looks like a scenario data structure that includes a Map<ScenarioName, ScenarioId>.

That won't necessarily solve all of your problems of course, but it is a step toward aligning the model with your actual business.

When that doesn't work...

The "real" answer is to move the step entity back into the scenario aggregate.  One way to think about it is this -- all of the entities taken together form "the model" that we are keeping consistent.  The aggregates aren't part of the business, per se; they are artificial, independent subdivisions within the model -- we identify and isolate aggregates as a performance optimization; we can perform concurrent edits, and evaluate the validity of a command while loading a much smaller data set.

If the failures make the performance optimization too expensive, you take it out.  So you can see that we have an estimate, of sorts, for what it means that the business impact is "large"; it needs to be bigger than the savings we get from using aggregates on the happy path.

Another possibility is to shift where you enforce the invariant.  Relational databases are really really good at set validation.  So maybe the right answer is to split the enforcement concern: put the invariant into your schema as a constraint, and ignore that constraint in code.

This isn't ideal for a number of reasons -- you've effectively "hidden" the constraint, you've introduced a constraint on the kind of data store that you use for your aggregates, you've introduced a constraint that requires that you store your step aggregates in the same database as the scenario they belong to, and so on.  If you squint, you'll see that this is really just the "make the step entities part of the scenario" solution, but in disguise.

But keep in mind: part of the point of domain-driven-design is that we can push back on the business when the code is telling us that the business model itself is wrong.  Where's the cost benefit analysis?

Here's the thing about uniqueness constraints: the model enforces uniqueness, not correctness.  Imagine a data race, two different commands that each claim the same "name" for a different step in the scenario -- perhaps caused by a data entry error.  The model, presumably, can't tell which command is "right", so it's going to make some arbitrary guess (most likely, first command wins).  If the model guesses wrong, it has effectively blocked the client that provided correct data!

In cases where the model is the authority, uniqueness constraints can make sense -- the SeatMap aggregate can enforce the constraint that only one ticket can be assigned to a seat at any given time, because it is the authority for assignment.


问:
Using multiple arrays in Awk without duplication of code
I have working code

```<code>BEGIN { FS=";"; }   # field separator
{
    if (match($2, /[0-9]+/)) {           # matching `ID` value
        m=substr($2, RSTART, RLENGTH);
        a[m]++;                          # accumulating number of lines for each `ID`
        print > m"_count.txt";    # writing lines pertaining to certain `ID` into respective file
    }
}
END {
    for(i in a) {
        print "mv "i"_count.txt "i"_"a[i]".txt"  # renaming files with actual counts
    }
}
</code>```

Now i need to change it to do something like this.
So i have three arrays of IDs and each array means separate folders to save result.

```<code>BEGIN { FS=";"; }   # field separator
{
    array1=(125 258 698 874)
    array2=(956 887 4455 22)
    array3=(111 444 558 966 332)
    if ($1 == $2) {varR=$3} else {varR=$2}
    if (match(varR, /[0-9]+/)) {           # matching `ID` value
        if ( varR in array1 ) {
            FolderName = "folder1/"
            m1=substr(varR, RSTART, RLENGTH);
            a1[m1]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m1)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array2 ) {
            FolderName = "folder2/"
            m2=substr(varR, RSTART, RLENGTH);
            a2[m2]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m2)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array3 ) {
            FolderName = "folder3/"
            m3=substr(varR, RSTART, RLENGTH);
            a3[m3]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m3)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
    }
}
END {
    for(i in a1) {
        print "mv "i"_count.txt "i"_"a1[i]".txt"  # renaming files with actual counts
    }
    for(i in a2) {
        print "mv "i"_count.txt "i"_"a2[i]".txt"  # renaming files with actual counts
    }
    for(i in a3) {
        print "mv "i"_count.txt "i"_"a3[i]".txt"  # renaming files with actual counts
    }
}
</code>```

As i need to save matching ID to txt files and put in needed folder
What if i have 100 arrays? I need to duplicate code for each one?

答:
Do you need to use different arrays, or could you do something like this:</p>

```<code>a[1","1] = "abc";
a[1","2] = "xyz";
a[2","2] = "123";
folders[1] = "folder1";
folders[2] = "folder2";
var = "1";
for (f in folders) {
    if (var","f in a) {
        print a[var","f] " >> " folders[f] "/file_" var;
    }
}
</code>```

Body:
I have working code

BEGIN { FS=";"; }   # field separator
{
    if (match($2, /[0-9]+/)) {           # matching `ID` value
        m=substr($2, RSTART, RLENGTH);
        a[m]++;                          # accumulating number of lines for each `ID`
        print > m"_count.txt";    # writing lines pertaining to certain `ID` into respective file
    }
}
END {
    for(i in a) {
        print "mv "i"_count.txt "i"_"a[i]".txt"  # renaming files with actual counts
    }
}

Now i need to change it to do something like this.
So i have three arrays of IDs and each array means separate folders to save result.

BEGIN { FS=";"; }   # field separator
{
    array1=(125 258 698 874)
    array2=(956 887 4455 22)
    array3=(111 444 558 966 332)
    if ($1 == $2) {varR=$3} else {varR=$2}
    if (match(varR, /[0-9]+/)) {           # matching `ID` value
        if ( varR in array1 ) {
            FolderName = "folder1/"
            m1=substr(varR, RSTART, RLENGTH);
            a1[m1]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m1)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array2 ) {
            FolderName = "folder2/"
            m2=substr(varR, RSTART, RLENGTH);
            a2[m2]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m2)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array3 ) {
            FolderName = "folder3/"
            m3=substr(varR, RSTART, RLENGTH);
            a3[m3]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m3)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
    }
}
END {
    for(i in a1) {
        print "mv "i"_count.txt "i"_"a1[i]".txt"  # renaming files with actual counts
    }
    for(i in a2) {
        print "mv "i"_count.txt "i"_"a2[i]".txt"  # renaming files with actual counts
    }
    for(i in a3) {
        print "mv "i"_count.txt "i"_"a3[i]".txt"  # renaming files with actual counts
    }
}

As i need to save matching ID to txt files and put in needed folder
What if i have 100 arrays? I need to duplicate code for each one?

Body:
Do you need to use different arrays, or could you do something like this:

a[1","1] = "abc";
a[1","2] = "xyz";
a[2","2] = "123";
folders[1] = "folder1";
folders[2] = "folder2";
var = "1";
for (f in folders) {
    if (var","f in a) {
        print a[var","f] " >> " folders[f] "/file_" var;
    }
}


问:
Delete N oldest entries in table
How to delete N oldest entries. I'm limited Sybase. I need to write a stored procedure which would accept a number X and then leave only X newest entries in the table.

For example:
Say ID is auto incremented. The smaller it is, the older this entry is.

```<code>ID  Text
=========
1   ASD
2   DSA
3   HJK
4   OIU
</code>```

I need a procedure which would be executed like this.

```<code>execute CleanUp 2
</code>```

and the result will be

```<code>ID  Text
=========
3   HJK
4   OIU
</code>```

答:
I know this is an old question but this can be done without constructing the statement as the top answer say, using a CTE : </p>

```<code>WITH MyCTE AS
(
    SELECT Field1, Field2, ROW_NUMBER() OVER (ORDER BY Field1 ASC) AS RowNum
    FROM MyTable
    WHERE Field2 = @WhatIWant
)
DELETE FROM MyCTE WHERE RowNum <= @NbRowsToDelete;
</code>```

Title: Delete N oldest entries in table

Body:
How to delete N oldest entries. I'm limited Sybase. I need to write a stored procedure which would accept a number X and then leave only X newest entries in the table.

For example:
Say ID is auto incremented. The smaller it is, the older this entry is.

ID  Text
=========
1   ASD
2   DSA
3   HJK
4   OIU

I need a procedure which would be executed like this.

execute CleanUp 2

and the result will be

ID  Text
=========
3   HJK
4   OIU

Body:
I know this is an old question but this can be done without constructing the statement as the top answer say, using a CTE :

WITH MyCTE AS
(
    SELECT Field1, Field2, ROW_NUMBER() OVER (ORDER BY Field1 ASC) AS RowNum
    FROM MyTable
    WHERE Field2 = @WhatIWant
)
DELETE FROM MyCTE WHERE RowNum <= @NbRowsToDelete;


问:
wpf - TextBlock text not wrapping
I have a simple wpf window that has a TextBlock element with the following xaml code:

```<code><TextBlock Grid.Row="3" Grid.Column="2" MaxWidth="370"
x:Name="ResultTxt" Text="{Binding Text, Mode=OneWay}" TextWrapping="Wrap"></TextBlock>
</code>```

When a new text is received from a server, I append the text to the TextBlock content. Here is the part of code that does that

```<code>Text = Text + e.Text; //e is an EventArgs
RaisePropertyChanged("Text");
</code>```

When the text exceeds the current window limit, it doesn't wrap to a newline. Instead it just continues to the horizontal, although I have set the TextWrap property of the TextBlock to Wrap.

According to the suggestions in the answers to this question, the TextBlock should be inside a Grid container. But the TextBlock is in a Grid container and still not wrapping.

How can I make the TextBlock to wrap its contents into newline when it exceeds its window size?

Edit: Here is xaml code for the whole Grid container:

```<code><Grid TextBlock.FontSize="16" DataContext="{Binding Main, Source={StaticResource Locator}}" HorizontalAlignment="Left" Width="760">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Capture Device" Margin="20,10,10,0"></TextBlock>
        <ComboBox ItemsSource="{Binding Path=CaptureDevices, Mode=OneWay}" DisplayMemberPath="ProductName" SelectedIndex="0" Margin="19,10,10,0" VerticalAlignment="Top" MinHeight="22" Grid.Row="0" Grid.Column="1" Name="DeviceCombo" SelectedItem="{Binding SelectedDevice, Mode=TwoWay}" IsEnabled="{Binding CanSelect}"/>
        <Slider Margin="19,10,10,0" Orientation="Horizontal" Value="{Binding MicrophoneLevel, Mode=TwoWay}" Maximum="100" Grid.Row="0" Grid.Column="2" Grid.ColumnSpan="2" IsEnabled="false" MaxWidth="150"/>
        <Button x:Name="StartBtn" Content="Start" Grid.Column="0" Grid.Row="1" Margin="30,10,5,25" Width="60" Command="{Binding StartRecodrding}" IsEnabled="{Binding CanStart}"/>
        <Button x:Name="StopBtn" Grid.Row="1" Content="Stop" Grid.Column="2" Margin="0,10,15,25" Width="60" Command="{Binding StopRecording}" IsEnabled="{Binding CanStop}"/>
        <ProgressBar x:Name="RecordLevel" Grid.Row="1" Grid.Column="3"  Margin="30,10,15,25" Minimum="0" Maximum="100" MinWidth="170" Value="{Binding CurrentLevel, Mode=OneWay}"></ProgressBar>
        <TextBlock x:Name="Status" Grid.Row="2" Grid.Column="2" Margin="15,15,10,10" Text="{Binding StatusText}"></TextBlock>
        <TextBlock Grid.Row="3" Grid.Column="2" MaxWidth="370" x:Name="ResultTxt" Text="{Binding Text, Mode=OneWay}" TextWrapping="Wrap"></TextBlock>
    </Grid>
</code>```

答:
The Width of the second column should not be set to Auto. Try to set it to *:

```<code><Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
</code>```

You should also avoid setting the Grid's Width to a fixed value. Try MaxWidth instead:

```<code><Grid TextBlock.FontSize="16" DataContext="{Binding Main, Source={StaticResource Locator}}" HorizontalAlignment="Left" MaxWidth="760">
</code>```

Title: wpf - TextBlock text not wrapping

Body:
I have a simple wpf window that has a TextBlock element with the following xaml code:

<TextBlock Grid.Row="3" Grid.Column="2" MaxWidth="370"
x:Name="ResultTxt" Text="{Binding Text, Mode=OneWay}" TextWrapping="Wrap"></TextBlock>

When a new text is received from a server, I append the text to the TextBlock content. Here is the part of code that does that

Text = Text + e.Text; //e is an EventArgs
RaisePropertyChanged("Text");

When the text exceeds the current window limit, it doesn't wrap to a newline. Instead it just continues to the horizontal, although I have set the TextWrap property of the TextBlock to Wrap.

According to the suggestions in the answers to this question, the TextBlock should be inside a Grid container. But the TextBlock is in a Grid container and still not wrapping.

How can I make the TextBlock to wrap its contents into newline when it exceeds its window size?

Edit: Here is xaml code for the whole Grid container:

<Grid TextBlock.FontSize="16" DataContext="{Binding Main, Source={StaticResource Locator}}" HorizontalAlignment="Left" Width="760">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Capture Device" Margin="20,10,10,0"></TextBlock>
        <ComboBox ItemsSource="{Binding Path=CaptureDevices, Mode=OneWay}" DisplayMemberPath="ProductName" SelectedIndex="0" Margin="19,10,10,0" VerticalAlignment="Top" MinHeight="22" Grid.Row="0" Grid.Column="1" Name="DeviceCombo" SelectedItem="{Binding SelectedDevice, Mode=TwoWay}" IsEnabled="{Binding CanSelect}"/>
        <Slider Margin="19,10,10,0" Orientation="Horizontal" Value="{Binding MicrophoneLevel, Mode=TwoWay}" Maximum="100" Grid.Row="0" Grid.Column="2" Grid.ColumnSpan="2" IsEnabled="false" MaxWidth="150"/>
        <Button x:Name="StartBtn" Content="Start" Grid.Column="0" Grid.Row="1" Margin="30,10,5,25" Width="60" Command="{Binding StartRecodrding}" IsEnabled="{Binding CanStart}"/>
        <Button x:Name="StopBtn" Grid.Row="1" Content="Stop" Grid.Column="2" Margin="0,10,15,25" Width="60" Command="{Binding StopRecording}" IsEnabled="{Binding CanStop}"/>
        <ProgressBar x:Name="RecordLevel" Grid.Row="1" Grid.Column="3"  Margin="30,10,15,25" Minimum="0" Maximum="100" MinWidth="170" Value="{Binding CurrentLevel, Mode=OneWay}"></ProgressBar>
        <TextBlock x:Name="Status" Grid.Row="2" Grid.Column="2" Margin="15,15,10,10" Text="{Binding StatusText}"></TextBlock>
        <TextBlock Grid.Row="3" Grid.Column="2" MaxWidth="370" x:Name="ResultTxt" Text="{Binding Text, Mode=OneWay}" TextWrapping="Wrap"></TextBlock>
    </Grid>

Body:
The Width of the second column should not be set to Auto. Try to set it to *:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>

You should also avoid setting the Grid's Width to a fixed value. Try MaxWidth instead:

<Grid TextBlock.FontSize="16" DataContext="{Binding Main, Source={StaticResource Locator}}" HorizontalAlignment="Left" MaxWidth="760">


问:
C# LocalDB connection
I have been trying to make my c# database application run everywhere but when using the following connection string

```<code> <add name="DBCS"
   connectionString="Data Source=(LocalDB)\v13;AttachDbFilename=|DataDirectory|\ServiceCardRecorderDatabase.mdf;Integrated Security=True;database=ServiceCardRecorderDatabase"
   providerName="System.Data.SqlClient" />
</code>```

and when I try to insert data to the table I get an exception saying
 System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.

thrown from Visual Studio:

答:
Thanks all for your effort, finally I found the problem solved by using this connection string below.

<add name="DBCS" connectionString="Data Source=(LocalDB)\mssqllocaldb;AttachDbFilename=|DataDirectory|\App_Data\ServiceCardRecorderDatabase.mdf;Integrated Security=True"
       providerName="System.Data.SqlClient" />```

I just added the folder name in which I put the  mdf  file in the project folder after |DataDirectory| and its runs as expected.

Title: C# LocalDB connection

Body:
I have been trying to make my c# database application run everywhere but when using the following connection string

 <add name="DBCS"
   connectionString="Data Source=(LocalDB)\v13;AttachDbFilename=|DataDirectory|\ServiceCardRecorderDatabase.mdf;Integrated Security=True;database=ServiceCardRecorderDatabase"
   providerName="System.Data.SqlClient" />

and when I try to insert data to the table I get an exception saying
 System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.

thrown from Visual Studio:

Body:
Thanks all for your effort, finally I found the problem solved by using this connection string below.

<add name="DBCS" connectionString="Data Source=(LocalDB)\mssqllocaldb;AttachDbFilename=|DataDirectory|\App_Data\ServiceCardRecorderDatabase.mdf;Integrated Security=True"
       providerName="System.Data.SqlClient" />

I just added the folder name in which I put the  mdf  file in the project folder after |DataDirectory| and its runs as expected.


问:
automatically remove indentation, unneeded empty space from html (minify)
I have an asp.net-mvc application, and when I look at the page's source I see the html is indented, has lots of white space,

I think if I will remove all these spaces, my page will become smaller in KB

anybody knows how to remove them automatically ?

答:
Taken from http://madskristensen.net/post/A-whitespace-removal-HTTP-module-for-ASPNET-20.aspx.</p>

```<code>[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
internal class WhiteSpaceFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
{
        filterContext.HttpContext.Response.Filter = new WhiteSpaceStream(filterContext.HttpContext.Response.Filter);
    }
}

internal class WhiteSpaceStream : Stream
{
    private Stream m_sink;
    private static Regex m_regex = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}");
    //private static Regex m_regex = new Regex(@"^\s+", RegexOptions.Multiline | RegexOptions.Compiled);

    public WhiteSpaceStream(Stream sink)
    {
        m_sink = sink;
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override bool CanSeek
    {
        get { return true; }
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override void Flush()
    {
        m_sink.Flush();
    }

    public override long Length
    {
        get { return 0; }
    }

    private long _position;
    public override long Position
    {
        get { return _position; }
        set { _position = value; }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        return m_sink.Read(buffer, offset, count);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return m_sink.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
        m_sink.SetLength(value);
    }

    public override void Close()
    {
        m_sink.Close();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        byte[] data = new byte[count];
        Buffer.BlockCopy(buffer, offset, data, 0, count);
        string text = Encoding.Default.GetString(buffer);

        text = m_regex.Replace(text, string.Empty);

        byte[] outdata = System.Text.Encoding.Default.GetBytes(text);
        m_sink.Write(outdata, 0, outdata.GetLength(0));
    }
</code>```

Body:
Taken from http://madskristensen.net/post/A-whitespace-removal-HTTP-module-for-ASPNET-20.aspx.

[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
internal class WhiteSpaceFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
{
        filterContext.HttpContext.Response.Filter = new WhiteSpaceStream(filterContext.HttpContext.Response.Filter);
    }
}

internal class WhiteSpaceStream : Stream
{
    private Stream m_sink;
    private static Regex m_regex = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}");
    //private static Regex m_regex = new Regex(@"^\s+", RegexOptions.Multiline | RegexOptions.Compiled);

    public WhiteSpaceStream(Stream sink)
    {
        m_sink = sink;
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override bool CanSeek
    {
        get { return true; }
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override void Flush()
    {
        m_sink.Flush();
    }

    public override long Length
    {
        get { return 0; }
    }

    private long _position;
    public override long Position
    {
        get { return _position; }
        set { _position = value; }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        return m_sink.Read(buffer, offset, count);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return m_sink.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
        m_sink.SetLength(value);
    }

    public override void Close()
    {
        m_sink.Close();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        byte[] data = new byte[count];
        Buffer.BlockCopy(buffer, offset, data, 0, count);
        string text = Encoding.Default.GetString(buffer);

        text = m_regex.Replace(text, string.Empty);

        byte[] outdata = System.Text.Encoding.Default.GetBytes(text);
        m_sink.Write(outdata, 0, outdata.GetLength(0));
    }


问:
My quick sort implementation is not working for 10000 sequence numbers
I have a quick sort implementation, this sort implementation is working fine with small arrays and 10000 random numbers but it is throwing a stackoverflow error when the input was 10000 sequence numbers (from 1 to 10000)

```<code>public class QuickSort<T extends Comparable> extends Sort<T>{

public void sort(Comparable[] input) {
    sort(input, 0, input.length-1);
}

private void sort(Comparable[] a, int lo, int hi) {
    if (hi <= lo) return;

    int j = partition(a, lo, hi);
    sort(a, lo, j-1);
    sort(a, j+1, hi);
}

private int partition(Comparable[] a, int lo, int hi) {
    int i=lo;
    int j=hi + 1;
    Comparable v = a[lo];

    while(true) {
        while (less(a[++i], v)) {
            if (i == hi) break;
        }

        while (less(v, a[--j])) {
            if (j == lo) break;
        }

        if(i >= j) break;

        exch(a, i, j);
    }
    exch(a, lo, j);
    return j;
}

public static boolean less (Comparable a, Comparable b) {
    return a.compareTo(b) < 0;
}

public static void exch(Comparable[] array, int i, int j) {
    Comparable temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static void main(String...args) {
    Integer[] array = new Integer[] {10,2,9,11,1,19,9,4,6,2,1,4,5,6};
    new QuickSort<>().sort(array);

    for (int temp : array) {
        System.out.print(temp + " ");
    }
}
}
</code>```

It is working for 10000 random numbers and for other input. But throws a stackoverflow error when executed with 10000 sequence numbers (from 1 to 10000)

答:
Simple Quicksort implementation has O(n^2) complexity and O(n) additional memory requirements in the worst-case scenario. You've got this worst-case on ordered sequence because of bad pivot element selection method.

Wikipedia:

In the very early versions of quicksort, the leftmost element of the
  partition would often be chosen as the pivot element. Unfortunately,
  this causes worst-case behavior on already sorted arrays, which is a
  rather common use-case. The problem was easily solved by choosing
  either a random index for the pivot, choosing the middle index of the
  partition or (especially for longer partitions) choosing the median of
  the first, middle and last element of the partition for the pivot (as
  recommended by Sedgewick).

Simple way to fix this issue is to take middle element as a pivot. Replace

```<code>Comparable v = a[lo];
</code>```

with

```<code>Comparable v = a[lo+(hi-lo)/2];
</code>```

It is not that hard to create worst-case test for this pivot selection method, but you'll need to do it intentionally on large input cases. If you want sorting algorithm that is similar to Quicksort and without O(n^2) worst-cases, you should look at Introsort algorithm.

Body:
I have a quick sort implementation, this sort implementation is working fine with small arrays and 10000 random numbers but it is throwing a stackoverflow error when the input was 10000 sequence numbers (from 1 to 10000)

public class QuickSort<T extends Comparable> extends Sort<T>{

public void sort(Comparable[] input) {
    sort(input, 0, input.length-1);
}

private void sort(Comparable[] a, int lo, int hi) {
    if (hi <= lo) return;

    int j = partition(a, lo, hi);
    sort(a, lo, j-1);
    sort(a, j+1, hi);
}

private int partition(Comparable[] a, int lo, int hi) {
    int i=lo;
    int j=hi + 1;
    Comparable v = a[lo];

    while(true) {
        while (less(a[++i], v)) {
            if (i == hi) break;
        }

        while (less(v, a[--j])) {
            if (j == lo) break;
        }

        if(i >= j) break;

        exch(a, i, j);
    }
    exch(a, lo, j);
    return j;
}

public static boolean less (Comparable a, Comparable b) {
    return a.compareTo(b) < 0;
}

public static void exch(Comparable[] array, int i, int j) {
    Comparable temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static void main(String...args) {
    Integer[] array = new Integer[] {10,2,9,11,1,19,9,4,6,2,1,4,5,6};
    new QuickSort<>().sort(array);

    for (int temp : array) {
        System.out.print(temp + " ");
    }
}
}

It is working for 10000 random numbers and for other input. But throws a stackoverflow error when executed with 10000 sequence numbers (from 1 to 10000)

Body:
Simple Quicksort implementation has O(n^2) complexity and O(n) additional memory requirements in the worst-case scenario. You've got this worst-case on ordered sequence because of bad pivot element selection method.

Wikipedia:

In the very early versions of quicksort, the leftmost element of the
  partition would often be chosen as the pivot element. Unfortunately,
  this causes worst-case behavior on already sorted arrays, which is a
  rather common use-case. The problem was easily solved by choosing
  either a random index for the pivot, choosing the middle index of the
  partition or (especially for longer partitions) choosing the median of
  the first, middle and last element of the partition for the pivot (as
  recommended by Sedgewick).

Simple way to fix this issue is to take middle element as a pivot. Replace

Comparable v = a[lo];

with

Comparable v = a[lo+(hi-lo)/2];

It is not that hard to create worst-case test for this pivot selection method, but you'll need to do it intentionally on large input cases. If you want sorting algorithm that is similar to Quicksort and without O(n^2) worst-cases, you should look at Introsort algorithm.


问:
How to insert and update two form same data into single table but different rows using php
I have to insert and update two form data on single submit click to mysql table. Please help me how can I do this. Just provide me a hint.

Thank you...

答:
You can do field names as arrays

```<code><form name='form1'>
   <input type='text' name='name[]' />
</form>
<form name='form2'>
   <input type='text' name='name[]' />
</form>

<?php

$connection stuff here
$name = $_POST['name'];
$query = "INSERT INTO X (val1) VALUES (?)";
for($i = 0; $i < 2 (# of inserts); $i++){

$stmt = $conn->prepare($query);
$stmt->bind_param("ss",$name[$i]);
$stmt->execute();
}
?>
</code>```

Note that $_POST['name']; is an array if you send more than one of the same named field in using [].  print_r($_POST['name']); will show you the field values

Body:
You can do field names as arrays

<form name='form1'>
   <input type='text' name='name[]' />
</form>
<form name='form2'>
   <input type='text' name='name[]' />
</form>

<?php

$connection stuff here
$name = $_POST['name'];
$query = "INSERT INTO X (val1) VALUES (?)";
for($i = 0; $i < 2 (# of inserts); $i++){

$stmt = $conn->prepare($query);
$stmt->bind_param("ss",$name[$i]);
$stmt->execute();
}
?>

Note that $_POST['name']; is an array if you send more than one of the same named field in using [].  print_r($_POST['name']); will show you the field values


问:
My syntax error when i want to make if conditional sql
why this is happen to me? I dont know why my syntax get wrong when i want to make if conditional in my sql

```<code>IF quantity <= 0
    UPDATE tbl_books
    SET status = 'Not Available'
ELSE
    UPDATE tbl_books
    SET quantity = quantity -1
    WHERE isbn = 'tes1'
</code>```

I got an error like this

```<code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF 'quantity' <= 0 UPDATE tbl_books SET status = 'Not Available' ELSE UPDA' at line 1
</code>```

答:
Presumably, quantity is not a variable.  Hence, it is outside the scope of the if statement.

You can do this in a single update statement:

```<code>UPDATE tbl_books
    SET status = (CASE WHEN quantity <= 0 THEN 'Not Available' ELSE status END),
        quantity = (CASE WHEN quantity > 0 THEN quantity - 1 ELSE quantity END)
    WHERE isbn = 'tes1'
</code>```

Body:
why this is happen to me? I dont know why my syntax get wrong when i want to make if conditional in my sql

IF quantity <= 0
    UPDATE tbl_books
    SET status = 'Not Available'
ELSE
    UPDATE tbl_books
    SET quantity = quantity -1
    WHERE isbn = 'tes1'

I got an error like this

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF 'quantity' <= 0 UPDATE tbl_books SET status = 'Not Available' ELSE UPDA' at line 1

Body:
Presumably, quantity is not a variable.  Hence, it is outside the scope of the if statement.

You can do this in a single update statement:

UPDATE tbl_books
    SET status = (CASE WHEN quantity <= 0 THEN 'Not Available' ELSE status END),
        quantity = (CASE WHEN quantity > 0 THEN quantity - 1 ELSE quantity END)
    WHERE isbn = 'tes1'


问:
Egit is installed (came with Juno), but does not show at all
I want to use GIT in eclipse, and preferably EGit, for it's support from the eclipse community itself. However, despite eclipse claiming the required plugins are installed, it does not appear in the perspectives, import and settings menu's.

I am using Eclipse Juno for Java EE, and have confirmed the following installs:

When I update software, there are no more updates available. When I go to the repository for Egit, or JGit for that matter, eclipse tells me the plugins are already installed.

Window > Preferences > Team contains no Git item, only CVS and SVN.
Import project contains no Git option.
Perspective window contains no Git repo option.

答:
I had the same problem with Eclipse Mars 2.
Fixed that by installing the version 4.0 of EGit from here: http://wiki.eclipse.org/EGit/FAQ#Where_can_I_find_older_releases_of_EGit.3F</p>


问:
how to zoom image
hai my images are gallery all image display in same view but i expect the selected image only zoom for my gallery that type how to create any one help how to create give me your idea.....now i am post my screenshot.....help me....

答:
Bala,
 Refer this url, for zomming an image</p>

Title: how to zoom image


问:
How to kill Linux properly C#
I need an app to quickly kill all programs launched, so far I've tried this and none of it kills any of these processes:

```<code>    static string[] helpers = new string[] { "/home/user1/server/server.exe", "/home/user1/server/MarginGenerator.exe", "/home/user1/server/nextday/NextDayTicketSystem.exe" };
    static string[] helpers_apps = new string[] { "server", "MarginGenerator", "NextDayTicketSystem" };

    static void Main(string[] args)
    {
        foreach(string s in helpers)
        {
            foreach (var process in Process.GetProcessesByName(s))
            {
                process.Kill();
                Console.WriteLine("Killing: " + s);
            }
        }
        foreach (string s in helpers_apps)
        {
            foreach (var process in Process.GetProcessesByName(s))
            {
                process.Kill();
                Console.WriteLine("Killing: " + s);
            }
        }
        foreach (string s in helpers_apps)
        {
            foreach (var process in Process.GetProcessesByName(s))
            {
                Process[] processlist = Process.GetProcesses();

                foreach (Process theprocess in processlist)
                {

                    if (theprocess.ProcessName.StartsWith(s))
                        theprocess.Kill();
                }
            }
        }
        foreach (string s in helpers_apps)
        {
            Process.GetProcesses().Where(x => x.ProcessName.ToLower()
                                     .StartsWith(s))
                                     .ToList()
                                     .ForEach(x => x.Kill());

                Console.WriteLine("Killing: " + s);
        }
    }
</code>```

I launch this app using command:
sudo /home/user1/server/AppsKiller.exe

答: This answer (Get process executed by MONO on GNU/Linux) suggests that if the processes you are trying to list are Mono processes, then their process name will be 'Mono' and you'll need to look at the command line to see what is really going on.</p>

Title: How to kill Linux properly C#

Body:
I need an app to quickly kill all programs launched, so far I've tried this and none of it kills any of these processes:

    static string[] helpers = new string[] { "/home/user1/server/server.exe", "/home/user1/server/MarginGenerator.exe", "/home/user1/server/nextday/NextDayTicketSystem.exe" };
    static string[] helpers_apps = new string[] { "server", "MarginGenerator", "NextDayTicketSystem" };

    static void Main(string[] args)
    {
        foreach(string s in helpers)
        {
            foreach (var process in Process.GetProcessesByName(s))
            {
                process.Kill();
                Console.WriteLine("Killing: " + s);
            }
        }
        foreach (string s in helpers_apps)
        {
            foreach (var process in Process.GetProcessesByName(s))
            {
                process.Kill();
                Console.WriteLine("Killing: " + s);
            }
        }
        foreach (string s in helpers_apps)
        {
            foreach (var process in Process.GetProcessesByName(s))
            {
                Process[] processlist = Process.GetProcesses();

                foreach (Process theprocess in processlist)
                {

                    if (theprocess.ProcessName.StartsWith(s))
                        theprocess.Kill();
                }
            }
        }
        foreach (string s in helpers_apps)
        {
            Process.GetProcesses().Where(x => x.ProcessName.ToLower()
                                     .StartsWith(s))
                                     .ToList()
                                     .ForEach(x => x.Kill());

                Console.WriteLine("Killing: " + s);
        }
    }

I launch this app using command:
sudo /home/user1/server/AppsKiller.exe


问:
Bootstrap tooltips and popovers: To Destroy, or NOT To Destroy?
if I create tooltips and popovers via BS' tooltip() and popover() methods, is there a need to do any explicit destroying of said creations if the DOM changes and the affected elements are no longer present? Am I creating JS dust bunnies by NOT explicitly destroying?</p>

答:
Hello,

No need to destroy, when you close the popover or the tooltip automatically it is excluded from the DOM.

Here is an tooltip example:

image description here

In this example I use jquery ui tooltip.

I hope I have helped!


问:
CodeIgniter URL Query String Manipulation
I have a E-Commerce Website build using CodeIgniter 2.3.

Please suggest how can I manipulate the URLs in the given sequence:-

Say a Person Searches for "Mobile Phones".
URL must be xyz.com/search/mobile-phone, which displays all the Mobile Phones from our Database.
I am already aware of the Search controller and use Routing to exclude the function name from the URL

Next the Person uses filtering by name of Mobile Phone Companies. Suppose he chooses "Apple". The URL must become xyz.com/search/mobile-phones/apple

Next the Person again filters by Condition ie "New" or "Refurbished". The URL must become xyz.com/search/mobile-phones/apples/new

The URLs need to be Functional URLs so that, if I pass the URL xyz.com/search/mobile-phones/apples/new to someone externally, he/she should be able to see the same result set as the person who came after Search & Filtering.

I am non-technical so may be I couldnt explain my problem very technically, but be assured, my Tech Person would be reading your suggestions.

Further Details

We are already using URI Segmentation, Routing & Post Method. But that way we are facing issues wrt Point #4 mentioned above

答:
For ex:
   Your URL is :  xyz.com/search/mobile-phones/apple/condition/new

```<code> $segment_array=$this->uri->segment_array();
 $mobile_brand=array_search('mobile-phones',$segment_array);
        if($mobile_brand !==FALSE && $this->uri->segment($mobile_brand+1)!='')
        {
            $mobile_brand = $this->uri->segment($mobile_brand+1); //apple
        }

 $condition=array_search('condition',$segment_array);
        if($condition !==FALSE && $this->uri->segment($condition+1)!='')
        {
            $condition = $this->uri->segment($condition+1); //new
        }
</code>```

You can follow up your coding by checking $mobile-brand & $condition to restrict the result.
This way it will not conflict other parameters, passing parameters with key and value approach.

Try and let me know you output.

Body:
For ex:
   Your URL is :  xyz.com/search/mobile-phones/apple/condition/new

 $segment_array=$this->uri->segment_array();
 $mobile_brand=array_search('mobile-phones',$segment_array);
        if($mobile_brand !==FALSE && $this->uri->segment($mobile_brand+1)!='')
        {
            $mobile_brand = $this->uri->segment($mobile_brand+1); //apple
        }

 $condition=array_search('condition',$segment_array);
        if($condition !==FALSE && $this->uri->segment($condition+1)!='')
        {
            $condition = $this->uri->segment($condition+1); //new
        }

You can follow up your coding by checking $mobile-brand & $condition to restrict the result.
This way it will not conflict other parameters, passing parameters with key and value approach.

Try and let me know you output.


问:
Do I need to worry about concurrency issues in my Flex/AIR code?
I have a situation where I'm starting a number of objects that, when they are ready to handle some input data, call a handler.

That handler gets a dataset from an ArrayCollection of pending requests, assigns it to the object, and removes the dataset from the ArrayCollection.

(I can't pop from the ArrayCollection because I need to search through it to find an appropriate dataset - it isn't always the one on top.)

Is it possible that two objects could call my handler in such a way that (1) the first is assigned a dataset, (2) the second is assigned the same dataset before the instance of the handler servicing the first has deleted it and I guess (3) the second instance of the handler errors on trying to delete the dataset from the ArrayCollection.

I'm not familiar enough with the Flash Player runtime to know if this failure scenario is even possible, or if I should take the extra time to put some sort of locking in place to prevent it.

Edit: The answers so far give glowing reviews for Flex, but I'm not sure they answer the question. To be clear, I'm not trying to decide whether or not to use Flex.

If I have a method that:

Gets a piece of data from somewhere in an ArrayCollection

Does something with that data

Removes that data from the ArrayCollection

Is it possible that another invocation of that same method could do #1 after the first invocation does #1 but before it does #3?

le dorfier, you said that Flex/AS "just works" - can you clarify that it will "just work" in this case?

答:
The answer to your question, as you've described it, is no.  While knowing about event registration, event dispatching, priorities, asynchronousness, etc., is all valuable, the fact remains you're doing the work of modifying the ArrayCollection within the scope of a single function on the main thread, which will be followed by the second invocation of that function, also on the main thread -- so you've got nothing to worry about in terms of concurrency:  while it's true you might not know which object gets there first (for lots of reasons), you can be certain the second one will get the product of the work performed by the first one.

So no, you're good to go.  Rock on!

OwnerDisplayName: Matt Miller

LastEditorDisplayName: Matt Miller

OwnerDisplayName: Christian Nunciato

LastEditorDisplayName: Christian Nunciato


问:
Import CSV or JSON file to DynamoDB using PHP
I have a table on DynamoDB.

I want to upload a CSV (or JSON, whatever file you say is better) to my table at DynamoDB using my PHP script.

I have six attributes in my DynamoDB table:

```<code>|name(S)|price(N)|category(S)|summary(S)|sale(BOOL)|salePrice(N)|
</code>```

And a CSV file with 5 items, each item with the above 6 attributes. If needed I can convert the file to a JSON file.

How can I upload the CSV file (or JSON) to my DynamoDB table using PHP?

答:
Please note that there is no straight forward way (i.e. like mongoimport tool of MongoDB) to upload the CSV or JSON files into DynamoDB directly.

Option 1:-

You can use Data Pipeline to import data into DynamoDB table

Option 2:-

Write code to read data from file and can use batch write item API to load the data into DynamoDB table

Body:
I have a table on DynamoDB.

I want to upload a CSV (or JSON, whatever file you say is better) to my table at DynamoDB using my PHP script.

I have six attributes in my DynamoDB table:

|name(S)|price(N)|category(S)|summary(S)|sale(BOOL)|salePrice(N)|

And a CSV file with 5 items, each item with the above 6 attributes. If needed I can convert the file to a JSON file.

How can I upload the CSV file (or JSON) to my DynamoDB table using PHP?