问:
Need to create headers within Recyclerview
I create app for sports site and need to make calendar events. There is a detail which I can't understand: how to make headers within Recyclerview for display of tournaments name that not to specified near each game (example "Примера" on the screen).

Is there a library or anyways for my task? I don’t want create many static Recyclerview and find agile ways.

Of course, there are a lot of tournaments in the calendar, so the headers should be the same.

Main class of the calendar:

```<code>public class FootballResults extends Fragment implements
View.OnClickListener, DatePickerDialog.OnDateSetListener{

private LinearLayoutManager linLM;
private FootballResultsAdapter adapter;
private ArrayList<FootballResultsData> dl;

String today_day;
String today_month;
String today_year;
String mDay;
String mMonth;
String mYear;

Button arrow_left;
Button arrow_right;
Button datepicker;

Switch swLive;

int n = 0;
//int n_plus = 1;

@SuppressLint("SetTextI18n")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rv = inflater.inflate(R.layout.results_football, container, false);

    RecyclerView footballresults_feed1 = (RecyclerView) rv.findViewById(R.id.rcMatch1);

    dl = new ArrayList<>();

    footballresults_feed1.setLayoutManager(new LinearLayoutManager(getActivity()));
    adapter = new FootballResultsAdapter(getActivity(), dl);
    footballresults_feed1.setAdapter(adapter);

    arrow_left = (Button)rv.findViewById(R.id.arrow_left);
    arrow_right = (Button)rv.findViewById(R.id.arrow_right);
    datepicker = (Button)rv.findViewById(R.id.btnDatepick);
    swLive = (Switch)rv.findViewById(R.id.swLive);

    arrow_left.setOnClickListener(this);
    arrow_right.setOnClickListener(this);

    datepicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            datepickermethod ();
        }
    });

    swLive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {swLive.setText("");}
            else {swLive.setText("");}
        }
    });

    currenttime();
    datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);

    ResultDisplay();

    return rv;
}

private void ResultDisplay() {
    @SuppressLint("StaticFieldLeak") AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {

            ResultFeed ();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            adapter.notifyDataSetChanged();
        }
    };
    task.execute();
}

void ResultFeed (){
    OkHttpClient client = new OkHttpClient();
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(C.RESULT_API+mYear+"/"+mMonth+"/"+mDay+"?sport_id=1")
            .build();
    try {
        okhttp3.Response response = client.newCall(request).execute();
        JSONObject object = new JSONObject(response.body().string());

        dl.clear();
        JSONArray sports = object.getJSONArray("sports");
        JSONObject tournament0 = sports.getJSONObject(0);

        JSONArray tournament = tournament0.getJSONArray("tournaments");
        for (int i=0; i<tournament.length(); i++){
            JSONObject matches1 = tournament.getJSONObject(i);
            Log.i (C.T, "Турнир: "+matches1.getString("tournament_name"));
            JSONArray matches0 = matches1.getJSONArray("matches");
            for (int j=0; j<matches0.length(); j++) {
                JSONObject matches = matches0.getJSONObject(j);

                String match_time = TimeFormat.TimeRadar(matches.getString("date_of_match")); //время начала матча
                String match_res = matches.getString("ft_value");
                String match_status = matches.getString("status");

                if (match_res.equals("null")) {match_res = "-:-";}
                if (match_status.equals("Не начался")) {match_status = "";}
                if (match_status.equals("null")) {match_status = "";}

                JSONObject team_home1 = matches.getJSONObject("team_home");
                String team_home = team_home1.getString("short_name");
                String team_home_logo = team_home1.getString("logo_small");

                JSONObject team_away1 = matches.getJSONObject("team_away");
                String team_away = team_away1.getString("short_name");
                String team_away_logo = team_away1.getString("logo_small");

                FootballResultsData data = new FootballResultsData(matches1.getString("tournament_name"),
                        match_time,
                        match_res,
                        team_home, team_away,
                        match_status,
                        team_home_logo,
                        team_away_logo);
            dl.add(data);
        }}

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

@SuppressLint("SimpleDateFormat")
void currenttime () {
    long date_today = System.currentTimeMillis();
    today_day = new SimpleDateFormat("dd").format(date_today);
    today_month = new SimpleDateFormat("MM").format(date_today);
    today_year = new SimpleDateFormat("yyyy").format(date_today);
    mDay = today_day; mMonth = today_month; mYear = today_year;
}

@SuppressLint("SimpleDateFormat")
void calendar (String dd, String mm, String yyyy, int day_n) {
    String sourceDate = yyyy+"-"+mm+"-"+dd;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date myDate;
    try {
        myDate = format.parse(sourceDate);
        myDate = DateUtil.addDays(myDate, day_n);
        String mDate = new SimpleDateFormat("dd MM yyyy").format(new SimpleDateFormat("EEE MMM dd kk:mm:ss zzzz yyyy").parse(myDate.toString()));
        mDay = new SimpleDateFormat("dd").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
        mMonth = new SimpleDateFormat("MM").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
        mYear = new SimpleDateFormat("yyyy").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
        Log.i(C.T, mDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
    //currenttime ();
    switch (v.getId()) {
        case R.id.arrow_left: {n=n-1; break;}
        case R.id.arrow_right: {n=n+1; break;}
        default: break;
    }
    calendar(today_day, today_month, today_year, n);
    datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
    ResultDisplay();
}

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

}

void datepickermethod () {
    DatePickerDialog datepick = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
    @SuppressLint("SetTextI18n")
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        datepicker.setText(dayOfMonth+" "+TimeFormat.monthDef(month+1)+" "+year);
        mDay = String.valueOf(dayOfMonth); mMonth = String.valueOf(month+1); mYear = String.valueOf(year);
        n=0;
        today_day = String.valueOf(dayOfMonth); today_month = String.valueOf(month+1); today_year = String.valueOf(year);
        ResultDisplay();
    }
        }, Integer.parseInt(today_year), Integer.parseInt(today_month)-1, Integer.parseInt(today_day));
    datepick.show();
}
}
</code>```

For setters and getters:

```<code>class FootballResultsData {

public FootballResultsData(String tournament_name, String match_time, String match_result, String team_home, String team_away, String match_status, String team_home_logo, String team_away_logo) {
    this.setTournament_name(tournament_name);
    this.setMatch_time(match_time);
    this.setMatch_result(match_result);
    this.setTeam_home(team_home);
    this.setTeam_away(team_away);
    this.setMatch_status(match_status);
    this.setTeam_home_logo(team_home_logo);
    this.setTeam_away_logo(team_away_logo);
}

private String tournament_name;
private String match_time;
private String match_result;
private String team_home;
private String team_away;
private String match_status;
private String team_home_logo;
private String team_away_logo;

public String getMatch_time() { return match_time; }

public void setMatch_time(String match_time) {
    this.match_time = match_time;
}

public String getTeam_home() {
    return team_home;
}

public void setTeam_home(String team_home) {
    this.team_home = team_home;
}

public String getTeam_away() {
    return team_away;
}

public void setTeam_away(String team_away) {
    this.team_away = team_away;
}

public String getMatch_status() {
    return match_status;
}

public void setMatch_status(String match_status) {
    this.match_status = match_status;
}

public String getMatch_result() { return match_result; }

public void setMatch_result(String match_result) { this.match_result = match_result; }

public String getTeam_home_logo() {
    return team_home_logo;
}

public void setTeam_home_logo(String team_home_logo) {
    this.team_home_logo = team_home_logo;
}

public String getTeam_away_logo() {
    return team_away_logo;
}

public void setTeam_away_logo(String team_away_logo) {
    this.team_away_logo = team_away_logo;
}

public String getTournament_name() {
    return tournament_name;
}

public void setTournament_name(String tournament_name) {
    this.tournament_name = tournament_name;
}
}
</code>```

Cardview for a display of match:

```<code><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tournament_result"    >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:background="@drawable/newsbody_file">

    <TextView
        android:id="@+id/linebelownews"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorNewsPressed" />

    <TextView
        android:id="@+id/match_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linebelownews"
        android:text="22:00" />

    <TextView
        android:id="@+id/match_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:text="ост." />

    <TextView
        android:id="@+id/match_res"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/match_time"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:text="2:2"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/match_th"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/match_time"
        android:layout_marginEnd="5dp"
        android:layout_toStartOf="@+id/logo_th"
        android:text="Динамо"
        android:textAlignment="viewEnd"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/match_ta"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_toEndOf="@+id/logo_ta"
        android:layout_below="@id/match_time"
        android:textColor="#000000"
        android:text="Шахтер" />

    <ImageView
        android:id="@+id/logo_th"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_toStartOf="@id/match_res"
        android:layout_below="@+id/match_time"
        android:contentDescription="logo_th"
        app:srcCompat="@drawable/author_file" />

    <ImageView
        android:id="@+id/logo_ta"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_below="@id/match_time"
        app:srcCompat="@drawable/author_file"
        android:layout_toEndOf="@id/match_res"
        android:layout_marginBottom="5dp"
        android:contentDescription="logo_th" />

    <TextView
        android:id="@+id/tournament_n"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/match_status"
        android:layout_centerHorizontal="true"
        android:text="@string/name_tournament" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</code>```

And main layout with Recyclerview:

