问:
How to update imageview from the parent recyclerview after click on nested recyclerview's imageview
Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.

Parent Recyclerview Adapter:

```<code>public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {

private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
    this.dataList = dataList;
    this.mContext = context;
}

@Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
    ItemRowHolder mh = new ItemRowHolder(v);
    return mh;
}

@Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {

    final String itemTitle = dataList.get(i).getTitle();
    final String itemDescription = dataList.get(i).getDescription();

    ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();

    itemRowHolder.itemTitle.setText(Html.fromHtml("<b>" + itemTitle + " </b> " + itemDescription));

    SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);

    itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
    itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
    itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);

}

@Override
public int getItemCount() {
    return (null != dataList ? dataList.size() : 0);
}

public class ItemRowHolder extends RecyclerView.ViewHolder {

    protected TextView itemTitle,  expandImage;
    protected ImageView bookmarkImage,largeImage;
    protected RecyclerView recyclerSmallImageList;

    protected Button btnMore;

    public ItemRowHolder(View view) {
        super(view);
        this.itemTitle = (TextView) view.findViewById(R.id.title);
        this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
        this.largeImage = (ImageView) view.findViewById(R.id.large_image);
        this.expandImage = (TextView) view.findViewById(R.id.expand);
        this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);

    }

}
</code>```

}

Nested Recyclerview Adapter:

```<code>public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

private ArrayList<SmallImages> itemsList;
private Context mContext;

public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
    this.itemsList = itemsList;
    this.mContext = context;
}

@Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
    SingleItemRowHolder mh = new SingleItemRowHolder(v);
    return mh;
}

@Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {

    SmallImages singleItem = itemsList.get(i);
}

@Override
public int getItemCount() {
    return (null != itemsList ? itemsList.size() : 0);
}

public class SingleItemRowHolder extends RecyclerView.ViewHolder {

    protected ImageView itemImage;

    public SingleItemRowHolder(View view) {
        super(view);

        //this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

            }
        });

    }

}
</code>```

}

答:
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.

/////Adapter class

```<code>public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {

    private Context mContext;
    private int rowLayout;
    private List<ModelRouteDetailsUp> dataMembers;
    private ArrayList<ModelRouteDetailsUp> arraylist;
    private ArrayList<ModelKidDetailsUp> arraylist_kids;
    List<String> wordList = new ArrayList<>();
    Random rnd = new Random();
    int randomNumberFromArray;

    private ModelRouteDetailsUp personaldata;
    private ProgressDialog pDialog;
    private ConnectionDetector cd;
    String img_baseurl = "";
    String item = "";

    public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
        this.mContext = mcontext;
        this.rowLayout = rowLayout;
        this.dataMembers = tripList;
        wordList.clear();
        this.img_baseurl = img_baseurl;
        arraylist = new ArrayList<>();
        arraylist_kids = new ArrayList<>();
        arraylist.addAll(dataMembers);
        cd = new ConnectionDetector(mcontext);
        pDialog = KPUtils.initializeProgressDialog(mcontext);
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
        return new AdapterTodayTrip.VHItem(v);
    }

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

    @Override
    public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
        viewHolder.setIsRecyclable(false);
        try {
            personaldata = dataMembers.get(position);
            if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
                viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
            }

            ****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
            if (personaldata.getKidlist().size() > 0) {
                viewHolder.linear_childview.setVisibility(View.VISIBLE);
                viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
                viewHolder.id_gallery.removeAllViews();
                LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                buttonLayoutParams.setMargins(0, 0, 8, 0);
                LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                for (int i = 0; i < personaldata.getKidlist().size(); i++) {
                    View view = layoutInflater.inflate(R.layout.view_child_list, null);
                    view.setLayoutParams(buttonLayoutParams);
                    RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
                    RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);

                    TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
                    com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
                    final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
                    int count = i + 1;
                    String count1 = "0";
                    if (count <= 10) {
                        count1 = "0" + count;
                    }

                    tv_count.setText(String.valueOf(count1));
                    viewHolder.id_gallery.addView(view);
                    final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
                    if(!baseurl.isEmpty()) {
                        iv_circular.setTag(baseurl);
                    }
                    if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
                        GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
                        bgShape.setColor(Color.parseColor("#A6b1a7a6"));
                        rl_txt.setVisibility(View.GONE);
                        //rl_img.setVisibility(View.VISIBLE);
                        tv_name.setVisibility(View.GONE);
                        Log.d("aimg_baseurl", baseurl);
                        try {
                            Picasso.with(mContext)
                                    .load(baseurl)
                                    .resize(60,60)
                                    .centerCrop()
                                    .into(iv_circular);

                            iv_circular.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    String url=iv_circular.getTag().toString().trim();
                                    if(!url.isEmpty())
                                    KPUtils.showToastShort(mContext,url);
                                    Picasso.with(mContext)
                                            .load(url)
                                            .resize(60,60)
                                            .centerCrop()
                                            .into(viewHolder.img_child);
                                }
                            });

                        } catch (Exception e) {
                        }
                    } else {

                    }
                }
            }else{
                viewHolder.linear_childview.setVisibility(View.GONE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class VHItem extends RecyclerView.ViewHolder {
        CardView cv_members;
        ImageView img_child;
        TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
        LinearLayout id_gallery,linear_childview;

        public VHItem(View itemView) {
            super(itemView);
            img_child= (ImageView) itemView.findViewById(R.id.img_child);
            cv_members = (CardView) itemView.findViewById(R.id.cv_members);
            tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
            tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
            tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
            tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
            tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
            tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
            tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
            id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
            linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
        }
    }
}
</code>```

/////////////////////////// this layout is inflated in every row
view_child_list

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/iv_circular"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@mipmap/ic_launcher"
        app:civ_border_color="#d27959"
        app:civ_border_width="1dp" />

    <RelativeLayout
        android:id="@+id/rl_txt"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:background="@drawable/gy_ring_circular"
        android:gravity="center"
        android:visibility="gone">

        <com.app.kidpooldriver.helper.CircularTextView
            android:id="@+id/tv_name"
            fontPath="fonts/Poppins-Bold.ttf"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:gravity="center"
            android:text="01"
            android:textColor="@color/white"
            android:textSize="35sp"
            tools:ignore="MissingPrefix" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rl_img"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:background="@drawable/gy_ring_circular"
        android:gravity="center"
        android:visibility="visible">

        <TextView
            android:id="@+id/tv_count"
            fontPath="fonts/Poppins-Bold.ttf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="01"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="#ffffff"
            android:textStyle="bold"
            tools:ignore="MissingPrefix" />

    </RelativeLayout>