```<code><RelativeLayout
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="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tournament_result">

<android.support.v7.widget.RecyclerView
 android:id="@+id/rcMatch1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/lCalendar">
    <Button
        android:id="@+id/arrow_left"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="5dp"
        android:layout_toStartOf="@+id/btnDatepick"
        android:background="@drawable/ic_arrow_left" />
    <Button
        android:id="@+id/arrow_right"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_toEndOf="@+id/btnDatepick"
        android:background="@drawable/ic_arrow_right" />
    <Button
        android:id="@+id/btnDatepick"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:paddingStart="8dp"
        android:paddingEnd="8dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    <Switch
        android:id="@+id/swLive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="16dp" />
</RelativeLayout>

</RelativeLayout>
</code>```

EDIT

Adapter:

```<code>class FootballResultsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ArrayList<FootballResultsData> footballresults_data = new ArrayList<FootballResultsData>();

private static int View_Header = 0;
private static int View_Item = 1;

public FootballResultsAdapter(Context context, ArrayList<FootballResultsData> footballresults_data) {
    this.context = context;
    this.footballresults_data = footballresults_data;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    RecyclerView.ViewHolder holder = null;
    if(viewType == View_Item) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_match, parent, false);
        holder = new ViewHolder_item(view);
    }
    else if(viewType == View_Header) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_tournament, parent, false);
        holder = new ViewHolder_header(view);
    }
    return holder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    FootballResultsData NFD = footballresults_data.get(position);
    if (holder instanceof ViewHolder_item) {
        ((ViewHolder_item) holder).match_time.setText(NFD.getMatch_time());
        ((ViewHolder_item) holder).match_result.setText(NFD.getMatch_result());
        ((ViewHolder_item) holder).team_home.setText(NFD.getTeam_home());
        ((ViewHolder_item) holder).team_away.setText(NFD.getTeam_away());
        ((ViewHolder_item) holder).match_status.setText(NFD.getMatch_status());
        Glide.with(context).load(NFD.getTeam_home_logo()).into(  ((ViewHolder_item) holder).team_home_logo);
        Glide.with(context).load(NFD.getTeam_away_logo()).into(  ((ViewHolder_item) holder).team_away_logo);
    }
    else if (holder instanceof ViewHolder_header) {
        ((ViewHolder_header) holder).tournament_name.setText(NFD.getTournament_name());
    }
}

@Override
public int getItemViewType(int position) {
    super.getItemViewType(position);
    if(position == 0) {
        return View_Header;
    }else  {
        return View_Item;
    }
}

@Override
public int getItemCount() {
    return footballresults_data.size()+1;
}

public static class ViewHolder_item extends RecyclerView.ViewHolder {

    public TextView match_time;
    public TextView match_result;
    public TextView team_home;
    public TextView team_away;
    public TextView match_status;
    public ImageView team_home_logo;
    public ImageView team_away_logo;

    public ViewHolder_item(View itemView) {
        super(itemView);
        match_time = (TextView)itemView.findViewById(R.id.match_time);
        match_result = (TextView)itemView.findViewById(R.id.match_res);
        team_home = (TextView)itemView.findViewById(R.id.match_th);
        team_away = (TextView)itemView.findViewById(R.id.match_ta);
        match_status = (TextView)itemView.findViewById(R.id.match_status);
        team_home_logo = (ImageView)itemView.findViewById(R.id.logo_th);
        team_away_logo = (ImageView)itemView.findViewById(R.id.logo_ta);
    }
}

public static class ViewHolder_header extends RecyclerView.ViewHolder {

    public TextView tournament_name;

    public ViewHolder_header(View itemView) {
        super(itemView);
        tournament_name = (TextView)itemView.findViewById(R.id.tournament_n);
    }
}
}
</code>```

答:
Override getItemViewType (int position) return the appropriate type based on position and then inflate a different layout for header in onCreateViewHolder.

In Adapter

```<code>private static int View_Header =0;
private static int View_Item = 1;
</code>```

Then

```<code>@Override
public int getItemViewType (int position) {
    // position 0 return header type
    if(position == 0) {

        return View_Header;

    }else  {

        return View_Item;
    }

}
</code>```

Then

```<code>// add 1 to the list
// total items is item in list + 1 for header
@Override
public int getItemCount() {
    return footballresults_data.size()+1;
}
</code>```

Then

```<code>@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    RecyclerView.ViewHolder holder = null;
    if(viewType == View_Item) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_match, parent, false);
        holder = new ViewHolder_Item(view);

    }else if(viewType == View_Header) {
         // inflate header layout
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.header_layout, parent, false);
        holder = new ViewHolder_header(view);

    }
 return holder;
 }
</code>```

Then

```<code>@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    if (holder instanceof ViewHolder) {
         // bind row items items

    }
    // create a separate viewholder class for header
    else if( holder instanceof ViewHolder_header){
        // bind header item
    }
</code>```

If you are looking for header and sub items (grouping items under a header) have a look at https://stackoverflow.com/a/42976078/653856. But the logic remains the same

Body:
I create app for sports site and need to make calendar events. There is a detail which I can't understand: how to make headers within Recyclerview for display of tournaments name that not to specified near each game (example "Примера" on the screen).

Is there a library or anyways for my task? I don’t want create many static Recyclerview and find agile ways.

Of course, there are a lot of tournaments in the calendar, so the headers should be the same.

Main class of the calendar:

public class FootballResults extends Fragment implements
View.OnClickListener, DatePickerDialog.OnDateSetListener{

private LinearLayoutManager linLM;
private FootballResultsAdapter adapter;
private ArrayList<FootballResultsData> dl;

String today_day;
String today_month;
String today_year;
String mDay;
String mMonth;
String mYear;

Button arrow_left;
Button arrow_right;
Button datepicker;

Switch swLive;

int n = 0;
//int n_plus = 1;

@SuppressLint("SetTextI18n")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rv = inflater.inflate(R.layout.results_football, container, false);

    RecyclerView footballresults_feed1 = (RecyclerView) rv.findViewById(R.id.rcMatch1);

    dl = new ArrayList<>();

    footballresults_feed1.setLayoutManager(new LinearLayoutManager(getActivity()));
    adapter = new FootballResultsAdapter(getActivity(), dl);
    footballresults_feed1.setAdapter(adapter);

    arrow_left = (Button)rv.findViewById(R.id.arrow_left);
    arrow_right = (Button)rv.findViewById(R.id.arrow_right);
    datepicker = (Button)rv.findViewById(R.id.btnDatepick);
    swLive = (Switch)rv.findViewById(R.id.swLive);

    arrow_left.setOnClickListener(this);
    arrow_right.setOnClickListener(this);

    datepicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            datepickermethod ();
        }
    });

    swLive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {swLive.setText("");}
            else {swLive.setText("");}
        }
    });

    currenttime();
    datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);

    ResultDisplay();

    return rv;
}

private void ResultDisplay() {
    @SuppressLint("StaticFieldLeak") AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {

            ResultFeed ();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            adapter.notifyDataSetChanged();
        }
    };
    task.execute();
}

void ResultFeed (){
    OkHttpClient client = new OkHttpClient();
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(C.RESULT_API+mYear+"/"+mMonth+"/"+mDay+"?sport_id=1")
            .build();
    try {
        okhttp3.Response response = client.newCall(request).execute();
        JSONObject object = new JSONObject(response.body().string());

        dl.clear();
        JSONArray sports = object.getJSONArray("sports");
        JSONObject tournament0 = sports.getJSONObject(0);

        JSONArray tournament = tournament0.getJSONArray("tournaments");
        for (int i=0; i<tournament.length(); i++){
            JSONObject matches1 = tournament.getJSONObject(i);
            Log.i (C.T, "Турнир: "+matches1.getString("tournament_name"));
            JSONArray matches0 = matches1.getJSONArray("matches");
            for (int j=0; j<matches0.length(); j++) {
                JSONObject matches = matches0.getJSONObject(j);

                String match_time = TimeFormat.TimeRadar(matches.getString("date_of_match")); //время начала матча
                String match_res = matches.getString("ft_value");
                String match_status = matches.getString("status");

                if (match_res.equals("null")) {match_res = "-:-";}
                if (match_status.equals("Не начался")) {match_status = "";}
                if (match_status.equals("null")) {match_status = "";}

                JSONObject team_home1 = matches.getJSONObject("team_home");
                String team_home = team_home1.getString("short_name");
                String team_home_logo = team_home1.getString("logo_small");

                JSONObject team_away1 = matches.getJSONObject("team_away");
                String team_away = team_away1.getString("short_name");
                String team_away_logo = team_away1.getString("logo_small");

                FootballResultsData data = new FootballResultsData(matches1.getString("tournament_name"),
                        match_time,
                        match_res,
                        team_home, team_away,
                        match_status,
                        team_home_logo,
                        team_away_logo);
            dl.add(data);
        }}

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

@SuppressLint("SimpleDateFormat")
void currenttime () {
    long date_today = System.currentTimeMillis();
    today_day = new SimpleDateFormat("dd").format(date_today);
    today_month = new SimpleDateFormat("MM").format(date_today);
    today_year = new SimpleDateFormat("yyyy").format(date_today);
    mDay = today_day; mMonth = today_month; mYear = today_year;
}

@SuppressLint("SimpleDateFormat")
void calendar (String dd, String mm, String yyyy, int day_n) {
    String sourceDate = yyyy+"-"+mm+"-"+dd;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date myDate;
    try {
        myDate = format.parse(sourceDate);
        myDate = DateUtil.addDays(myDate, day_n);
        String mDate = new SimpleDateFormat("dd MM yyyy").format(new SimpleDateFormat("EEE MMM dd kk:mm:ss zzzz yyyy").parse(myDate.toString()));
        mDay = new SimpleDateFormat("dd").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
        mMonth = new SimpleDateFormat("MM").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
        mYear = new SimpleDateFormat("yyyy").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
        Log.i(C.T, mDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
    //currenttime ();
    switch (v.getId()) {
        case R.id.arrow_left: {n=n-1; break;}
        case R.id.arrow_right: {n=n+1; break;}
        default: break;
    }
    calendar(today_day, today_month, today_year, n);
    datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
    ResultDisplay();
}

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

}

void datepickermethod () {
    DatePickerDialog datepick = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
    @SuppressLint("SetTextI18n")
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        datepicker.setText(dayOfMonth+" "+TimeFormat.monthDef(month+1)+" "+year);
        mDay = String.valueOf(dayOfMonth); mMonth = String.valueOf(month+1); mYear = String.valueOf(year);
        n=0;
        today_day = String.valueOf(dayOfMonth); today_month = String.valueOf(month+1); today_year = String.valueOf(year);
        ResultDisplay();
    }
        }, Integer.parseInt(today_year), Integer.parseInt(today_month)-1, Integer.parseInt(today_day));
    datepick.show();
}
}

For setters and getters:

class FootballResultsData {

public FootballResultsData(String tournament_name, String match_time, String match_result, String team_home, String team_away, String match_status, String team_home_logo, String team_away_logo) {
    this.setTournament_name(tournament_name);
    this.setMatch_time(match_time);
    this.setMatch_result(match_result);
    this.setTeam_home(team_home);
    this.setTeam_away(team_away);
    this.setMatch_status(match_status);
    this.setTeam_home_logo(team_home_logo);
    this.setTeam_away_logo(team_away_logo);
}

private String tournament_name;
private String match_time;
private String match_result;
private String team_home;
private String team_away;
private String match_status;
private String team_home_logo;
private String team_away_logo;

public String getMatch_time() { return match_time; }

public void setMatch_time(String match_time) {
    this.match_time = match_time;
}

public String getTeam_home() {
    return team_home;
}

public void setTeam_home(String team_home) {
    this.team_home = team_home;
}

public String getTeam_away() {
    return team_away;
}

public void setTeam_away(String team_away) {
    this.team_away = team_away;
}

public String getMatch_status() {
    return match_status;
}

public void setMatch_status(String match_status) {
    this.match_status = match_status;
}

public String getMatch_result() { return match_result; }

public void setMatch_result(String match_result) { this.match_result = match_result; }

public String getTeam_home_logo() {
    return team_home_logo;
}

public void setTeam_home_logo(String team_home_logo) {
    this.team_home_logo = team_home_logo;
}

public String getTeam_away_logo() {
    return team_away_logo;
}

public void setTeam_away_logo(String team_away_logo) {
    this.team_away_logo = team_away_logo;
}

public String getTournament_name() {
    return tournament_name;
}

public void setTournament_name(String tournament_name) {
    this.tournament_name = tournament_name;
}
}

Cardview for a display of match:

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tournament_result"    >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:background="@drawable/newsbody_file">

    <TextView
        android:id="@+id/linebelownews"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorNewsPressed" />

    <TextView
        android:id="@+id/match_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linebelownews"
        android:text="22:00" />

    <TextView
        android:id="@+id/match_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:text="ост." />

    <TextView
        android:id="@+id/match_res"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/match_time"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:text="2:2"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/match_th"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/match_time"
        android:layout_marginEnd="5dp"
        android:layout_toStartOf="@+id/logo_th"
        android:text="Динамо"
        android:textAlignment="viewEnd"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/match_ta"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_toEndOf="@+id/logo_ta"
        android:layout_below="@id/match_time"
        android:textColor="#000000"
        android:text="Шахтер" />

    <ImageView
        android:id="@+id/logo_th"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_toStartOf="@id/match_res"
        android:layout_below="@+id/match_time"
        android:contentDescription="logo_th"
        app:srcCompat="@drawable/author_file" />

    <ImageView
        android:id="@+id/logo_ta"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_below="@id/match_time"
        app:srcCompat="@drawable/author_file"
        android:layout_toEndOf="@id/match_res"
        android:layout_marginBottom="5dp"
        android:contentDescription="logo_th" />

    <TextView
        android:id="@+id/tournament_n"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/match_status"
        android:layout_centerHorizontal="true"
        android:text="@string/name_tournament" />
</RelativeLayout>
</android.support.v7.widget.CardView>

And main layout with Recyclerview:

<RelativeLayout
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="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tournament_result">

<android.support.v7.widget.RecyclerView
 android:id="@+id/rcMatch1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/lCalendar">
    <Button
        android:id="@+id/arrow_left"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="5dp"
        android:layout_toStartOf="@+id/btnDatepick"
        android:background="@drawable/ic_arrow_left" />
    <Button
        android:id="@+id/arrow_right"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_toEndOf="@+id/btnDatepick"
        android:background="@drawable/ic_arrow_right" />
    <Button
        android:id="@+id/btnDatepick"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:paddingStart="8dp"
        android:paddingEnd="8dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    <Switch
        android:id="@+id/swLive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="16dp" />
</RelativeLayout>

</RelativeLayout>

EDIT

Adapter:

class FootballResultsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ArrayList<FootballResultsData> footballresults_data = new ArrayList<FootballResultsData>();

private static int View_Header = 0;
private static int View_Item = 1;

public FootballResultsAdapter(Context context, ArrayList<FootballResultsData> footballresults_data) {
    this.context = context;
    this.footballresults_data = footballresults_data;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    RecyclerView.ViewHolder holder = null;
    if(viewType == View_Item) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_match, parent, false);
        holder = new ViewHolder_item(view);
    }
    else if(viewType == View_Header) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_tournament, parent, false);
        holder = new ViewHolder_header(view);
    }
    return holder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    FootballResultsData NFD = footballresults_data.get(position);
    if (holder instanceof ViewHolder_item) {
        ((ViewHolder_item) holder).match_time.setText(NFD.getMatch_time());
        ((ViewHolder_item) holder).match_result.setText(NFD.getMatch_result());
        ((ViewHolder_item) holder).team_home.setText(NFD.getTeam_home());
        ((ViewHolder_item) holder).team_away.setText(NFD.getTeam_away());
        ((ViewHolder_item) holder).match_status.setText(NFD.getMatch_status());
        Glide.with(context).load(NFD.getTeam_home_logo()).into(  ((ViewHolder_item) holder).team_home_logo);
        Glide.with(context).load(NFD.getTeam_away_logo()).into(  ((ViewHolder_item) holder).team_away_logo);
    }
    else if (holder instanceof ViewHolder_header) {
        ((ViewHolder_header) holder).tournament_name.setText(NFD.getTournament_name());
    }
}

@Override
public int getItemViewType(int position) {
    super.getItemViewType(position);
    if(position == 0) {
        return View_Header;
    }else  {
        return View_Item;
    }
}

@Override
public int getItemCount() {
    return footballresults_data.size()+1;
}

public static class ViewHolder_item extends RecyclerView.ViewHolder {

    public TextView match_time;
    public TextView match_result;
    public TextView team_home;
    public TextView team_away;
    public TextView match_status;
    public ImageView team_home_logo;
    public ImageView team_away_logo;

    public ViewHolder_item(View itemView) {
        super(itemView);
        match_time = (TextView)itemView.findViewById(R.id.match_time);
        match_result = (TextView)itemView.findViewById(R.id.match_res);
        team_home = (TextView)itemView.findViewById(R.id.match_th);
        team_away = (TextView)itemView.findViewById(R.id.match_ta);
        match_status = (TextView)itemView.findViewById(R.id.match_status);
        team_home_logo = (ImageView)itemView.findViewById(R.id.logo_th);
        team_away_logo = (ImageView)itemView.findViewById(R.id.logo_ta);
    }
}

public static class ViewHolder_header extends RecyclerView.ViewHolder {

    public TextView tournament_name;

    public ViewHolder_header(View itemView) {
        super(itemView);
        tournament_name = (TextView)itemView.findViewById(R.id.tournament_n);
    }
}
}

Body:
Override getItemViewType (int position) return the appropriate type based on position and then inflate a different layout for header in onCreateViewHolder.

In Adapter

private static int View_Header =0;
private static int View_Item = 1;

Then

@Override
public int getItemViewType (int position) {
    // position 0 return header type
    if(position == 0) {

        return View_Header;

    }else  {

        return View_Item;
    }

}

Then

// add 1 to the list
// total items is item in list + 1 for header
@Override
public int getItemCount() {
    return footballresults_data.size()+1;
}