</FrameLayout>
</code>```

///// this is the mianlayout which is inflated.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cv_members"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/card_margin"
    android:elevation="@dimen/elevation"
    card_view:cardCornerRadius="5dp">

    <LinearLayout
        android:id="@+id/main_body"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:layout_marginTop="@dimen/fifteen"
            android:orientation="horizontal"
            android:paddingLeft="@dimen/ten">

            <TextView
                android:id="@+id/tv_trip_id"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="#KD09201701"
                android:textColor="@color/colorPrimary"
                android:textSize="@dimen/twenty"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_trip_status"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/light_green"
                android:gravity="center"
                android:padding="5dp"
                android:text="In Progress"
                android:textAppearance="@style/TextAppearance.AppCompat.Small"
                android:textColor="@color/black" />

        </LinearLayout>

        <TextView
            android:id="@+id/tv_vehicle_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="20dp"
            android:text="Route 26U-26D"
            android:visibility="gone"
            android:textAppearance="@style/TextAppearance.AppCompat.Small"
            android:textColor="@color/route_textcolor" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_trip_start_time"
                android:layout_width="match_parent"
                android:visibility="gone"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/five"
                android:paddingLeft="20dp"
                android:text="06:30am"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:textColor="@color/grey_textcolor" />

            <TextView
                android:id="@+id/tv_trip_end_time"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/five"
                android:paddingLeft="20dp"
                android:text="08:30am"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:textColor="@color/grey_textcolor"
                android:visibility="gone" />

        </LinearLayout>

        <TextView
            android:id="@+id/tv_trip_way"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="@dimen/five"
            android:paddingLeft="20dp"
            android:visibility="gone"
            android:paddingRight="20dp"
            android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
            android:textAppearance="@style/TextAppearance.AppCompat.Small"
            android:textColor="@color/grey_textcolor"
            android:textStyle="normal" />
        <ImageView
            android:id="@+id/img_child"
            android:layout_width="200dp"
            android:layout_gravity="center"
            android:layout_height="200dp" />

        <LinearLayout
            android:id="@+id/linear_childview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/fifteen"
            android:orientation="horizontal">

            <HorizontalScrollView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:scrollbars="none">

                <LinearLayout
                    android:id="@+id/id_gallery"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:orientation="horizontal" />

            </HorizontalScrollView>

            <LinearLayout
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:background="@drawable/ly_ring_circular"
                android:gravity="center_vertical">

                <TextView
                    android:id="@+id/tv_total_count"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    tools:ignore="MissingPrefix"
                    fontPath="fonts/Poppins-Bold.ttf"
                    android:text="+20"
                    android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                    android:textColor="@color/white"
                    android:textStyle="bold" />

            </LinearLayout>

        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>
</code>```

/////POJO CLASS &json parsing & Adapter /////

```<code>public class ModelRouteDetailsUp {

    String city_id;
    String area_name;
    String area_status;
    String is_active;
    String areas;

    private ArrayList<ModelKidDetailsUp> kidlist;

    ///////this is the kid list
    public ArrayList<ModelKidDetailsUp> getKidlist() {
        return kidlist;
    }

    public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
        this.kidlist = kidlist;
    }
 }

**///json parsing.......**
 public boolean addRideDetails(JSONObject jsonObject) {
        Boolean flag = false;
        String isstatus = "";

        if (jsonObject != null && jsonObject.length() > 0) {
            try {
                JSONArray mainArray = jsonObject.getJSONArray("schedules");

                for (int i = 0; i < mainArray.length(); i++) {
                    ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
                    JSONObject c = mainArray.getJSONObject(i);

                    //////   For Route Details   //////
                    JSONObject route_details = c.getJSONObject("route_details");
                    modelRouteDetails.setDs_id(route_details.optString("ds_id"));
                    modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
                    modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
                    modelRouteDetails.setRoute_id(route_details.optString("route_id"));
                    modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
                    modelRouteDetails.setStart_time(route_details.optString("start_time"));
                    modelRouteDetails.setEnd_time(route_details.optString("end_time"));

                    //////   For Allotted Kids  //////
                    JSONArray kidArray = c.getJSONArray("alloted_kids");
                    ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
                    if (kidArray.length() > 0) {
                        for (int j = 0; j < kidArray.length(); j++) {
                            ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
                            JSONObject kidObject = kidArray.getJSONObject(j);
                            kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
                            kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
                            kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
                            kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
                            genre.add(kidDetailsUp);
                        }
                    }
///////add the kidlist here
                    modelRouteDetails.setKidlist(genre);

////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
                    //}
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return flag;
    }

**/////adapter callfrom class**

private void showData() {
        if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
            adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
            rv_trip_list.setAdapter(adapterTodayTrip);
        }else {
            tv_msg.setVisibility(View.VISIBLE);
        }
    }
</code>```

Body:
Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.

Parent Recyclerview Adapter:

public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {

private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
    this.dataList = dataList;
    this.mContext = context;
}

@Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
    ItemRowHolder mh = new ItemRowHolder(v);
    return mh;
}

@Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {

    final String itemTitle = dataList.get(i).getTitle();
    final String itemDescription = dataList.get(i).getDescription();

    ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();

    itemRowHolder.itemTitle.setText(Html.fromHtml("" + itemTitle + "  " + itemDescription));

    SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);

    itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
    itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
    itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);

}

@Override
public int getItemCount() {
    return (null != dataList ? dataList.size() : 0);
}

public class ItemRowHolder extends RecyclerView.ViewHolder {

    protected TextView itemTitle,  expandImage;
    protected ImageView bookmarkImage,largeImage;
    protected RecyclerView recyclerSmallImageList;

    protected Button btnMore;

    public ItemRowHolder(View view) {
        super(view);
        this.itemTitle = (TextView) view.findViewById(R.id.title);
        this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
        this.largeImage = (ImageView) view.findViewById(R.id.large_image);
        this.expandImage = (TextView) view.findViewById(R.id.expand);
        this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);

    }

}

}

Nested Recyclerview Adapter:

public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

private ArrayList<SmallImages> itemsList;
private Context mContext;

public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
    this.itemsList = itemsList;
    this.mContext = context;
}

@Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
    SingleItemRowHolder mh = new SingleItemRowHolder(v);
    return mh;
}

@Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {

    SmallImages singleItem = itemsList.get(i);
}

@Override
public int getItemCount() {
    return (null != itemsList ? itemsList.size() : 0);
}

public class SingleItemRowHolder extends RecyclerView.ViewHolder {

    protected ImageView itemImage;

    public SingleItemRowHolder(View view) {
        super(view);

        //this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

            }
        });

    }

}

}

Body:
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.

/////Adapter class

public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {

    private Context mContext;
    private int rowLayout;
    private List<ModelRouteDetailsUp> dataMembers;
    private ArrayList<ModelRouteDetailsUp> arraylist;
    private ArrayList<ModelKidDetailsUp> arraylist_kids;
    List<String> wordList = new ArrayList<>();
    Random rnd = new Random();
    int randomNumberFromArray;

    private ModelRouteDetailsUp personaldata;
    private ProgressDialog pDialog;
    private ConnectionDetector cd;
    String img_baseurl = "";
    String item = "";

    public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
        this.mContext = mcontext;
        this.rowLayout = rowLayout;
        this.dataMembers = tripList;
        wordList.clear();
        this.img_baseurl = img_baseurl;
        arraylist = new ArrayList<>();
        arraylist_kids = new ArrayList<>();
        arraylist.addAll(dataMembers);
        cd = new ConnectionDetector(mcontext);
        pDialog = KPUtils.initializeProgressDialog(mcontext);
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
        return new AdapterTodayTrip.VHItem(v);
    }

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

    @Override
    public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
        viewHolder.setIsRecyclable(false);
        try {
            personaldata = dataMembers.get(position);
            if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
                viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
            }

            ****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
            if (personaldata.getKidlist().size() > 0) {
                viewHolder.linear_childview.setVisibility(View.VISIBLE);
                viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
                viewHolder.id_gallery.removeAllViews();
                LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                buttonLayoutParams.setMargins(0, 0, 8, 0);
                LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                for (int i = 0; i < personaldata.getKidlist().size(); i++) {
                    View view = layoutInflater.inflate(R.layout.view_child_list, null);
                    view.setLayoutParams(buttonLayoutParams);
                    RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
                    RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);

                    TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
                    com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
                    final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
                    int count = i + 1;
                    String count1 = "0";
                    if (count <= 10) {
                        count1 = "0" + count;
                    }

                    tv_count.setText(String.valueOf(count1));
                    viewHolder.id_gallery.addView(view);
                    final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
                    if(!baseurl.isEmpty()) {
                        iv_circular.setTag(baseurl);
                    }
                    if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
                        GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
                        bgShape.setColor(Color.parseColor("#A6b1a7a6"));
                        rl_txt.setVisibility(View.GONE);
                        //rl_img.setVisibility(View.VISIBLE);
                        tv_name.setVisibility(View.GONE);
                        Log.d("aimg_baseurl", baseurl);
                        try {
                            Picasso.with(mContext)
                                    .load(baseurl)
                                    .resize(60,60)
                                    .centerCrop()
                                    .into(iv_circular);

                            iv_circular.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    String url=iv_circular.getTag().toString().trim();
                                    if(!url.isEmpty())
                                    KPUtils.showToastShort(mContext,url);
                                    Picasso.with(mContext)
                                            .load(url)
                                            .resize(60,60)
                                            .centerCrop()
                                            .into(viewHolder.img_child);
                                }
                            });

                        } catch (Exception e) {
                        }
                    } else {

                    }
                }
            }else{
                viewHolder.linear_childview.setVisibility(View.GONE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class VHItem extends RecyclerView.ViewHolder {
        CardView cv_members;
        ImageView img_child;
        TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
        LinearLayout id_gallery,linear_childview;

        public VHItem(View itemView) {
            super(itemView);
            img_child= (ImageView) itemView.findViewById(R.id.img_child);
            cv_members = (CardView) itemView.findViewById(R.id.cv_members);
            tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
            tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
            tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
            tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
            tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
            tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
            tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
            id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
            linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
        }
    }
}

/////////////////////////// this layout is inflated in every row
view_child_list

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/iv_circular"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@mipmap/ic_launcher"
        app:civ_border_color="#d27959"
        app:civ_border_width="1dp" />

    <RelativeLayout
        android:id="@+id/rl_txt"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:background="@drawable/gy_ring_circular"
        android:gravity="center"
        android:visibility="gone">

        <com.app.kidpooldriver.helper.CircularTextView
            android:id="@+id/tv_name"
            fontPath="fonts/Poppins-Bold.ttf"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:gravity="center"
            android:text="01"
            android:textColor="@color/white"
            android:textSize="35sp"
            tools:ignore="MissingPrefix" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rl_img"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:background="@drawable/gy_ring_circular"
        android:gravity="center"
        android:visibility="visible">

        <TextView
            android:id="@+id/tv_count"
            fontPath="fonts/Poppins-Bold.ttf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="01"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="#ffffff"
            android:textStyle="bold"
            tools:ignore="MissingPrefix" />

    </RelativeLayout>
</FrameLayout>

///// this is the mianlayout which is inflated.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cv_members"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/card_margin"
    android:elevation="@dimen/elevation"
    card_view:cardCornerRadius="5dp">

    <LinearLayout
        android:id="@+id/main_body"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:layout_marginTop="@dimen/fifteen"
            android:orientation="horizontal"
            android:paddingLeft="@dimen/ten">

            <TextView
                android:id="@+id/tv_trip_id"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="#KD09201701"
                android:textColor="@color/colorPrimary"
                android:textSize="@dimen/twenty"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_trip_status"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/light_green"
                android:gravity="center"
                android:padding="5dp"
                android:text="In Progress"
                android:textAppearance="@style/TextAppearance.AppCompat.Small"
                android:textColor="@color/black" />

        </LinearLayout>

        <TextView
            android:id="@+id/tv_vehicle_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="20dp"
            android:text="Route 26U-26D"
            android:visibility="gone"
            android:textAppearance="@style/TextAppearance.AppCompat.Small"
            android:textColor="@color/route_textcolor" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_trip_start_time"
                android:layout_width="match_parent"
                android:visibility="gone"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/five"
                android:paddingLeft="20dp"
                android:text="06:30am"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:textColor="@color/grey_textcolor" />

            <TextView
                android:id="@+id/tv_trip_end_time"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/five"
                android:paddingLeft="20dp"
                android:text="08:30am"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:textColor="@color/grey_textcolor"
                android:visibility="gone" />

        </LinearLayout>

        <TextView
            android:id="@+id/tv_trip_way"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="@dimen/five"
            android:paddingLeft="20dp"
            android:visibility="gone"
            android:paddingRight="20dp"
            android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
            android:textAppearance="@style/TextAppearance.AppCompat.Small"
            android:textColor="@color/grey_textcolor"
            android:textStyle="normal" />
        <ImageView
            android:id="@+id/img_child"
            android:layout_width="200dp"
            android:layout_gravity="center"
            android:layout_height="200dp" />

        <LinearLayout
            android:id="@+id/linear_childview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/fifteen"
            android:orientation="horizontal">

            <HorizontalScrollView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:scrollbars="none">

                <LinearLayout
                    android:id="@+id/id_gallery"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:orientation="horizontal" />

            </HorizontalScrollView>

            <LinearLayout
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:background="@drawable/ly_ring_circular"
                android:gravity="center_vertical">

                <TextView
                    android:id="@+id/tv_total_count"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    tools:ignore="MissingPrefix"
                    fontPath="fonts/Poppins-Bold.ttf"
                    android:text="+20"
                    android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                    android:textColor="@color/white"
                    android:textStyle="bold" />

            </LinearLayout>

        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>

/////POJO CLASS &json parsing & Adapter /////

public class ModelRouteDetailsUp {

    String city_id;
    String area_name;
    String area_status;
    String is_active;
    String areas;

    private ArrayList<ModelKidDetailsUp> kidlist;

    ///////this is the kid list
    public ArrayList<ModelKidDetailsUp> getKidlist() {
        return kidlist;
    }

    public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
        this.kidlist = kidlist;
    }
 }