Then

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    RecyclerView.ViewHolder holder = null;
    if(viewType == View_Item) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_match, parent, false);
        holder = new ViewHolder_Item(view);

    }else if(viewType == View_Header) {
         // inflate header layout
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.header_layout, parent, false);
        holder = new ViewHolder_header(view);

    }
 return holder;
 }

Then

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    if (holder instanceof ViewHolder) {
         // bind row items items

    }
    // create a separate viewholder class for header
    else if( holder instanceof ViewHolder_header){
        // bind header item
    }

If you are looking for header and sub items (grouping items under a header) have a look at https://stackoverflow.com/a/42976078/653856. But the logic remains the same


来源: stackexchange

问:
How do I pad an IP address' octets and turn it into a unique int id in an Ansible playbook?
Given an IP address like 127.0.0.1 (as a string), I want to drop the dots, pad each octet (ideally except for the first one) with zeros to a length of three digits and turn the result into an integer, e.g. 127000000001. (Although I'm assuming that leading zeros would be dropped when converting from string to integer anyway.)

How do I go about doing that in Ansible?
I have the ip defined as ip: "127.0.0.1"

The octets can be obtained with octets: "{{ ip.split('.')}}"

I have found a post that shows how to format strings: {{'%03d'|format(item|int) }}

And I can join a list to a string using result: modified_octets.join()

What I'm struggling with is how to bring all that together. I know I can loop over the octets with an with_items: octets, and could thus apply the format to each item. But how would I join the result together into a list of items (i.e. modified_octets) again? (If I assign item to a variable using the register module, I'll only get the last octet's value; previous ones will be overridden by it...)

Update: It's not important whether I get a string or an int back, really, as long as the return value looks like an integer (i.e. no leading zeroes, no dots, numbers only, etc.)

答:
AFAIK you can't get int out of {{ ... }} expression because of how Ansible's templator works. You can test it with:

```<code>- name: 'this will print "int"'
  debug:
    msg: '{{ "1" | int | type_debug }}'
- name: 'this will print "1", but not 1'
  debug:
    msg: '{{ "1" | int }}'
</code>```

If string id is still make sense to you, try this:

```<code>- set_fact:
    ip_id: "{% for i in my_ip.split('.') %}\
            {{ '%03d' | format(i|int) }}\
            {% endfor %}"
  vars:
    my_ip: 10.20.30.40
</code>```

ContentLicense: CC BY-SA 3.0

Body:
AFAIK you can't get int out of {{ ... }} expression because of how Ansible's templator works. You can test it with:

- name: 'this will print "int"'
  debug:
    msg: '{{ "1" | int | type_debug }}'
- name: 'this will print "1", but not 1'
  debug:
    msg: '{{ "1" | int }}'

If string id is still make sense to you, try this:

- set_fact:
    ip_id: "{% for i in my_ip.split('.') %}\
            {{ '%03d' | format(i|int) }}\
            {% endfor %}"
  vars:
    my_ip: 10.20.30.40


问:
Checking if checkbox is checked, display both booleans
I am trying to determine whether the checkbox is checked or not, but when I push the checkbox, the javascript displays:

```<code>false
true
</code>```

And when I push it again it changes to

```<code>true
false
</code>```

And then it continues as I push further...

How can I only display one of those?

Here is my javascript code:

```<code>function selected() {
  const bg = document.getElementById("myCheck").checked;

  console.log(bg);

  if (bg == 'true') {
    document.getElementById("changeBG").style.backgroundColor = 'red';
  } else {
    document.getElementById("changeBG").style.backgroundColor = 'green';
  }
}
</code>```

答:
This is incorrect:

```<code>if (bg == 'true') {
</code>```

The checked property gives you a boolean, not a string. true is a string.

Just use:

```<code>if (bg) {
</code>```

Body:
I am trying to determine whether the checkbox is checked or not, but when I push the checkbox, the javascript displays:

false
true

And when I push it again it changes to

true
false

And then it continues as I push further...

How can I only display one of those?

Here is my javascript code:

function selected() {
  const bg = document.getElementById("myCheck").checked;

  console.log(bg);

  if (bg == 'true') {
    document.getElementById("changeBG").style.backgroundColor = 'red';
  } else {
    document.getElementById("changeBG").style.backgroundColor = 'green';
  }
}

Body:
This is incorrect:

if (bg == 'true') {

The checked property gives you a boolean, not a string. true is a string.

Just use:

if (bg) {


问:
How do I check if a directory exists or not in a Bash shell script?
What command checks if a directory exists or not within a Bash shell script?</p>

答:
Have you considered just doing whatever you want to do in the if rather than looking before you leap?

I.e., if you want to check for the existence of a directory before you enter it, try just doing this:

```<code>if pushd /path/you/want/to/enter; then
    # Commands you want to run in this directory
    popd
fi
</code>```

If the path you give to pushd exists, you'll enter it and it'll exit with 0, which means the then portion of the statement will execute. If it doesn't exist, nothing will happen (other than some output saying the directory doesn't exist, which is probably a helpful side-effect anyways for debugging).

It seems better than this, which requires repeating yourself:

```<code>if [ -d /path/you/want/to/enter ]; then
    pushd /path/you/want/to/enter
    # Commands you want to run in this directory
    popd
fi
</code>```

The same thing works with cd, mv, rm, etc... if you try them on files that don't exist, they'll exit with an error and print a message saying it doesn't exist, and your then block will be skipped. If you try them on files that do exist, the command will execute and exit with a status of 0, allowing your then block to execute.

OwnerDisplayName: Grundlefleck

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Grundlefleck

Body:
Have you considered just doing whatever you want to do in the if rather than looking before you leap?

I.e., if you want to check for the existence of a directory before you enter it, try just doing this:

if pushd /path/you/want/to/enter; then
    # Commands you want to run in this directory
    popd
fi

If the path you give to pushd exists, you'll enter it and it'll exit with 0, which means the then portion of the statement will execute. If it doesn't exist, nothing will happen (other than some output saying the directory doesn't exist, which is probably a helpful side-effect anyways for debugging).

It seems better than this, which requires repeating yourself:

if [ -d /path/you/want/to/enter ]; then
    pushd /path/you/want/to/enter
    # Commands you want to run in this directory
    popd
fi

The same thing works with cd, mv, rm, etc... if you try them on files that don't exist, they'll exit with an error and print a message saying it doesn't exist, and your then block will be skipped. If you try them on files that do exist, the command will execute and exit with a status of 0, allowing your then block to execute.


问:
Netlogo: How to assign a value to a variable from an existing (string) list
I have a problem as I am trying to a assign a location to a (franchisee) supermarket. I have a list per supermarket brand, which has cities that are repeated as many times as the amount of outlets that supermarket brand has in the given city.

However, with the code I've been using, I cannot get to assign the exact amount of cities I have in my list, it is randomly changing every time.

```<code>;to create coop franchisees
  create-Fs 32 [
    set HQ-brand "Coop"
    set fcoop-location-outlet ["Zuidlaren" "Zuidlaren" "Nijmegen"   "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Ba neveld" "Barneveld" "Doetinchem"    "Doetinchem"    "Doetinchem"    "Zutphen"   "Huissen" "Amstelveen" "Amstelveen" "Amstelveen"    "Zwolle"    "Zwolle" "Rotterdam" "Rotterdam" "Rotterdam"    "Rotterdam" "Rotterdam" "Rotterdam" "Rotterdam" "Rotterdam"]
]
</code>```

once I have the list above, I have tried the following, to assign a city outlet to each franchisee (per brand)

trial 1

```<code>ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [ set location-outlet one-of fcoop-location-outlet ]
</code>```

trial 2

```<code>ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [ foreach fcoop-location-outlet [set location-outlet one-of fcoop-location-outlet] ]
</code>```

trial 3

```<code>ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [ set location-outlet n-of 32 fcoop-location-outlet ]
</code>```

I thought that with one-of I would assign one item of the Coop location list to each one of my 32 Coop outlets, but it is random. With the n-of it didn't work and I thought that maybe foreach would work, but it is the same as with the one-of the way I am coding it.

How can I code this so that every time I will have all the items of the list with the cities assigned to one of my Coop outlets? There must be a simple way to do this, but I have been googling it and can't figure it out.

(I am doing this for 8 other supermarkets).

答:
I found a way! A friend helped me with this

so, first the list that has all the locations of the outlets:

```<code>fcoop-location-outlet
</code>```

has to be made a global instead of a variable of each outlet.

Then, the code should look like this:

```<code>ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [
 set location-outlet item 0 fcoop-location-outlet
 set fcoop-location-outlet remove-item 0 fcoop-location-outlet
]
</code>```

In that way, the item (location) that is added to the location-outlet variable, is deleted from the main list, so it does not get repeated.

Body:
I have a problem as I am trying to a assign a location to a (franchisee) supermarket. I have a list per supermarket brand, which has cities that are repeated as many times as the amount of outlets that supermarket brand has in the given city.

However, with the code I've been using, I cannot get to assign the exact amount of cities I have in my list, it is randomly changing every time.

;to create coop franchisees
  create-Fs 32 [
    set HQ-brand "Coop"
    set fcoop-location-outlet ["Zuidlaren" "Zuidlaren" "Nijmegen"   "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Nijmegen"  "Ba neveld" "Barneveld" "Doetinchem"    "Doetinchem"    "Doetinchem"    "Zutphen"   "Huissen" "Amstelveen" "Amstelveen" "Amstelveen"    "Zwolle"    "Zwolle" "Rotterdam" "Rotterdam" "Rotterdam"    "Rotterdam" "Rotterdam" "Rotterdam" "Rotterdam" "Rotterdam"]
]

once I have the list above, I have tried the following, to assign a city outlet to each franchisee (per brand)

trial 1

ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [ set location-outlet one-of fcoop-location-outlet ]

trial 2

ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [ foreach fcoop-location-outlet [set location-outlet one-of fcoop-location-outlet] ]

trial 3

ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [ set location-outlet n-of 32 fcoop-location-outlet ]

I thought that with one-of I would assign one item of the Coop location list to each one of my 32 Coop outlets, but it is random. With the n-of it didn't work and I thought that maybe foreach would work, but it is the same as with the one-of the way I am coding it.

How can I code this so that every time I will have all the items of the list with the cities assigned to one of my Coop outlets? There must be a simple way to do this, but I have been googling it and can't figure it out.

(I am doing this for 8 other supermarkets).

Body:
I found a way! A friend helped me with this

so, first the list that has all the locations of the outlets:

fcoop-location-outlet

has to be made a global instead of a variable of each outlet.

Then, the code should look like this:

ask Fs with [(HQ-brand = "Coop") and (location-outlet = 0)] [
 set location-outlet item 0 fcoop-location-outlet
 set fcoop-location-outlet remove-item 0 fcoop-location-outlet
]

In that way, the item (location) that is added to the location-outlet variable, is deleted from the main list, so it does not get repeated.


问:
Rows more narrow than the UITableView itself
How can I create a UITableView with grouped style such that the cells are a different width than the table view is?

For instance, the table view is width 768 (iPad width) but I want the cells to be only 500 wide.

答:
What middaparka said in his comment, with the parent view the same background color as the uitableview:</p>

```<code>myTableView.superview.backgroundColor = myTableView.backgroundColor;
// Not tested, should work though.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What middaparka said in his comment, with the parent view the same background color as the uitableview:

myTableView.superview.backgroundColor = myTableView.backgroundColor;
// Not tested, should work though.


问:
constructor() and super () react
I am learning from scratch react jsx. I have no previous learning of java or html language.

I've been searching what is it for the constructor() and super(). This are components? Anyone can explain me everything about this 2 things.

答: If you are new to Javascript diving straight into a framework probably isn't a good idea. I would recommend using the classes on codecademy to get a basic understanding of how Javascript works, then you can either do the React classes or go and try to learn it yourself, but you should definitely do the javascript class just to learn the basic language features.</p>

Title: constructor() and super () react


问:
Gather boolean from repeating table
I'm having trouble finding the best way to achieve this. I'd like to solve it with just a select query if possible, but I'm not sure if it is solvable by just a select.

Customer Repeating Table:

- customer_id (PK)

- year (PK)

- code1

- code2

This is a repeating table, so a customer has multiple entries with their id number for the same year.

I need to some how gather a boolean or SELECT 'Y' to use as a flag where:

```<code>WHERE customer_id  = '1001'
AND year = '2017'
AND...
</code>```

If there is any case for this customer for each of there code2

where (sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%')) then I need to return TRUE or 'Y'

Example Table

```<code>id      year    code1   code2

1001    2017    RE      AB
1001    2017    D2      AB
1001    2017    RW      BC
</code>```

So here, it would return TRUE because for code2 that are AB,

```<code>sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%') = TRUE
</code>```

I need to compare the sum of the code1's for all the different code2's that a customer has.

答:
I believe this is what you need. I created more test data in the WITH clause (which is only for testing, you don't need it for your actual data). I changed the column name from yr to year since year is an Oracle keyword, which shouldn't be used as table or column name.

I create an initial flag, FLAG1, for each code2 value - used to then compute the final flag, FLAG2, for each (id, yr) combination. In my query I show both flags, just so you can see how this works; you probably need only FLAG2.

And it is not really clear what output you require; I assumed you just wanted an additional flag to complement the input data. If you need something else, perhaps you can adapt it yourself. If you need to add a specific id and specific year, you can do so by adding a WHERE clause to the subquery (in which case you can clean up the analytic functions by removing id and yr from the PARTITION BY clause).

```<code>with
  inputs ( id, yr, code1, code2 ) as (
    select 1001, 2017, 'RE', 'AB' from dual union all
    select 1001, 2017, 'D2', 'AB' from dual union all
    select 1001, 2017, 'RW', 'BC' from dual union all
    select 1004, 2015, 'RE', 'ZZ' from dual union all
    select 1004, 2015, 'DW', 'XX' from dual union all
    select 1004, 2016, 'RX', 'ZZ' from dual
  )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins below this line. Use your actual table and column names.
select id, yr, code1, code2, flag1,
       case count(case flag1 when 'FALSE' then 1 end)
                                            over (partition by id, yr)
            when 0 then 'TRUE' else 'FALSE' end as flag2
from   (
         select id, yr, code1, code2,
                case when count(case when code1 like 'D%' then 1 end)
                                            over (partition by id, yr, code2)
                          <=
                          count(case when code1 like 'R%' then 1 end)
                                            over (partition by id, yr, code2)
                     then 'TRUE' else 'FALSE' end as flag1
         from   inputs
       )
;

        ID         YR CODE1 CODE2 FLAG1 FLAG2
---------- ---------- ----- ----- ----- -----
      1001       2017 RE    AB    TRUE  TRUE
      1001       2017 D2    AB    TRUE  TRUE
      1001       2017 RW    BC    TRUE  TRUE
      1004       2015 DW    XX    FALSE FALSE
      1004       2015 RE    ZZ    TRUE  FALSE
      1004       2016 RX    ZZ    TRUE  TRUE
</code>```

Title: Gather boolean from repeating table

Body:
I'm having trouble finding the best way to achieve this. I'd like to solve it with just a select query if possible, but I'm not sure if it is solvable by just a select.

Customer Repeating Table:

- customer_id (PK)

- year (PK)

- code1

- code2

This is a repeating table, so a customer has multiple entries with their id number for the same year.

I need to some how gather a boolean or SELECT 'Y' to use as a flag where:

WHERE customer_id  = '1001'
AND year = '2017'
AND...

If there is any case for this customer for each of there code2

where (sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%')) then I need to return TRUE or 'Y'

Example Table

id      year    code1   code2

1001    2017    RE      AB
1001    2017    D2      AB
1001    2017    RW      BC

So here, it would return TRUE because for code2 that are AB,

sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%') = TRUE

I need to compare the sum of the code1's for all the different code2's that a customer has.

Body:
I believe this is what you need. I created more test data in the WITH clause (which is only for testing, you don't need it for your actual data). I changed the column name from yr to year since year is an Oracle keyword, which shouldn't be used as table or column name.

I create an initial flag, FLAG1, for each code2 value - used to then compute the final flag, FLAG2, for each (id, yr) combination. In my query I show both flags, just so you can see how this works; you probably need only FLAG2.

And it is not really clear what output you require; I assumed you just wanted an additional flag to complement the input data. If you need something else, perhaps you can adapt it yourself. If you need to add a specific id and specific year, you can do so by adding a WHERE clause to the subquery (in which case you can clean up the analytic functions by removing id and yr from the PARTITION BY clause).

with
  inputs ( id, yr, code1, code2 ) as (
    select 1001, 2017, 'RE', 'AB' from dual union all
    select 1001, 2017, 'D2', 'AB' from dual union all
    select 1001, 2017, 'RW', 'BC' from dual union all
    select 1004, 2015, 'RE', 'ZZ' from dual union all
    select 1004, 2015, 'DW', 'XX' from dual union all
    select 1004, 2016, 'RX', 'ZZ' from dual
  )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins below this line. Use your actual table and column names.
select id, yr, code1, code2, flag1,
       case count(case flag1 when 'FALSE' then 1 end)
                                            over (partition by id, yr)
            when 0 then 'TRUE' else 'FALSE' end as flag2
from   (
         select id, yr, code1, code2,
                case when count(case when code1 like 'D%' then 1 end)
                                            over (partition by id, yr, code2)
                          <=
                          count(case when code1 like 'R%' then 1 end)
                                            over (partition by id, yr, code2)
                     then 'TRUE' else 'FALSE' end as flag1
         from   inputs
       )
;

        ID         YR CODE1 CODE2 FLAG1 FLAG2
---------- ---------- ----- ----- ----- -----
      1001       2017 RE    AB    TRUE  TRUE
      1001       2017 D2    AB    TRUE  TRUE
      1001       2017 RW    BC    TRUE  TRUE
      1004       2015 DW    XX    FALSE FALSE
      1004       2015 RE    ZZ    TRUE  FALSE
      1004       2016 RX    ZZ    TRUE  TRUE


问:
How to use SpriteBatch and ShapeRenderer in one screen?
I'm using SpriteBatch to draw textures and ShapeRenderer to draw some shape.

Here is my code in an actor

```<code>@Override
public void draw(Batch batch, float parentAlpha) {
    batch.end();
    Gdx.gl.glEnable(GL20.GL_ARRAY_BUFFER_BINDING);
    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    shapeRenderer.begin(ShapeType.Filled);

    //change color

    shapeRenderer.setColor(color);

    shapeRenderer.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);

    shapeRenderer.end();
    Gdx.gl.glDisable(GL20.GL_BLEND);
    batch.begin();
}
</code>```

and call stage.draw() on the screen

```<code>@Override
public void render(float delta) {
    Gdx.gl20.glClearColor(0, 0, 0, 0);
    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
    Gdx.gl20.glEnable(GL20.GL_TEXTURE_2D);
    stage.act(delta);
    stage.draw();
    //......
}
</code>```

It's working but unpredictably throw exception:

```<code>STACK_TRACE=java.lang.IllegalStateException: SpriteBatch.end must be called before begin.
at com.badlogic.gdx.graphics.g2d.SpriteBatch.begin(SpriteBatch.java:164)
at com.badlogic.gdx.scenes.scene2d.Stage.draw(Stage.java:127)
at c.i.a.a(AbstractCardRoomRenderer.java:3078)
at c.i.s.a(TLMNCardRoomRenderer.java:1158)
at c.j.e.render(GameScreen.java:22)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:422)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1522)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1239)
</code>```

EDIT: For more details what I'm doing:

What I want is to draw a shape. Because the stage's batch is drawing so I have to end it for shape drawing. My code still work but sometime, another actor, I think, use stage's batch to draw something else. It make the stage begin its batch. So it conflict between begin and end.

For example, the actor draw method:

```<code>batch.end();
//drawing shapes

         batch.begin() (somewhere else) <--- I think this code is call when stage call draw on other actor

 //drawing completed
 batch.begin()