**///json parsing.......**
 public boolean addRideDetails(JSONObject jsonObject) {
        Boolean flag = false;
        String isstatus = "";

        if (jsonObject != null && jsonObject.length() > 0) {
            try {
                JSONArray mainArray = jsonObject.getJSONArray("schedules");

                for (int i = 0; i < mainArray.length(); i++) {
                    ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
                    JSONObject c = mainArray.getJSONObject(i);

                    //////   For Route Details   //////
                    JSONObject route_details = c.getJSONObject("route_details");
                    modelRouteDetails.setDs_id(route_details.optString("ds_id"));
                    modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
                    modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
                    modelRouteDetails.setRoute_id(route_details.optString("route_id"));
                    modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
                    modelRouteDetails.setStart_time(route_details.optString("start_time"));
                    modelRouteDetails.setEnd_time(route_details.optString("end_time"));

                    //////   For Allotted Kids  //////
                    JSONArray kidArray = c.getJSONArray("alloted_kids");
                    ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
                    if (kidArray.length() > 0) {
                        for (int j = 0; j < kidArray.length(); j++) {
                            ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
                            JSONObject kidObject = kidArray.getJSONObject(j);
                            kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
                            kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
                            kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
                            kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
                            genre.add(kidDetailsUp);
                        }
                    }
///////add the kidlist here
                    modelRouteDetails.setKidlist(genre);

////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
                    //}
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return flag;
    }

**/////adapter callfrom class**

private void showData() {
        if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
            adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
            rv_trip_list.setAdapter(adapterTodayTrip);
        }else {
            tv_msg.setVisibility(View.VISIBLE);
        }
    }


来源: stackexchange

问:
Text color animation
Is there a way to animate a text color change (from anycolor to white)?

The only variant I came up with, is placing two textviews (with the same text) in one place, and fading the top one, so the bottom one (that has a white color) will become visible.

P.S. I scrapped the variant of the 2 TextViews since it looked weird (edges weren't smooth and, since I have a lot of such elements on the screen it was really lagging the scrolling). What I did, was a crazy hack that does the animation with the use of a Thread and setTextColor (that also forces redraw of a textview).

Since I needed only 2 color changes (from red to white, and from green to white) I hardcoded the values and all of the transition colors between them. So here's how it looks:

```<code>public class BlinkingTextView extends TextView {
public BlinkingTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void animateBlink(final boolean red) {
    if (animator != null) {
        animator.drop();
    }
    animator = new Animator(this, red);
    animator.start();
}

public void clearBlinkAnimation() {
    if (animator != null) {
        animator.drop();
    }
}

private Animator animator;

private final static class Animator extends Thread {
    public Animator(final TextView textView, final boolean red) {
        this.textView = textView;
        if (red) {
            SET_TO_USE = RED;
        } else {
            SET_TO_USE = GREEN;
        }
    }

    private TextView textView;

    private final int[] SET_TO_USE;

    private final static int[] RED = {
        -2142396,
        -2008754,
        -1874854,
        -1740697,
        -1540490,
        -1405563,
        -1205099,
        -1004634,
        -804170,
        -669243,
        -469036,
        -334879,
        -200979,
        -67337,
        -1
    };
    private final static int[] GREEN = {
        -6959821,
        -6565826,
        -6106293,
        -5646758,
        -5055894,
        -4530309,
        -3939444,
        -3283042,
        -2692177,
        -2166592,
        -1575728,
        -1116193,
        -656660,
        -262665,
        -1
    };

    private boolean stop;

    @Override
    public void run() {
        int i = 0;
        while (i < 15) {
            if (stop) break;
            final int color = SET_TO_USE[i];
            if (stop) break;
            textView.post(new Runnable() {
                @Override
                public void run() {
                    if (!stop) {
                        textView.setTextColor(color);
                    }
                }
            });
            if (stop) break;
            i++;
            if (stop) break;
            try {
                Thread.sleep(66);
            } catch (InterruptedException e) {}
            if (stop) break;
        }
    }

    public void drop() {
        stop = true;
    }
}
}
</code>```

答:
No need to keep handles to the two text views. First add the fadeIn/fadeOut animations:

```<code>textSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
textSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
</code>```

then:

```<code>TextView currentTextView = (TextView)(textSwitcher.getNextView().equals(
  textSwitcher.getChildAt(0)) ?
  textSwitcher.getChildAt(1) : textSwitcher.getChildAt(0)
);
// setCurrentText() first to be the same as newText if you need to
textSwitcher.setTextColor(fadeOutColor);
((TextView) textSwitcher.getNextView()).setTextColor(Color.WHITE);
textSwitcher.setText(newText);
</code>```

Just implemented it like this so proven to work.

ContentLicense: CC BY-SA 2.5

Title: Text color animation

Body:
Is there a way to animate a text color change (from anycolor to white)?

The only variant I came up with, is placing two textviews (with the same text) in one place, and fading the top one, so the bottom one (that has a white color) will become visible.

P.S. I scrapped the variant of the 2 TextViews since it looked weird (edges weren't smooth and, since I have a lot of such elements on the screen it was really lagging the scrolling). What I did, was a crazy hack that does the animation with the use of a Thread and setTextColor (that also forces redraw of a textview).

Since I needed only 2 color changes (from red to white, and from green to white) I hardcoded the values and all of the transition colors between them. So here's how it looks:

public class BlinkingTextView extends TextView {
public BlinkingTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void animateBlink(final boolean red) {
    if (animator != null) {
        animator.drop();
    }
    animator = new Animator(this, red);
    animator.start();
}

public void clearBlinkAnimation() {
    if (animator != null) {
        animator.drop();
    }
}

private Animator animator;

private final static class Animator extends Thread {
    public Animator(final TextView textView, final boolean red) {
        this.textView = textView;
        if (red) {
            SET_TO_USE = RED;
        } else {
            SET_TO_USE = GREEN;
        }
    }

    private TextView textView;

    private final int[] SET_TO_USE;

    private final static int[] RED = {
        -2142396,
        -2008754,
        -1874854,
        -1740697,
        -1540490,
        -1405563,
        -1205099,
        -1004634,
        -804170,
        -669243,
        -469036,
        -334879,
        -200979,
        -67337,
        -1
    };
    private final static int[] GREEN = {
        -6959821,
        -6565826,
        -6106293,
        -5646758,
        -5055894,
        -4530309,
        -3939444,
        -3283042,
        -2692177,
        -2166592,
        -1575728,
        -1116193,
        -656660,
        -262665,
        -1
    };

    private boolean stop;

    @Override
    public void run() {
        int i = 0;
        while (i < 15) {
            if (stop) break;
            final int color = SET_TO_USE[i];
            if (stop) break;
            textView.post(new Runnable() {
                @Override
                public void run() {
                    if (!stop) {
                        textView.setTextColor(color);
                    }
                }
            });
            if (stop) break;
            i++;
            if (stop) break;
            try {
                Thread.sleep(66);
            } catch (InterruptedException e) {}
            if (stop) break;
        }
    }

    public void drop() {
        stop = true;
    }
}
}

Body:
No need to keep handles to the two text views. First add the fadeIn/fadeOut animations:

textSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
textSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));

then:

TextView currentTextView = (TextView)(textSwitcher.getNextView().equals(
  textSwitcher.getChildAt(0)) ?
  textSwitcher.getChildAt(1) : textSwitcher.getChildAt(0)
);
// setCurrentText() first to be the same as newText if you need to
textSwitcher.setTextColor(fadeOutColor);
((TextView) textSwitcher.getNextView()).setTextColor(Color.WHITE);
textSwitcher.setText(newText);

Just implemented it like this so proven to work.


问:
Passing value from activity to view class
I have an activity in which there are 3 checkboxes in different views. These checkboxes are to pick up a color.

In the DrawingView class, I have to draw on my canvas with the color that is checked. What I want is to pass an integer value from the activity to the view class and set the color of paint accordingly.  itried using getter and setters, but I get black color. I suppose this is because the color is being set in the constructor itself, and it does not change when I check any box.

Please refer this for updates in the below code

Code:

MainActivity: the color/checkbox is selected here. And the drawing is to be done in the layout of this activity itself.

```<code>        carImageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            drawingView=new DrawingView(carImageView.getContext());
            drawingView=new DrawingView(carImageView.getContext(),null);
            drawingView.setColor(color);
            return false;
        }
    });

  scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
          if(b)
          {
              color=1;
              chipsCb.setChecked(false);
              dentsCb.setChecked(false);
          }
      }
  });
    chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                color=2;
                scratchesCb.setChecked(false);
                dentsCb.setChecked(false);
            }
        }
    });
    dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                color=3;
                chipsCb.setChecked(false);
                scratchesCb.setChecked(false);
            }
        }
    });
}
</code>```

View Class:

```<code>   public DrawingView(Context context, @Nullable AttributeSet attrs) {
   super(context, attrs);
    mPaint=new Paint();
    if(color==1)
        mPaint.setColor(Color.RED);
    else if(color==2)
        mPaint.setColor(Color.BLUE);
    else if(color==3)
        mPaint.setColor(Color.GREEN);
    this.context=context;
    mPath=new Path();
    mPaint.setAntiAlias(true);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.MITER);
    mPaint.setStrokeWidth(5f);
}
     public void setColor(int color){
    this.color=color;
}
public int getColor(){
    return this.color;
}
</code>```

Edit

I don't necessarily want to use the exact same code. All I want is to change paint color when a checkbox is selected to be able to draw on an image view. Any other approach is welcome.

答:
Define static data member in your DrawingView

static int color = 1; //default

Then, from your activity simply call

DrawingView.color = someValue;

Static Keyword before variable color will make sure there is only one variable reference for all objects of your DrawingView class.

ContentLicense: CC BY-SA 3.0

Body:
I have an activity in which there are 3 checkboxes in different views. These checkboxes are to pick up a color.

In the DrawingView class, I have to draw on my canvas with the color that is checked. What I want is to pass an integer value from the activity to the view class and set the color of paint accordingly.  itried using getter and setters, but I get black color. I suppose this is because the color is being set in the constructor itself, and it does not change when I check any box.

Please refer this for updates in the below code

Code:

MainActivity: the color/checkbox is selected here. And the drawing is to be done in the layout of this activity itself.

        carImageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            drawingView=new DrawingView(carImageView.getContext());
            drawingView=new DrawingView(carImageView.getContext(),null);
            drawingView.setColor(color);
            return false;
        }
    });

  scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
          if(b)
          {
              color=1;
              chipsCb.setChecked(false);
              dentsCb.setChecked(false);
          }
      }
  });
    chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                color=2;
                scratchesCb.setChecked(false);
                dentsCb.setChecked(false);
            }
        }
    });
    dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                color=3;
                chipsCb.setChecked(false);
                scratchesCb.setChecked(false);
            }
        }
    });
}