</code>```

EDIT:
If others' answer not suit you, please consider my workaround I post as an answer below.

答:
I know this is my old question but I can see there are still new people using libgdx facing this error too. So I post my workaround as an answer:

The problem is that there is something break in between

```<code>batch.begin()
</code>```

and

```<code>batch.end()
</code>```

when the stage drawing

so if you use Stage to manage the batch, try-catch can save your time:

```<code>@Override
public void render(float delta) {
    try {
        stage.act(delta)
        stage.draw()
    } catch (Exception ex) {
        if(stage.batch.isDrawing)
            stage.batch.end()
    }
}
</code>```

** This is just a workaround to bypass some accidental error (e.g glyphlayout) in a frame and it should work fine in next frame. If there is any real problem in your code or resources, your render code will end up in the catch{}

Body:
I'm using SpriteBatch to draw textures and ShapeRenderer to draw some shape.

Here is my code in an actor

@Override
public void draw(Batch batch, float parentAlpha) {
    batch.end();
    Gdx.gl.glEnable(GL20.GL_ARRAY_BUFFER_BINDING);
    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    shapeRenderer.begin(ShapeType.Filled);

    //change color

    shapeRenderer.setColor(color);

    shapeRenderer.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);

    shapeRenderer.end();
    Gdx.gl.glDisable(GL20.GL_BLEND);
    batch.begin();
}

and call stage.draw() on the screen

@Override
public void render(float delta) {
    Gdx.gl20.glClearColor(0, 0, 0, 0);
    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
    Gdx.gl20.glEnable(GL20.GL_TEXTURE_2D);
    stage.act(delta);
    stage.draw();
    //......
}

It's working but unpredictably throw exception:

STACK_TRACE=java.lang.IllegalStateException: SpriteBatch.end must be called before begin.
at com.badlogic.gdx.graphics.g2d.SpriteBatch.begin(SpriteBatch.java:164)
at com.badlogic.gdx.scenes.scene2d.Stage.draw(Stage.java:127)
at c.i.a.a(AbstractCardRoomRenderer.java:3078)
at c.i.s.a(TLMNCardRoomRenderer.java:1158)
at c.j.e.render(GameScreen.java:22)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:422)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1522)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1239)

EDIT: For more details what I'm doing:

What I want is to draw a shape. Because the stage's batch is drawing so I have to end it for shape drawing. My code still work but sometime, another actor, I think, use stage's batch to draw something else. It make the stage begin its batch. So it conflict between begin and end.

For example, the actor draw method:

batch.end();
//drawing shapes

         batch.begin() (somewhere else) <--- I think this code is call when stage call draw on other actor

 //drawing completed
 batch.begin()

EDIT:
If others' answer not suit you, please consider my workaround I post as an answer below.

Body:
I know this is my old question but I can see there are still new people using libgdx facing this error too. So I post my workaround as an answer:

The problem is that there is something break in between

batch.begin()

and

batch.end()

when the stage drawing

so if you use Stage to manage the batch, try-catch can save your time:

@Override
public void render(float delta) {
    try {
        stage.act(delta)
        stage.draw()
    } catch (Exception ex) {
        if(stage.batch.isDrawing)
            stage.batch.end()
    }
}

** This is just a workaround to bypass some accidental error (e.g glyphlayout) in a frame and it should work fine in next frame. If there is any real problem in your code or resources, your render code will end up in the catch{}


问:
Setting masked corners in Interface Builder
What type of value is [.layerMaxXMinYCorner, .layerMinXMinYCorner]? Is it possible to set this parameter on a View in Interface Builder? I know how to set layer.borderWidth, layer.borderUIColor and layer.cornerRadius in the Identity Inspector, but I can't figure out the right Type and Value to use for masked corners.

Thanks!

Jake

Update: here are the integer values for each combination (in terms of which are rounded):

0: no rounded corners

1: top left

2: top right

3: top left & right (both top corners)

4: bottom left

5: top & bottom left (both left corners)

6: top right & bottom left

7: top left & right, bottom left (all corners except bottom right)

8: bottom right

9: top left, bottom right

10: top & bottom right (both right corners)

11: both top corners, bottom right (all corners except bottom left)

12: bottom left & right (both bottom corners)

13: bottom left & right, top left (all corners except top right)

14: bottom left & right, top right (all corners except top left)

15: all corners rounded

Top left is in 1, 3, 5, 7, 9, 11, 13, 15

Top right is in 2-3, 6-7, 10-11, 14-15

Bottom left is in 4-7, 12-15

Bottom right is in 8-15

Both top corners are in 3, 7, 11, 15

Both right corners are in 10-11, 14,15

Both bottom corners are in 12-15

Both left corners are in 5, 7, 13, 15

答:
maskedCorners is a CACornerMask, which is an OptionSet, or bit mask. The raw value is an integer: in code, you can try printing the value of someView.layer.maskedCorners.rawValue, or setting it via someView.layer.maskedCorners.setValue(3, forKey: "maskedCorners").

So you should be able to set the value of layer.maskedCorners to the integer 3 (or whatever you need) in Interface Builder, and I don't see why it would be unsafe to do this. Though it will be a pain to figure out what set of corners that integer value actually maps to if you forget.


问:
codeigniter will not show info from database
Hello all i have a problem that my information is not being sendt to my view file.

it says: Message: Undefined variable: queryWall

my controller is this

```<code>function wallShow()
 {
  $this->load->model('profil_model');
  $data['queryWall'] = $this->profil_model->wallGet($this->uri->segment(3));

  $data['content'] = 'profil_view';
  $this->load->view('includes/template', $data);
 }
</code>```

my model:

```<code>function wallGet($name)
 {
  $this->db->select('profileName', 'wallComment');
  $this->db->where('profileName', $name);
  $queryWall = $this->db->get('profileWall');

  if($queryWall->num_rows() > 0)
  {
   return $queryWall->result();
  } else {
   return false;
  }
 }
</code>```

and my view file

```<code> <?php
 if(!isset($queryWall)):
  foreach ($queryWall as $wall):
   echo $wall->wallComment;
  endforeach;
 endif;
 ?>
</code>```

答:
Even if everything is fine, you'll keep getting this error since you are using the queryWall variable whenever it's NOT defined!

```<code>if(!isset($queryWall))
</code>```

It should be:

```<code>if(isset($queryWall))
</code>```

But since you are passing the conditional check, then I suppose you have something wrong with your model OR URI segment.

Body:
Hello all i have a problem that my information is not being sendt to my view file.

it says: Message: Undefined variable: queryWall

my controller is this

function wallShow()
 {
  $this->load->model('profil_model');
  $data['queryWall'] = $this->profil_model->wallGet($this->uri->segment(3));

  $data['content'] = 'profil_view';
  $this->load->view('includes/template', $data);
 }

my model:

function wallGet($name)
 {
  $this->db->select('profileName', 'wallComment');
  $this->db->where('profileName', $name);
  $queryWall = $this->db->get('profileWall');

  if($queryWall->num_rows() > 0)
  {
   return $queryWall->result();
  } else {
   return false;
  }
 }

and my view file

 <?php
 if(!isset($queryWall)):
  foreach ($queryWall as $wall):
   echo $wall->wallComment;
  endforeach;
 endif;
 ?>

Body:
Even if everything is fine, you'll keep getting this error since you are using the queryWall variable whenever it's NOT defined!

if(!isset($queryWall))

It should be:

if(isset($queryWall))

But since you are passing the conditional check, then I suppose you have something wrong with your model OR URI segment.


问:
Http proxy in Netty websocket client to connect to internet
My application is running behind a corporate firewall and I need to use http proxy(http://theclientproxy.net:8080) to connect to internet

I have used the Netty client as below,
https://github.com/netty/netty/tree/4.1/example/src/main/java/io/netty/example/http/websocketx/client

Code:

```<code>    public final class WebSocketClient {

        static final String URL = System.getProperty("url", "wss://127.0.0.1:8080/websocket");

        public static void main(String[] args) throws Exception {
            URI uri = new URI(URL);
            String scheme = uri.getScheme() == null? "ws" : uri.getScheme();
            final String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
            final int port;
    final boolean ssl = "wss".equalsIgnoreCase(scheme);
            final SslContext sslCtx;
            if (ssl) {
                sslCtx = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
            } else {
                sslCtx = null;
            }

            EventLoopGroup group = new NioEventLoopGroup();
            try {
        final WebSocketClientHandler handler =
                            new WebSocketClientHandler(
                                    WebSocketClientHandshakerFactory.newHandshaker(
                                            uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));

                    Bootstrap b = new Bootstrap();
                    b.group(group)
                     .channel(NioSocketChannel.class)
                     .handler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel ch) {
                             ChannelPipeline p = ch.pipeline();
                             if (sslCtx != null) {
                                 p.addFirst(new HttpProxyHandler(new InetSocketAddress("theclientproxy.net", 8080) ) );
                                 p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                             }
                             p.addLast(
                                     new HttpClientCodec(),
                                     new HttpObjectAggregator(8192),
                                     WebSocketClientCompressionHandler.INSTANCE,
                                     handler);
                         }
                     });

                    Channel ch = b.connect(uri.getHost(), port).sync().channel();
                    handler.handshakeFuture().sync();

BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine(); //THIS IS NULL IN DATA CENTER LOGS
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                    ch.writeAndFlush(frame);
                } else {
                    WebSocketFrame frame = new TextWebSocketFrame(msg);
                    ch.writeAndFlush(frame);
                }
            }
        } finally {
            group.shutdownGracefully();
        }
</code>```

Handler:

```<code>public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    private final WebSocketClientHandshaker handshaker;
    private ChannelPromise handshakeFuture;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshaker.handshake(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("WebSocket Client disconnected!");
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            try {
                handshaker.finishHandshake(ch, (FullHttpResponse) msg);
                System.out.println("WebSocket Client connected!");
                handshakeFuture.setSuccess();
            } catch (WebSocketHandshakeException e) {
                System.out.println("WebSocket Client failed to connect");
                handshakeFuture.setFailure(e);
            }
            return;
        }
</code>```

The application is able to connect to the websocket server endpoint from my local machine successfully.

But in the company datacenter where my application is deployed, I see the msg value is null and the websocket client is disconnected

Does that mean my connection is blocked at firewall? If that is the case then why did the statement "WebSocket Client connected!" is printed at all?

Thanks

答:
The httpproxyhandler you used is correct

Just remove the BufferredReader code as mentioned below when deploying in linux, docker, etc:
Netty WebSocket Client Channel always gets inactive on Linux Server

Body:
My application is running behind a corporate firewall and I need to use http proxy(http://theclientproxy.net:8080) to connect to internet

I have used the Netty client as below,
https://github.com/netty/netty/tree/4.1/example/src/main/java/io/netty/example/http/websocketx/client

Code:

    public final class WebSocketClient {

        static final String URL = System.getProperty("url", "wss://127.0.0.1:8080/websocket");

        public static void main(String[] args) throws Exception {
            URI uri = new URI(URL);
            String scheme = uri.getScheme() == null? "ws" : uri.getScheme();
            final String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
            final int port;
    final boolean ssl = "wss".equalsIgnoreCase(scheme);
            final SslContext sslCtx;
            if (ssl) {
                sslCtx = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
            } else {
                sslCtx = null;
            }

            EventLoopGroup group = new NioEventLoopGroup();
            try {
        final WebSocketClientHandler handler =
                            new WebSocketClientHandler(
                                    WebSocketClientHandshakerFactory.newHandshaker(
                                            uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));

                    Bootstrap b = new Bootstrap();
                    b.group(group)
                     .channel(NioSocketChannel.class)
                     .handler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel ch) {
                             ChannelPipeline p = ch.pipeline();
                             if (sslCtx != null) {
                                 p.addFirst(new HttpProxyHandler(new InetSocketAddress("theclientproxy.net", 8080) ) );
                                 p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                             }
                             p.addLast(
                                     new HttpClientCodec(),
                                     new HttpObjectAggregator(8192),
                                     WebSocketClientCompressionHandler.INSTANCE,
                                     handler);
                         }
                     });

                    Channel ch = b.connect(uri.getHost(), port).sync().channel();
                    handler.handshakeFuture().sync();

BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine(); //THIS IS NULL IN DATA CENTER LOGS
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                    ch.writeAndFlush(frame);
                } else {
                    WebSocketFrame frame = new TextWebSocketFrame(msg);
                    ch.writeAndFlush(frame);
                }
            }
        } finally {
            group.shutdownGracefully();
        }

Handler:

public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    private final WebSocketClientHandshaker handshaker;
    private ChannelPromise handshakeFuture;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshaker.handshake(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("WebSocket Client disconnected!");
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            try {
                handshaker.finishHandshake(ch, (FullHttpResponse) msg);
                System.out.println("WebSocket Client connected!");
                handshakeFuture.setSuccess();
            } catch (WebSocketHandshakeException e) {
                System.out.println("WebSocket Client failed to connect");
                handshakeFuture.setFailure(e);
            }
            return;
        }

The application is able to connect to the websocket server endpoint from my local machine successfully.

But in the company datacenter where my application is deployed, I see the msg value is null and the websocket client is disconnected

Does that mean my connection is blocked at firewall? If that is the case then why did the statement "WebSocket Client connected!" is printed at all?

Thanks


问:
Validation strategy
I'm trying to build a series of attribute classes to make it easier for our development team to validate objects. The objects are POCO classes like this.

```<code>public class User
{
    public string Name { get; set; }
    public string Company { get; set; }
}
</code>```

I want to decorate this model with a custom attribute.

```<code>public class User
{
    [MustHaveValue]
    public string Name { get; set; }
    public string Company { get; set; }
}
</code>```

Then I would create my own class implementing ValidationAttribute, the base class in .NET Framework, which belongs to System.ComponentModel.DataAnnotations.

```<code>public class MustHaveValueAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // validation logic.
    }
}
</code>```

And then I can validate the User model whenever I want by making the set of instances like ValidationContext, List<ValidationResult>.

But in an enterprise environment, problems just can't be solved by a specific class. My validation scenario requires more complex and more flexible ways. Imagine that one of the required validation scenarios would something like this.

```<code>public class User
{
    public string Name { get; set; }
    public string Company { get; set; }

    // Check if an item exists in this list.
    [MustHaveMoreThanOneItem]
    public IList<Client> Clients { get; set; }
}
</code>```

Then I would need to make another attribute class

```<code>public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // Let's assume this value is List<Client> for now.
        // I know the exact type, so I'm going to cast it to List<Client> without further considerations
        List<Client> clients = value as List<Client>;
        if(clients.Count > 0) {
            return true;
        } else {
            return false;
        }
    }
}
</code>```

But the problem is that there are a lot of other models that have a nested list items. Try to imagine the time when I want to reuse the MustHaveMoreThanOneItem in one of the other models like...

```<code>public class Department
{
    public string Name { get; set; }

    [MustHaveMoreThanOneItem]
    public IList<Employee> { get; set; }
}
</code>```

You already know that it's not going to work because it was strongly typed only for List<Client>. So I decided to use Generic there to solve this problem.

But to my disappointment, the _Attribute interface doesn't support Generic. There's no additional implementation like _Attribute<T> : Attribute and therefore, no ValidationAttribute<T> alas!! I just cannot use Generic here !!

```<code>public class Department
{
    public string Name { get; set; }

    // No way to use this syntax.
    [MustHaveMoreThanOneItem<Employee>]
    public IList<Employee> { get; set; }
}
</code>```

So I made a conclusion that Attribute must have been designed for a fixed set of validations like email format, card format, null check, and etc IMAO.

But I still want to use an attribute and give a lot of flexibilities in it to prevent the duplicated, verbose validation codes like this.

```<code>if(model.Clients.Count > 0) ...
if(model.Name != null) ...
if(model.Clients.GroupBy(x => x.Country == Country.USA).Count >= 1) ...
if(model.Clients.Where(x => x.CompanyName == Company.Google).ToList().Count > 1 ) ...
.
.
.
</code>```

I want to pose two questions here.

If Attirbute supports Generic, this problem will be solved?

Is there any way to implement Generic Attribute? in order to use
[MustHaveMoreThanOneItem<Employee>] annotation on a class member?

答:
C# by definition does not support generic type attributes, although this has been requested actively for a long time:

https://github.com/dotnet/roslyn/issues/953

https://github.com/dotnet/csharplang/issues/124

However, you can still inject a type into a validation attribute via constructor. You then can use reflection or whatever you need to define your custom validation criteria.

```<code>public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    public Type EnumerableType { get; }
    public MustHaveMoreThanOneItemAttribute(Type t)
        => this.EnumerableType = typeof(ICollection<>).MakeGenericType(t);
    public override bool IsValid(object value)
    {
        var count = this.EnumerableType.GetProperty("Count").GetValue(value) as int?;
        return (count ?? 0) > 1;
    }
}
</code>```

Now this allows you to use something similar to your goal:

```<code>public class Department
{
    public string Name { get; set; }

    [MustHaveMoreThanOneItem(typeof(Employee))]
    public IList<Employee> { get; set; }
}
</code>```

Title: Validation strategy

Body:
I'm trying to build a series of attribute classes to make it easier for our development team to validate objects. The objects are POCO classes like this.

public class User
{
    public string Name { get; set; }
    public string Company { get; set; }
}

I want to decorate this model with a custom attribute.

public class User
{
    [MustHaveValue]
    public string Name { get; set; }
    public string Company { get; set; }
}

Then I would create my own class implementing ValidationAttribute, the base class in .NET Framework, which belongs to System.ComponentModel.DataAnnotations.

public class MustHaveValueAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // validation logic.
    }
}

And then I can validate the User model whenever I want by making the set of instances like ValidationContext, List<ValidationResult>.

But in an enterprise environment, problems just can't be solved by a specific class. My validation scenario requires more complex and more flexible ways. Imagine that one of the required validation scenarios would something like this.

public class User
{
    public string Name { get; set; }
    public string Company { get; set; }

    // Check if an item exists in this list.
    [MustHaveMoreThanOneItem]
    public IList<Client> Clients { get; set; }
}

Then I would need to make another attribute class

public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // Let's assume this value is List<Client> for now.
        // I know the exact type, so I'm going to cast it to List<Client> without further considerations
        List<Client> clients = value as List<Client>;
        if(clients.Count > 0) {
            return true;
        } else {
            return false;
        }
    }
}

But the problem is that there are a lot of other models that have a nested list items. Try to imagine the time when I want to reuse the MustHaveMoreThanOneItem in one of the other models like...

public class Department
{
    public string Name { get; set; }

    [MustHaveMoreThanOneItem]
    public IList<Employee> { get; set; }
}

You already know that it's not going to work because it was strongly typed only for List<Client>. So I decided to use Generic there to solve this problem.

But to my disappointment, the _Attribute interface doesn't support Generic. There's no additional implementation like _Attribute<T> : Attribute and therefore, no ValidationAttribute<T> alas!! I just cannot use Generic here !!

public class Department
{
    public string Name { get; set; }

    // No way to use this syntax.
    [MustHaveMoreThanOneItem<Employee>]
    public IList<Employee> { get; set; }
}

So I made a conclusion that Attribute must have been designed for a fixed set of validations like email format, card format, null check, and etc IMAO.

But I still want to use an attribute and give a lot of flexibilities in it to prevent the duplicated, verbose validation codes like this.

if(model.Clients.Count > 0) ...
if(model.Name != null) ...
if(model.Clients.GroupBy(x => x.Country == Country.USA).Count >= 1) ...
if(model.Clients.Where(x => x.CompanyName == Company.Google).ToList().Count > 1 ) ...
.
.
.

I want to pose two questions here.

If Attirbute supports Generic, this problem will be solved?

Is there any way to implement Generic Attribute? in order to use
[MustHaveMoreThanOneItem<Employee>] annotation on a class member?

Body:
C# by definition does not support generic type attributes, although this has been requested actively for a long time:

https://github.com/dotnet/roslyn/issues/953

https://github.com/dotnet/csharplang/issues/124

However, you can still inject a type into a validation attribute via constructor. You then can use reflection or whatever you need to define your custom validation criteria.

public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    public Type EnumerableType { get; }
    public MustHaveMoreThanOneItemAttribute(Type t)
        => this.EnumerableType = typeof(ICollection<>).MakeGenericType(t);
    public override bool IsValid(object value)
    {
        var count = this.EnumerableType.GetProperty("Count").GetValue(value) as int?;
        return (count ?? 0) > 1;
    }
}

Now this allows you to use something similar to your goal:

public class Department
{
    public string Name { get; set; }

    [MustHaveMoreThanOneItem(typeof(Employee))]
    public IList<Employee> { get; set; }
}


问:
Bootstrap datepicker not working with AJAX load()
I have an AJAX loaded page - users.php. Every time I click on the users tab, the following function is called:

```<code>function users(){
    var id = document.getElementById("usersstab");
    $("#users").load("load.php");
    $("#users").load("users.php");
}
</code>```

In users.php, I have a form that is hidden. The form is displayed only on the click of "Add user" button. In that form, I have a birth date field, for which I want to use the datepicker().

```<code><input id="dobofsubuser" type="text" name="subuserdob" class="form-control" />
</code>```

I call this function at the footer of the main (parent page) :

```<code>$('#dobofsubuser').datepicker({
    format: "yyyy-mm-dd",
    endDate: "Current Date",
    startView: 2
});
</code>```

This doesn't show the calendar and I have tried to look for answers but none of the previously mentioned solutions have helped this far. Can someone please tell me what I am doing wrong or what needs to be done so that the datepicker works on load() ? Thanks in advance!

This is the order of my scripts:

```<code>        <script src="js/modernizr-2.6.2.min.js"></script>
        <script src="http://code.jquery.com/jquery.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <script src="js/validetta.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="js/jquery.mask.min.js"></script>
        <script src="js/sweet-alert.min.js"></script>
        <script src="js/bootstrap-datepicker.min.js"></script>
        <script type="text/javascript" src="http://js.stripe.com/v2/"></script>