View Class:

   public DrawingView(Context context, @Nullable AttributeSet attrs) {
   super(context, attrs);
    mPaint=new Paint();
    if(color==1)
        mPaint.setColor(Color.RED);
    else if(color==2)
        mPaint.setColor(Color.BLUE);
    else if(color==3)
        mPaint.setColor(Color.GREEN);
    this.context=context;
    mPath=new Path();
    mPaint.setAntiAlias(true);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.MITER);
    mPaint.setStrokeWidth(5f);
}
     public void setColor(int color){
    this.color=color;
}
public int getColor(){
    return this.color;
}

Edit

I don't necessarily want to use the exact same code. All I want is to change paint color when a checkbox is selected to be able to draw on an image view. Any other approach is welcome.


问:
VueRouter is not defined
I have a laravel project and want use Vue.js for frontend. But i have never used
something more complicated than jquery. I can't run vue-router.

In my app.js

```<code>require('./bootstrap');
require('./vue-router');
require('./routes');

window.Vue = require('vue');
     const app = new Vue({
     el: '#app',
});
</code>```

Then i copy code vue-router from https://router.vuejs.org/en/installation.html

In my routes.js

```<code>const router = new VueRouter();

var App = Vue.extend({});

router.start(App, '#app');
</code>```

And when i try open page in console i see next : "VueRouter is not defined"

答:
You forgot to use the Vue.use method, here's how you do it:

```<code>Vue.use(VueRouter) // use the imported router as the parameter.
</code>```

Title: VueRouter is not defined

Body:
I have a laravel project and want use Vue.js for frontend. But i have never used
something more complicated than jquery. I can't run vue-router.

In my app.js

require('./bootstrap');
require('./vue-router');
require('./routes');

window.Vue = require('vue');
     const app = new Vue({
     el: '#app',
});

Then i copy code vue-router from https://router.vuejs.org/en/installation.html

In my routes.js

const router = new VueRouter();

var App = Vue.extend({});

router.start(App, '#app');

And when i try open page in console i see next : "VueRouter is not defined"

Body:
You forgot to use the Vue.use method, here's how you do it:

Vue.use(VueRouter) // use the imported router as the parameter.


问:
For-loop in R to create a new file (but gives incorrect/unexpected output)
I'm currently busy with some data and I need to check their validity.
Therefore, I would like to use a for-loop to go through all my data files.
In this for-loop, I would like to calculate some things (like mean, min,max...).

My code below works but produced an incorrectly written csv file. The problem occurs after the calculations (and their values) are done during csv file creation. CSV:

```<code>"c.1..1..1004.89081855716..630.174466667434..461.738905906677.." "c.1..1..950.990843858612..479.98560814955..517.955102920532.."
1 1
1 1
1004.89081855716 950.990843858612
630.174466667434 479.98560814955
461.738905906677 517.955102920532
1535.86795806885 1452.30199813843
-13.3948961645365 3.72026950120926
1259.26423788071 1159.17089223862
</code>```

Approach/What I'm expecting:
So I start from some data files with eye tracking data in it.
As you can see at the beginning of the code, I try to get some values out of this eye tracking data (validity, new file with only validity == 1 data...). Once I created the filtered_data dataframe, I want to calculate some extra values out of it (mean, sd, min/max).
My plan is to create a new csv file (validity_loop.csv) in which I can find all my calculations (validity_left, validity_right,mean_eye_x, mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y). All in a row. One row for each data set (file_list[i]).

Can someone help me in how to tackle and solve this issue?

Here is my code:

```<code>set <- setwd("/Users/Sarah/Documents")

file_list <- list.files(set, pattern = ".csv", all.files = TRUE)
validity_list <- data_list <- vector("list", "length" = length(file_list))

for(i in seq_along(file_list)){

  filename = file_list[i]

  #read files

  data_frame = read.csv(filename, sep = ",", dec = ".",
                        header = TRUE,
                        stringsAsFactors = FALSE)

  #what has to be done
  #validity

  validity_left <- mean(is.numeric(data_frame$left_gaze_point_validity))
  validity_right <-mean(is.numeric(data_frame$right_gaze_point_validity))

  #Zuiver dataframe (validity ==1)

  to_keep = which(data_frame$left_gaze_point_validity == 1 &
                  data_frame$right_gaze_point_validity==1)

  filtered_data = data_frame[to_keep,]
  filtered_data$left_eye_x = as.numeric(filtered_data$left_eye_x)
  filtered_data$left_eye_y = as.numeric(filtered_data$left_eye_y)
  filtered_data$right_eye_x = as.numeric(filtered_data$right_eye_x)
  filtered_data$right_eye_y = as.numeric(filtered_data$right_eye_y)

  #1 eye-data

  filtered_data$eye_x <- (filtered_data$left_eye_x+filtered_data$right_eye_x)/2
  filtered_data$eye_y <- (filtered_data$left_eye_y+filtered_data$right_eye_y)/2

  #Pixels

  filtered_data$eye_x <- (filtered_data$eye_x)*1920
  filtered_data$eye_y <- (filtered_data$eye_y)*1080

  #SD and Mean + min-max

  mean_eye_x<- mean(filtered_data$eye_x)
  mean_eye_y <- mean(filtered_data$eye_y)

  sd_eye_x <- sd(filtered_data$eye_x)
  sd_eye_y <- sd(filtered_data$eye_y)

  min_eye_x <- min(filtered_data$eye_x)
  min_eye_y <- min(filtered_data$eye_y)
  max_eye_x <- max(filtered_data$eye_x)
  max_eye_y <- max(filtered_data$eye_y)

  #add everything to new file

  validity_list[[i]] <- c(validity_left, validity_right,
                          mean_eye_x, mean_eye_y,
                          min_eye_x, min_eye_y,
                          max_eye_x, max_eye_y)

}

#new document
write.table(validity_list,
            file = "Master T&O/Thesis /Loop/Validity/validity_loop.csv",
            col.names = TRUE, row.names = FALSE)
</code>```

答:
If I get it then the following line grabs all your data together:

```<code>validity_list[[i]] <- c (validity_left, validity_right,mean_eye_x,
                         mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y).
</code>```

if it's like in python then I would have:

```<code>validity_list = (validity_left, validity_right,mean_eye_x,
                      mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y)
</code>```

... whereas the '=' tell the interpreter that everything behind it is a tuple '(', data, ')' ...which makes it one single dataset and if I then write it... it would be end up in one column. If you do a pick using a for-loop I would get "validity_left" writing in a separate column. In your case adding this to your below code an option?

```<code>for item in validity_list:
         function to process item..etc.
</code>```

Body:
I'm currently busy with some data and I need to check their validity.
Therefore, I would like to use a for-loop to go through all my data files.
In this for-loop, I would like to calculate some things (like mean, min,max...).

My code below works but produced an incorrectly written csv file. The problem occurs after the calculations (and their values) are done during csv file creation. CSV:

"c.1..1..1004.89081855716..630.174466667434..461.738905906677.." "c.1..1..950.990843858612..479.98560814955..517.955102920532.."
1 1
1 1
1004.89081855716 950.990843858612
630.174466667434 479.98560814955
461.738905906677 517.955102920532
1535.86795806885 1452.30199813843
-13.3948961645365 3.72026950120926
1259.26423788071 1159.17089223862

Approach/What I'm expecting:
So I start from some data files with eye tracking data in it.
As you can see at the beginning of the code, I try to get some values out of this eye tracking data (validity, new file with only validity == 1 data...). Once I created the filtered_data dataframe, I want to calculate some extra values out of it (mean, sd, min/max).
My plan is to create a new csv file (validity_loop.csv) in which I can find all my calculations (validity_left, validity_right,mean_eye_x, mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y). All in a row. One row for each data set (file_list[i]).

Can someone help me in how to tackle and solve this issue?

Here is my code:

set <- setwd("/Users/Sarah/Documents")

file_list <- list.files(set, pattern = ".csv", all.files = TRUE)
validity_list <- data_list <- vector("list", "length" = length(file_list))

for(i in seq_along(file_list)){

  filename = file_list[i]

  #read files

  data_frame = read.csv(filename, sep = ",", dec = ".",
                        header = TRUE,
                        stringsAsFactors = FALSE)

  #what has to be done
  #validity

  validity_left <- mean(is.numeric(data_frame$left_gaze_point_validity))
  validity_right <-mean(is.numeric(data_frame$right_gaze_point_validity))

  #Zuiver dataframe (validity ==1)

  to_keep = which(data_frame$left_gaze_point_validity == 1 &
                  data_frame$right_gaze_point_validity==1)

  filtered_data = data_frame[to_keep,]
  filtered_data$left_eye_x = as.numeric(filtered_data$left_eye_x)
  filtered_data$left_eye_y = as.numeric(filtered_data$left_eye_y)
  filtered_data$right_eye_x = as.numeric(filtered_data$right_eye_x)
  filtered_data$right_eye_y = as.numeric(filtered_data$right_eye_y)

  #1 eye-data

  filtered_data$eye_x <- (filtered_data$left_eye_x+filtered_data$right_eye_x)/2
  filtered_data$eye_y <- (filtered_data$left_eye_y+filtered_data$right_eye_y)/2

  #Pixels

  filtered_data$eye_x <- (filtered_data$eye_x)*1920
  filtered_data$eye_y <- (filtered_data$eye_y)*1080

  #SD and Mean + min-max

  mean_eye_x<- mean(filtered_data$eye_x)
  mean_eye_y <- mean(filtered_data$eye_y)

  sd_eye_x <- sd(filtered_data$eye_x)
  sd_eye_y <- sd(filtered_data$eye_y)

  min_eye_x <- min(filtered_data$eye_x)
  min_eye_y <- min(filtered_data$eye_y)
  max_eye_x <- max(filtered_data$eye_x)
  max_eye_y <- max(filtered_data$eye_y)

  #add everything to new file

  validity_list[[i]] <- c(validity_left, validity_right,
                          mean_eye_x, mean_eye_y,
                          min_eye_x, min_eye_y,
                          max_eye_x, max_eye_y)

}

#new document
write.table(validity_list,
            file = "Master T&O/Thesis /Loop/Validity/validity_loop.csv",
            col.names = TRUE, row.names = FALSE)

Body:
If I get it then the following line grabs all your data together:

validity_list[[i]] <- c (validity_left, validity_right,mean_eye_x,
                         mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y).

if it's like in python then I would have:

validity_list = (validity_left, validity_right,mean_eye_x,
                      mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y)

... whereas the '=' tell the interpreter that everything behind it is a tuple '(', data, ')' ...which makes it one single dataset and if I then write it... it would be end up in one column. If you do a pick using a for-loop I would get "validity_left" writing in a separate column. In your case adding this to your below code an option?

for item in validity_list:
         function to process item..etc.


问:
Subscript out of range on VBA
I am writing my first VBA. I have a sheet named Sheet1. That sheet has a column E; I would like to delete all rows which have an empty field on column E.

Therefore, I wrote this code:

```<code>Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub
</code>```

However, when I run it, I get this error:

Subscript out of range

Why is this error occurring? I am sure the column E exists in Sheet1. Are my references incorrect?

EDIT

If I try Columns("E") or Range("E:E"), instead of Columns("E:E") I get the same error

答:
Your code will work if there are any REAL empty cells in column E (within UsedRange).

You may have cells that contain formulas returning Null.  SpecialCells does not consider them empty.  You may have cells in column E containing Null as a constant; SpecialCells also considers them filled.

EDIT#1:

Based upon your specific error message make sure the worksheet name is spelled correctly.  Sheet1 is not the same as Sheet 1

Title: Subscript out of range on VBA

Body:
I am writing my first VBA. I have a sheet named Sheet1. That sheet has a column E; I would like to delete all rows which have an empty field on column E.

Therefore, I wrote this code:

Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

However, when I run it, I get this error:

Subscript out of range

Why is this error occurring? I am sure the column E exists in Sheet1. Are my references incorrect?

EDIT

If I try Columns("E") or Range("E:E"), instead of Columns("E:E") I get the same error


问:
Visual studio data-bind attribute highlighting [knockout.js]
In previous versions of Visual Studio I've had knockout.js syntax highlighting.

Since moving to Visual Studio 2017 Community building in Razor however, the syntax highlighting is gone and I found no way to enable it.

Interesting is however, that when I put the very same code into project built on Webforms, the highlighting seems to work at least to some degree

Is there anything I can do to enable syntax hightlighting for Razor? And/Or is there a way how to make custom syntax highlighting rules? [e.g. highlight specific data attribute, or so]

答:
Yes, in our Project we added the file reference on the _references.js file:

```<code>/// <reference path="knockout-3.4.0.debug.js" />
</code>```

This make Visual Studio Intellisense to get the sintax hightlighting on the .cshtml files.

Reference Directives

A reference directive enables Visual Studio to establish a relationship between the script you are currently editing and other scripts. The reference directive lets you include a script file in the scripting context of the current script file. This enables IntelliSense to reference externally defined functions, types, and fields as you code.

Sources:

MSDN - JavaScript IntelliSense

C# Corner - Use of _references.js File

Mads Kristensen - The history behind _references.js

Body:
Yes, in our Project we added the file reference on the _references.js file:

/// <reference path="knockout-3.4.0.debug.js" />

This make Visual Studio Intellisense to get the sintax hightlighting on the .cshtml files.

Reference Directives

A reference directive enables Visual Studio to establish a relationship between the script you are currently editing and other scripts. The reference directive lets you include a script file in the scripting context of the current script file. This enables IntelliSense to reference externally defined functions, types, and fields as you code.

Sources:

MSDN - JavaScript IntelliSense

C# Corner - Use of _references.js File

Mads Kristensen - The history behind _references.js


问:
Graphileon Interactor: how to set style for a node with a given string property
What is the right format to define a style selector for a node with a specific string property?

In Interactor one can define different styles for nodes and relationships based on their Labels and properties (doc). The example shows how to select nodes with label MyLabel and the value of property myParam larger than 5.

When trying to create a style for nodes that have a property 'kind' set to a given string 'Needle_Mover', the style is applied to all nodes with the same label, even if their property string is different.

For example:

```<code>:Program                        -> red
:Program[kind=='Needle_Mover']  -> blue
</code>```

All nodes with label Program will show blue.

I suspect it is a syntax mistake on my side... I have tried with a single = as well.

答:
The following style selectors should work

for a style for a specific value of a property

```<code>:Program[myProp=abc]
</code>```

for a style to be applied when a property exists

```<code>:Program[myProp]
</code>```

for numeric properties we also have

```<code>:Program[myNumericProp > 5]
:Program[myNumericProp = 5]
:Program[myNumericProp < 5]
</code>```

Body:
What is the right format to define a style selector for a node with a specific string property?

In Interactor one can define different styles for nodes and relationships based on their Labels and properties (doc). The example shows how to select nodes with label MyLabel and the value of property myParam larger than 5.

When trying to create a style for nodes that have a property 'kind' set to a given string 'Needle_Mover', the style is applied to all nodes with the same label, even if their property string is different.

For example:

:Program                        -> red
:Program[kind=='Needle_Mover']  -> blue

All nodes with label Program will show blue.

I suspect it is a syntax mistake on my side... I have tried with a single = as well.

Body:
The following style selectors should work

for a style for a specific value of a property

:Program[myProp=abc]

for a style to be applied when a property exists

:Program[myProp]

for numeric properties we also have

:Program[myNumericProp > 5]
:Program[myNumericProp = 5]
:Program[myNumericProp < 5]


问:
Get id of last inserted document in laravel after save() using mongodb
Here is a code </p>

```<code>public function addItem(Request $req)
{
    $data = new UserModel();
    $data->Name = $req->name;
    $data->IP=$req->ip;
    $data->username=$req->username;
    $data->password=$req->password;
    $data->save();
    return response()->json($data);
}
</code>```

答:
As I asked I'm not getting the id. I'm getting this error because after insertion. if you want to get id it must get like data->_id not data->id as I get the id data.id in ajax so I write code as below:

```<code>$data = new UserModel();
$data->Name = $req->name;
$data->IP=$req->ip;
$data->username=$req->username;
$data->password=$req->password;
$data->save();
$data->id=$data->_id;
return response()->json($data);
</code>```

and in Ajax:

```<code>$.ajax({
        type: 'post',
        url: '/addItem',
        data: {
            '_token': $('input[name=_token]').val(),
            'name': $('#en').val(),
            'ip': $('#eip').val(),
            'username': $('#eun').val(),
            'password': $('#ep').val()
        },
        success: function(data) {
            if ((data.errors)){
                $('.error').removeClass('d-none');
                $('.error').text(data.errors.name);
            }
            else {
                $('.error').addClass('d-none');
                $('#table').append("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.IP + "</td><td>" + data.Name + "</td><td>" + data.username + "</td><td>" + data.password + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-name='" + data.Name + "' data-ip='" + data.IP + "' data-username='" + data.username + "' data-password='" + data.password + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-name='" + data.Name + "' data-ip='" + data.IP + "' data-username='" + data.username + "' data-password='" + data.password + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
            }
        },
    });
</code>```

Body:
Here is a code

public function addItem(Request $req)
{
    $data = new UserModel();
    $data->Name = $req->name;
    $data->IP=$req->ip;
    $data->username=$req->username;
    $data->password=$req->password;
    $data->save();
    return response()->json($data);
}

Body:
As I asked I'm not getting the id. I'm getting this error because after insertion. if you want to get id it must get like data->_id not data->id as I get the id data.id in ajax so I write code as below:

$data = new UserModel();
$data->Name = $req->name;
$data->IP=$req->ip;
$data->username=$req->username;
$data->password=$req->password;
$data->save();
$data->id=$data->_id;
return response()->json($data);

and in Ajax:

$.ajax({
        type: 'post',
        url: '/addItem',
        data: {
            '_token': $('input[name=_token]').val(),
            'name': $('#en').val(),
            'ip': $('#eip').val(),
            'username': $('#eun').val(),
            'password': $('#ep').val()
        },
        success: function(data) {
            if ((data.errors)){
                $('.error').removeClass('d-none');
                $('.error').text(data.errors.name);
            }
            else {
                $('.error').addClass('d-none');
                $('#table').append("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.IP + "</td><td>" + data.Name + "</td><td>" + data.username + "</td><td>" + data.password + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-name='" + data.Name + "' data-ip='" + data.IP + "' data-username='" + data.username + "' data-password='" + data.password + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-name='" + data.Name + "' data-ip='" + data.IP + "' data-username='" + data.username + "' data-password='" + data.password + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
            }
        },
    });


问:
Representing mathematical relations in Alloy
I am new to Alloy and I am still quite confused. I am relatively comfortable with mathematical relations but not sure how to translate those to Alloy.

Say I have the following definition of a (mathematical) relation

```<code>rel = {(x, y) | x \in S1, y \in S2}
</code>```

Is the following Alloy fragment a correct representation for 'rel'?

```<code>sig S2 {}

sig S1 {rel: S2}
</code>```

How would I constrain this relation to be irreflexive and transitive?

答:
First define the types:

```<code> sig S1, S2 {}
</code>```

Then you can define a rel relation with the following equivalent syntaxes

```<code>let rel = { x : univ, y : univ | x in S1 and y in S2 }
let rel = { x : S1, y : S2 }
let rel = S1 -> S2
</code>```

Body:
I am new to Alloy and I am still quite confused. I am relatively comfortable with mathematical relations but not sure how to translate those to Alloy.

Say I have the following definition of a (mathematical) relation

rel = {(x, y) | x \in S1, y \in S2}

Is the following Alloy fragment a correct representation for 'rel'?

sig S2 {}

sig S1 {rel: S2}

How would I constrain this relation to be irreflexive and transitive?

Body:
First define the types:

 sig S1, S2 {}

Then you can define a rel relation with the following equivalent syntaxes

let rel = { x : univ, y : univ | x in S1 and y in S2 }
let rel = { x : S1, y : S2 }
let rel = S1 -> S2


问:
Why am I getting variable not declared
I have the following in my partial view...

```<code>@Model.ServerDetails
<div>
..... various markup
</div>
<script type="text/javascript">
    var bs = '@Model.BackupServer';
    if (bs == null) {
        bs = "";
    }
    var bssn = bs + '|' + '@Model.ServerName';

    $(document).ready( function() {
        if (bs != "") {
          $getJSON('@UrlContent("~/Details/OtherBackedUpServers?bsn=" + bssn)', function(returnedServers) {
             ..... removed for brevity...
          }
        }
    });
</code>```

Unfortunately bssn in the $getJSON() paramater is showing an error: 'bssn' is not declared. It may be inaccessible due to its protection level.

Can someone explain why and how I can correct it?

Thanks

答:
You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side.

As a workaround, you can use placeholder to generate the url. Then use .replace() method to generate the actual url.

```<code>var url = '@Url.Action("OtherBackedUpServers", "Details", new { bsn= -1})';
url = url .replace('-1', bssn);
$.getJSON(url );
</code>```

Or, Better pass the variable as payload

```<code>$.getJSON('@Url.Action("OtherBackedUpServers", "Details")', { bsn : -1});
</code>```

Title: Why am I getting variable not declared

Body:
I have the following in my partial view...

@Model.ServerDetails

..... various markup

Body:
You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side.

As a workaround, you can use placeholder to generate the url. Then use .replace() method to generate the actual url.

var url = '@Url.Action("OtherBackedUpServers", "Details", new { bsn= -1})';
url = url .replace('-1', bssn);
$.getJSON(url );

Or, Better pass the variable as payload

$.getJSON('@Url.Action("OtherBackedUpServers", "Details")', { bsn : -1});


问:
How can i filter a List neighbors is equal? Request something like unique()
If have list of af string, how can filter so equal neighbors only appears one?

Example:

```<code>['0.1', '0.1', '0.2','0.3','0.3','0.1','0.2']
</code>```

should result in

```<code>['0.1', '0.2','0.3','0.1','0.2']
</code>```

notice that element 0, 1 only appears once and element 4 and 5 also appears only once.

If use unique:

```<code>['0.1', '0.1', '0.2','0.3','0.3','0.1','0.2'].unique()
</code>```

the result will be:

```<code>['0.1', '0.2','0.3'] //what is not wanted
</code>```

Any suggestions for the best groovy method?

答:
Another, more functional way, is as follows, using inject (known in other languages as reduce):

```<code>def example = ['0.1','0.1','0.2','0.3','0.3','0.1','0.2']

def array = example.inject([example[0]]) { acc, val ->
    if (val != acc[-1]) { acc << val }
    acc
}

assert ['0.1','0.2','0.3','0.1','0.2'] == array
</code>```

The key is to start with array containing the first element, [example[0]], and then iterate over example. inject provides both the running accumulation and the value. If we add a log line:

```<code>def array = example.inject([example[0]]) { acc, val ->
    println "acc: ${acc} val: ${val}"
    if (val != acc[-1]) { acc << val }
    acc
}
</code>```

then output is:

```<code>acc: [0.1] val: 0.1
acc: [0.1] val: 0.1
acc: [0.1] val: 0.2
acc: [0.1, 0.2] val: 0.3
acc: [0.1, 0.2, 0.3] val: 0.3
acc: [0.1, 0.2, 0.3] val: 0.1
acc: [0.1, 0.2, 0.3, 0.1] val: 0.2
</code>```

Body:
If have list of af string, how can filter so equal neighbors only appears one?

Example:

['0.1', '0.1', '0.2','0.3','0.3','0.1','0.2']

should result in

['0.1', '0.2','0.3','0.1','0.2']

notice that element 0, 1 only appears once and element 4 and 5 also appears only once.

If use unique:

['0.1', '0.1', '0.2','0.3','0.3','0.1','0.2'].unique()

the result will be:

['0.1', '0.2','0.3'] //what is not wanted

Any suggestions for the best groovy method?

Body:
Another, more functional way, is as follows, using inject (known in other languages as reduce):

def example = ['0.1','0.1','0.2','0.3','0.3','0.1','0.2']

def array = example.inject([example[0]]) { acc, val ->
    if (val != acc[-1]) { acc << val }
    acc
}

assert ['0.1','0.2','0.3','0.1','0.2'] == array

The key is to start with array containing the first element, [example[0]], and then iterate over example. inject provides both the running accumulation and the value. If we add a log line:

def array = example.inject([example[0]]) { acc, val ->
    println "acc: ${acc} val: ${val}"
    if (val != acc[-1]) { acc << val }
    acc
}

then output is:

acc: [0.1] val: 0.1
acc: [0.1] val: 0.1
acc: [0.1] val: 0.2
acc: [0.1, 0.2] val: 0.3
acc: [0.1, 0.2, 0.3] val: 0.3
acc: [0.1, 0.2, 0.3] val: 0.1
acc: [0.1, 0.2, 0.3, 0.1] val: 0.2


问:
How to train a model to detect an event in a time line sequence of data
I have a time line of a users data and i want to train a model to detect events.

For example an event could be a gesture in a time line of accelerometer data.

or

time line of looking at the time (looking at a watch), (labeling nerves or calm).

What machine learning algorithm  will be appropriate for this problem?

Thanks

答:
This task is known as Event Detection and can be performed using Natural Language Processing (NLP) techniques.

There is no 'appropriate' or 'not appropriate' algorithm. You have to extract various features (e.g. Part-of-Speech tags) that enable the algorithm(s) to detect events. Then, you need to evaluate the implemented algorithms/models (assuming that you have also tuned the corresponding parameters for each algorithm) and decide which one is the best (in terms of performance). Also, you need to decide which features are helpful and which are not.

These papers might be a good starting point:

Machine Learning Algorithms for Event Detection

Event Detection Challenges, Methods, and Applications
in Natural and Artificial Systems