</code>```

If there is no solution here, can someone please suggest an alternative calendar plugin that would work well with ajax loaded pages?

答:
Possibly there is some js library that is interfering with your code.

Try this for bootstrap datepicker

```<code>$(document).ready(function () {
    var datepicker = $.fn.datepicker.noConflict();
    $.fn.bootstrapDP = datepicker;
    $("#datepicker").bootstrapDP({  format: 'yyyy-mm-dd'});
});
</code>```

Body:
I have an AJAX loaded page - users.php. Every time I click on the users tab, the following function is called:

function users(){
    var id = document.getElementById("usersstab");
    $("#users").load("load.php");
    $("#users").load("users.php");
}

In users.php, I have a form that is hidden. The form is displayed only on the click of "Add user" button. In that form, I have a birth date field, for which I want to use the datepicker().

<input id="dobofsubuser" type="text" name="subuserdob" class="form-control" />

I call this function at the footer of the main (parent page) :

$('#dobofsubuser').datepicker({
    format: "yyyy-mm-dd",
    endDate: "Current Date",
    startView: 2
});

This doesn't show the calendar and I have tried to look for answers but none of the previously mentioned solutions have helped this far. Can someone please tell me what I am doing wrong or what needs to be done so that the datepicker works on load() ? Thanks in advance!

This is the order of my scripts:

If there is no solution here, can someone please suggest an alternative calendar plugin that would work well with ajax loaded pages?

Body:
Possibly there is some js library that is interfering with your code.

Try this for bootstrap datepicker

$(document).ready(function () {
    var datepicker = $.fn.datepicker.noConflict();
    $.fn.bootstrapDP = datepicker;
    $("#datepicker").bootstrapDP({  format: 'yyyy-mm-dd'});
});


问:
C++ filling array of structure from file
Hi I need to read a file and get data from file to array of structure.

Structure

```<code>struct Activity {
    string ID;
    string Name;
    string quantity; };
</code>```

I have this function for reading from file

```<code>int* fillStructure(ifstream &fileActivity){

    int i=0;
    int numberOfElements = numberOfLines(fileActivity);

    Activity* myActivity = new Activity[numberOfElements];

    while (i < numberOfElements)
    {
          getline(fileActivity, myAktivity[i].ID, ',');
          getline(fileActivity, myActivity[i].Name, ',');
          getline(fileActivity, myActivity[i].quantity, '\n');
          i++;
    }

   fileActivity.close();
   return myActivity; }
</code>```

And when i try in main function to print members of structures It doesnt work

```<code>int main(){

    if (!(fileActivity.is_open())){
        cout << "Error when reading file" << endl;
        return 0;
    }

    fillStructure(fileActivity);

    cout << myActivity[1].ID << endl; return 0;  }
</code>```

I am beginner, can you guys help me what I am doing wrong ?

答: You declared myActivity in void fillStructure(ifstream &fileActivity), but trying to access from int main().

Body:
Hi I need to read a file and get data from file to array of structure.

Structure

struct Activity {
    string ID;
    string Name;
    string quantity; };

I have this function for reading from file

int* fillStructure(ifstream &fileActivity){

    int i=0;
    int numberOfElements = numberOfLines(fileActivity);

    Activity* myActivity = new Activity[numberOfElements];

    while (i < numberOfElements)
    {
          getline(fileActivity, myAktivity[i].ID, ',');
          getline(fileActivity, myActivity[i].Name, ',');
          getline(fileActivity, myActivity[i].quantity, '\n');
          i++;
    }

   fileActivity.close();
   return myActivity; }

And when i try in main function to print members of structures It doesnt work

int main(){

    if (!(fileActivity.is_open())){
        cout << "Error when reading file" << endl;
        return 0;
    }

    fillStructure(fileActivity);

    cout << myActivity[1].ID << endl; return 0;  }

I am beginner, can you guys help me what I am doing wrong ?