问:
How to ignore the fail case and continues to next value
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

```<code>open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================
</code>```

答:
you can use Run keyword and ignore error or Run Keyword And Continue On Failure.
details about these keywords can be found from

http://robotframework.org/robotframework/latest/libraries/BuiltIn.html

also there is a good example about these keywords here

How to ignore Get Table Text from Cell, if xpath of cell not match

in your code , your can use below line

```<code>     \   ${status}    ${result}
     \    ...   Run Keyword And Ignore Error    input text       name=id_or_tsn     ${txnExcel}
     \    Continue For Loop If    '${status}' == 'FAIL'
</code>```

and one more time in last to skip error for ${txnexcel}

```<code>Run Keyword And Continue On Failure    Should Be Equal As Strings
  ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
</code>```

Even if the value or variable ${txnExcel} is not provided , it will continue to next KW.

Body:
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================

Body:
you can use Run keyword and ignore error or Run Keyword And Continue On Failure.
details about these keywords can be found from

http://robotframework.org/robotframework/latest/libraries/BuiltIn.html

also there is a good example about these keywords here

How to ignore Get Table Text from Cell, if xpath of cell not match

in your code , your can use below line

     \   ${status}    ${result}
     \    ...   Run Keyword And Ignore Error    input text       name=id_or_tsn     ${txnExcel}
     \    Continue For Loop If    '${status}' == 'FAIL'

and one more time in last to skip error for ${txnexcel}

Run Keyword And Continue On Failure    Should Be Equal As Strings
  ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]

Even if the value or variable ${txnExcel} is not provided , it will continue to next KW.


来源: stackexchange

问:
How to encode U+FFFD in order to do a replace?
In a text file I obtain from a source I do not control, and which text content changes periodically and I have to compensate by re-downloading and processing, the char U+FFFD occurs frequently (but not always) when what is meant is the single quote or ' character.

How can I encode a replace operation so as to replace the U+FFFD with an actual single-quote in C#. I envision something like:

```<code>string s = s.Replace("U+FFFD", "'");
</code>```

Clearly I should use the overload that deals with char, but I am not sure how to encode the U+FFFD, or for that matter, the single quote!

答:
```<code>string s = s.Replace('\uFFFD','\'');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In a text file I obtain from a source I do not control, and which text content changes periodically and I have to compensate by re-downloading and processing, the char U+FFFD occurs frequently (but not always) when what is meant is the single quote or ' character.

How can I encode a replace operation so as to replace the U+FFFD with an actual single-quote in C#. I envision something like:

string s = s.Replace("U+FFFD", "'");

Clearly I should use the overload that deals with char, but I am not sure how to encode the U+FFFD, or for that matter, the single quote!

Body: string s = s.Replace('\uFFFD','\'');


问:
My main div is stuck over my header div
I am pretty new to this. I am hoping for some help and advise keeping my divs side by side. One is a menu which works fine but now my content is overlapping and I'm not sure what I did. I should make multiple saves. any advice on positioning my divs would be crazy appreciated.

apologies if my formatting of the post is wrong. brain is fried and my website is due for class tomorrow.

```<code>body {
background-color: #35455e;
}

h1 {
text-align: center;
font-size: 400%;
color: #ecb3ff;
padding-left: 30px;
}

h2 {
text-align: center;
font-size: 300%;
color: #ecb3ff;
padding-left: 40px;
}

ul {
list-style: none;
overflow: hidden;
list-style: none;
text-align: center;
border-style: hidden;
}

a {
color: white;
text-decoration: none;
font-size: 125%;
padding-left: 12px;
}

a:hover {
color: #fff666;
}

a:active {
color: #9bc1ff;
}

div.header {
background-image: url("https://scontent-sea1-1.xx.fbcdn.net/v/t1.0-
9/22089728_10212094710577763_385045730802353501_n.jpg?
oh=534f6bd3108f6f68f96cf5709e404b9f&oe=5AD4BADA");
background-size: initial;
background-repeat: repeat;
border-radius: 8px;
height: 573px;
width: 449px;
border: 10px;
box-shadow: 10px 10px 5px #333333;
float: left;
position:fixed;}

div.main{

position: relative;
top: 500px;
right: 500px;

}

li {
width: 30%;
}

My HTML:

<!DOCTYPE html>

<html>
<head>
<title>Madison Queen's Art Portfolio: Home</title>
<link rel="stylesheet" type="text/css" href="final.css">
</head>
<body>

<div class="container">

<div class="header">

<h1>Madison Art Portfolio</h1>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="Photo.html">Photography</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>

</div><!--closing of header-->

<div class="main">

<h2>Madison Art Portfolio</h2>

</div><!--CLOSING OF MAIN-->

</div><!--CLOSING OF THE CONTAINER-->
</body>
</html>
</code>```

答:
As you are using position:fixed; in div.header and position:relative; in div.main you can change the stack of them using z-index value in CSS. if you want your header on the front side and main on the back side then add z-index:2 in div.header and z-index:1 in div.main.

it is overlapping because you have specified the fixed position to the header which is placing the header on the fixed place and anything on the page will overlap with the header. you can try position:absolute

ContentLicense: CC BY-SA 3.0

Title: My main div is stuck over my header div

Body:
I am pretty new to this. I am hoping for some help and advise keeping my divs side by side. One is a menu which works fine but now my content is overlapping and I'm not sure what I did. I should make multiple saves. any advice on positioning my divs would be crazy appreciated.

apologies if my formatting of the post is wrong. brain is fried and my website is due for class tomorrow.

body {
background-color: #35455e;
}

h1 {
text-align: center;
font-size: 400%;
color: #ecb3ff;
padding-left: 30px;
}

h2 {
text-align: center;
font-size: 300%;
color: #ecb3ff;
padding-left: 40px;
}

ul {
list-style: none;
overflow: hidden;
list-style: none;
text-align: center;
border-style: hidden;
}

a {
color: white;
text-decoration: none;
font-size: 125%;
padding-left: 12px;
}

a:hover {
color: #fff666;
}

a:active {
color: #9bc1ff;
}

div.header {
background-image: url("https://scontent-sea1-1.xx.fbcdn.net/v/t1.0-
9/22089728_10212094710577763_385045730802353501_n.jpg?
oh=534f6bd3108f6f68f96cf5709e404b9f&oe=5AD4BADA");
background-size: initial;
background-repeat: repeat;
border-radius: 8px;
height: 573px;
width: 449px;
border: 10px;
box-shadow: 10px 10px 5px #333333;
float: left;
position:fixed;}

div.main{

position: relative;
top: 500px;
right: 500px;

}

li {
width: 30%;
}

My HTML:

<!DOCTYPE html>

<title>Madison Queen's Art Portfolio: Home</title>
<link rel="stylesheet" type="text/css" href="final.css">

Madison Art Portfolio

Home

Photography

Contact

Madison Art Portfolio


问:
ngIf to find substr
```<code>       <ul class="list-group" *ngFor="let head of channelDisplayHeads">
        <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1">
          <strong>{{ head }}</strong>
        </li>
      </ul>
</code>```

<p>Here the ngFor loop displays group heads like "A", "B", "C" etc. For each group head I am trying to list the channels starting with that letter in which the for loop is in. I am trying to accomplish this behavior using ngIf, but it doesn't seem to work as expected. Please advise! </p>

答:
your forgot * here , please include it as given below and try it out,

```<code> *ngIf="channel.channel.indexOf('head') === 1"
</code>```

Following is working for me

template

```<code>   <ul *ngFor="let hero of numbers"  >
   <div *ngIf="hero==1">
   {{hero}}
   </div>
   </ul>
</code>```

ts file

```<code>  numbers: Array<string> = new Array<string>();
  constructor()
  {
    this.numbers.push('1');
    this.numbers.push('2');
    this.numbers.push('3');
  }
</code>```

Title: ngIf to find substr

Body:
          {{ head }}

Here the ngFor loop displays group heads like "A", "B", "C" etc. For each group head I am trying to list the channels starting with that letter in which the for loop is in. I am trying to accomplish this behavior using ngIf, but it doesn't seem to work as expected. Please advise!

Body:
your forgot * here , please include it as given below and try it out,

 *ngIf="channel.channel.indexOf('head') === 1"

Following is working for me

template

   <ul *ngFor="let hero of numbers"  >
   <div *ngIf="hero==1">
   {{hero}}
   </div>
   </ul>

ts file

  numbers: Array<string> = new Array<string>();
  constructor()
  {
    this.numbers.push('1');
    this.numbers.push('2');
    this.numbers.push('3');
  }


问:
Converting an empty null integer from datagridview and store into database
Hi everyone i have this codes that read a datagridview to database.

```<code>cmd.Parameters.AddWithValue("@NxtKinNum", Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value));
</code>```

The row that was added is empty cell and i tried to add this into the database where the value of this is an integer... How do i set it to store a null into the database or is it not possible to do that? Thanks

答:
First Of All, In your table design "YourColumnName" should be "Allow Null".

cmd.Parameters.AddWithValue("@NxtKinNum",dataGridView1.Rows[i].Cells[3].Value==null ? DBNull.Value : dataGridView1.Rows[i].Cells[3].Value);

If cell value is null then store null value in table else store the value of datagridview Cell.

Body:
Hi everyone i have this codes that read a datagridview to database.

cmd.Parameters.AddWithValue("@NxtKinNum", Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value));

The row that was added is empty cell and i tried to add this into the database where the value of this is an integer... How do i set it to store a null into the database or is it not possible to do that? Thanks


问:
Not able to add another table in sqlite database in android studio
I created several tables in the application and all worked well. after that I am trying to add one more table with the same approach but it always gives following error

android.database.sqlite.SQLiteException: no such table: patients_record (code 1): , while compiling: SELECT * FROM patients_record
                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                           at android.os.Looper.loop(Looper.java:154)
  Here is the query of the table.

```<code> private static final String PATIENT_TABLE_CREATE = "create table if not exists patients_record( patientId text primary key not null, "
            + "patientFirstName text not null, patientLastName text not null, patientDepartment text not null, patientDoctorId text not null, patientRoom text not null );";
</code>```

I added the string to onCreate() of Database Handler with other tables that are created previously.

答:
The most usual cause is a misunderstanding in regard to when the onCreate methods runs automatically. Newcomers to SQLite often assume that it runs everytime an instance of the SQLiteOpenHelper subclass (often known as the DatabaseHelper) is instantiated.

However, onCreate is only called automatically when the Database is created. As such a simple fix, when developing an App, is to delete the database. When the App next runs the onCreate method will be invoked and create the amended structure.

Deleting the App's data will delete the database as it is part of the App's data.

Uninstalling the App will also delete the App's data.

Often the 'onUpgrade' method will contain code that DROPS the tables and then calls the onCreate method. The onUpgrade method is invoked when the Database version is increased.

Note that using any of the 3 methods above will result in some data being lost.

Body:
I created several tables in the application and all worked well. after that I am trying to add one more table with the same approach but it always gives following error

android.database.sqlite.SQLiteException: no such table: patients_record (code 1): , while compiling: SELECT * FROM patients_record
                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                           at android.os.Looper.loop(Looper.java:154)
  Here is the query of the table.

 private static final String PATIENT_TABLE_CREATE = "create table if not exists patients_record( patientId text primary key not null, "
            + "patientFirstName text not null, patientLastName text not null, patientDepartment text not null, patientDoctorId text not null, patientRoom text not null );";

I added the string to onCreate() of Database Handler with other tables that are created previously.


问:
Adding image control box into excel cells as template
Is it possible to add picture box into the excel cells, so the user could click the box on the cell and insert image instead of clicking the add picture tool at the top of excel?

example of outcome:
enter image description here

答:
You can go with this code:

```<code>With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    .ButtonName = "Submit"
    .Title = "Select an image file"
    .Filters.Clear
    .Filters.Add "JPG", "*.JPG"
    .Filters.Add "JPEG File Interchange Format", "*.JPEG"
    .Filters.Add "Graphics Interchange Format", "*.GIF"
    .Filters.Add "Portable Network Graphics", "*.PNG"
    .Filters.Add "Tag Image File Format", "*.TIFF"
    .Filters.Add "All Pictures", "*.*"

    If .Show = -1 Then
        Dim img As Object
        Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

    End If
End With
</code>```

Embed the code onto a click event for an object in your worksheet (e.g. ActiveX / Form).
Please Note: The solution is from the user Portland Runner: Excel VBA - Insert image (using dialog box) into a certain cell.

After all, the add value is rather low. You need to save the file as an .xlsm in order to keep the code working.

Body:
You can go with this code:

With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    .ButtonName = "Submit"
    .Title = "Select an image file"
    .Filters.Clear
    .Filters.Add "JPG", "*.JPG"
    .Filters.Add "JPEG File Interchange Format", "*.JPEG"
    .Filters.Add "Graphics Interchange Format", "*.GIF"
    .Filters.Add "Portable Network Graphics", "*.PNG"
    .Filters.Add "Tag Image File Format", "*.TIFF"
    .Filters.Add "All Pictures", "*.*"

    If .Show = -1 Then
        Dim img As Object
        Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

    End If
End With

Embed the code onto a click event for an object in your worksheet (e.g. ActiveX / Form).
Please Note: The solution is from the user Portland Runner: Excel VBA - Insert image (using dialog box) into a certain cell.

After all, the add value is rather low. You need to save the file as an .xlsm in order to keep the code working.


问:
aframe: how does look-controls set its initial values
When an AFrame <scene> gets loaded and a camera component has been set with look-controls enabled, how does the current orientation of the device (mobile) set the values of rotation and position of the camera?

Since a scene will have a certain point of origin. I have found that when open the scene from different positions the initial view is different, while I would like it to be the "look ahead" view.

The code is simple:

答:
look-controls takes the orientation from the sensors of the phone that is absolute and not relative to where you position the camera initially in the scene. The initial values are overridden by those coming from the sensors. Phones in 2017 do not have positional tracking but have a head neck model and calculate the position of your eyes with respect of the base of your neck which is the rotation pivot.

I don't know the context of your application but in VR you cannot rely on the same degree of control of the camera that you would have on a traditional 3D application. If you require the user to look in a certain direction you can place hints or indications to influence the user's behavior.


问:
Countdown timer in recyclerview not working properly

I have created a recyclerview that contains multiple data and a countdown timer too . All the things working properly untill i couldn't scroll the list . when i scroll down the list countdowntimer will conflicts with the above view items . It counts the current view time and the random time also . I tried too many things to solved it but couldn't able to . Please  help me out . Thanks in advance .

Here is my RecyclerAdapter's code .

```<code>public class ReferendumQuestionAdapter extends RecyclerView.Adapter<ReferendumQuestionAdapter.MyViewHolder> {

List<QuestionsModel.QuestionsData> questionBeen = new ArrayList<>();
List<QuestionsModel.LikedImages> likedImagesList = new ArrayList<>();
Activity activity;
boolean channerlView = false;
OnViewClick onViewClick ;

AppPreference preference;
CustomDialog customDialog;
AdminAPI adminAPI;

ReferendumImagesAdapter imagesRecycleViewAdapter;
List<CommentModel.GetCommentData> commentDataList = new ArrayList<>();
CommentViewAdapter commentViewAdapter;

public ReferendumQuestionAdapter(List<QuestionsModel.QuestionsData> questionBeen, Activity activity, boolean channerlView , OnViewClick onViewClick) {
    this.questionBeen = questionBeen;
    this.activity = activity;
    this.channerlView = channerlView;
    this.onViewClick = onViewClick ;
    this.preference = new AppPreference(activity);
    this.customDialog = new CustomDialog(activity);
    this.adminAPI = ServiceGenerator.getAPIClass();
}

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

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

    holder.txtQuestion.setText(questionBeen.get(position).getRef_question());
    holder.txt_channelName.setText(questionBeen.get(position).getPost_by());
    holder.txt_userName.setText(questionBeen.get(position).getNews_channel_name());

    holder.txt_views.setText(questionBeen.get(position).getTotal_view() + " View  ");
    holder.txt_comments.setText(questionBeen.get(position).getTotal_comment() + " Comment");
    holder.txt_referendums.setText(questionBeen.get(position).getTotal_like() + " Referendum ");

    String getUserName = holder.txt_userName.getText().toString().trim();
    if(getUserName==null || getUserName.isEmpty()){
        holder.txt_userName.setVisibility(View.GONE);
    }

    String channelImageURL = questionBeen.get(position).getPost_user_image();
    Glide.with(activity)
            .load(ApiURLs.IMAGE_URL + channelImageURL)
            .error(R.drawable.noimagefound)
            .into(holder.imgChannel);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    String startDateTime = questionBeen.get(position).getCurrent_date_time();
    String endDateTime = questionBeen.get(position).getEnd_date_time();
    Date startDate = null, endDate = null;
    try {
        startDate = simpleDateFormat.parse(startDateTime);
        endDate = simpleDateFormat.parse(endDateTime);

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

    long start_millis = startDate.getTime();
    long end_millis = endDate.getTime();
    long total_millis = (end_millis - start_millis);

    Log.e("checkTime" , "-->" + total_millis);

    CountDownTimer cdt = new CountDownTimer(total_millis, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
            millisUntilFinished -= TimeUnit.DAYS.toMillis(days);

            long hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished);
            millisUntilFinished -= TimeUnit.HOURS.toMillis(hours);

            long minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
            millisUntilFinished -= TimeUnit.MINUTES.toMillis(minutes);

            long seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);

            holder.txtTime.setText(" " + days + " D: " + hours + " H: " + minutes + " M: " + seconds + " S  ");
        }

        @Override
        public void onFinish() {
            holder.txtTime.setText("Finish!");
            onViewClick.onClick(position);
        }
    };
    cdt.start();
}
@Override
public int getItemCount() {
    return questionBeen.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {

    RecyclerView questionRecycle;
    TextView txtQuestion, txtTime, txt_content, txt_userName, txt_totalComment, txt_submitComment, txt_channelName , txt_views , txt_referendums  ,txt_comments;
    ImageView imgShare, imgChannel;
    EditText edt_comment;

    public MyViewHolder(View itemView) {
        super(itemView);
        questionRecycle = (RecyclerView) itemView.findViewById(R.id.recyclerview_images);
        txtQuestion = (TextView) itemView.findViewById(R.id.txt_question);
        txtTime = (TextView) itemView.findViewById(R.id.txt_time);
        txt_content = (TextView) itemView.findViewById(R.id.txt_content);
        txt_userName = (TextView) itemView.findViewById(R.id.txt_userName);
        txt_totalComment = (TextView) itemView.findViewById(R.id.txt_totalComment);
        txt_submitComment = (TextView) itemView.findViewById(R.id.txt_submitComment);
        txt_channelName = (TextView) itemView.findViewById(R.id.txt_channelName);
        txt_views = (TextView) itemView.findViewById(R.id.txt_views);
        txt_referendums = (TextView) itemView.findViewById(R.id.txt_referendums);
        txt_comments = (TextView) itemView.findViewById(R.id.txt_comments);
        imgShare = (ImageView) itemView.findViewById(R.id.img_share);
        imgChannel = (ImageView) itemView.findViewById(R.id.img_channel);
        edt_comment = (EditText) itemView.findViewById(R.id.edt_comment);

    }
}

public interface OnViewClick {
    void onClick(int position);
}
</code>```

答:
The issue is that on every onBindViewHolder call you are creating a new CountDownTimer and updating that ViewHolder. So after a couple of scrolls, multiple CountDownTimer will try to update the same ViewHolder.

Create only one CountDownTimer per ViewHolder. To do that, cancel the CountDownTimer by calling the .cancel(); on it before setting a new CountDownTimer on the ViewHolder.

In order to get access to the CountDownTimer already set on a  ViewHolder, create it on onCreateViewHolder and put it inside MyViewHolder as a field.

Have a public method on MyViewHolder called say update which does all the procedure you have written in onBindViewHolder and simple call update in onBindViewHolder of the Adapter. (cleaner code too :) )

Body:
I have created a recyclerview that contains multiple data and a countdown timer too . All the things working properly untill i couldn't scroll the list . when i scroll down the list countdowntimer will conflicts with the above view items . It counts the current view time and the random time also . I tried too many things to solved it but couldn't able to . Please  help me out . Thanks in advance .

Here is my RecyclerAdapter's code .

public class ReferendumQuestionAdapter extends RecyclerView.Adapter<ReferendumQuestionAdapter.MyViewHolder> {

List<QuestionsModel.QuestionsData> questionBeen = new ArrayList<>();
List<QuestionsModel.LikedImages> likedImagesList = new ArrayList<>();
Activity activity;
boolean channerlView = false;
OnViewClick onViewClick ;

AppPreference preference;
CustomDialog customDialog;
AdminAPI adminAPI;

ReferendumImagesAdapter imagesRecycleViewAdapter;
List<CommentModel.GetCommentData> commentDataList = new ArrayList<>();
CommentViewAdapter commentViewAdapter;

public ReferendumQuestionAdapter(List<QuestionsModel.QuestionsData> questionBeen, Activity activity, boolean channerlView , OnViewClick onViewClick) {
    this.questionBeen = questionBeen;
    this.activity = activity;
    this.channerlView = channerlView;
    this.onViewClick = onViewClick ;
    this.preference = new AppPreference(activity);
    this.customDialog = new CustomDialog(activity);
    this.adminAPI = ServiceGenerator.getAPIClass();
}

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

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

    holder.txtQuestion.setText(questionBeen.get(position).getRef_question());
    holder.txt_channelName.setText(questionBeen.get(position).getPost_by());
    holder.txt_userName.setText(questionBeen.get(position).getNews_channel_name());

    holder.txt_views.setText(questionBeen.get(position).getTotal_view() + " View  ");
    holder.txt_comments.setText(questionBeen.get(position).getTotal_comment() + " Comment");
    holder.txt_referendums.setText(questionBeen.get(position).getTotal_like() + " Referendum ");

    String getUserName = holder.txt_userName.getText().toString().trim();
    if(getUserName==null || getUserName.isEmpty()){
        holder.txt_userName.setVisibility(View.GONE);
    }

    String channelImageURL = questionBeen.get(position).getPost_user_image();
    Glide.with(activity)
            .load(ApiURLs.IMAGE_URL + channelImageURL)
            .error(R.drawable.noimagefound)
            .into(holder.imgChannel);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    String startDateTime = questionBeen.get(position).getCurrent_date_time();
    String endDateTime = questionBeen.get(position).getEnd_date_time();
    Date startDate = null, endDate = null;
    try {
        startDate = simpleDateFormat.parse(startDateTime);
        endDate = simpleDateFormat.parse(endDateTime);

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

    long start_millis = startDate.getTime();
    long end_millis = endDate.getTime();
    long total_millis = (end_millis - start_millis);

    Log.e("checkTime" , "-->" + total_millis);

    CountDownTimer cdt = new CountDownTimer(total_millis, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
            millisUntilFinished -= TimeUnit.DAYS.toMillis(days);

            long hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished);
            millisUntilFinished -= TimeUnit.HOURS.toMillis(hours);

            long minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
            millisUntilFinished -= TimeUnit.MINUTES.toMillis(minutes);

            long seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);

            holder.txtTime.setText(" " + days + " D: " + hours + " H: " + minutes + " M: " + seconds + " S  ");
        }

        @Override
        public void onFinish() {
            holder.txtTime.setText("Finish!");
            onViewClick.onClick(position);
        }
    };
    cdt.start();
}
@Override
public int getItemCount() {
    return questionBeen.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {

    RecyclerView questionRecycle;
    TextView txtQuestion, txtTime, txt_content, txt_userName, txt_totalComment, txt_submitComment, txt_channelName , txt_views , txt_referendums  ,txt_comments;
    ImageView imgShare, imgChannel;
    EditText edt_comment;

    public MyViewHolder(View itemView) {
        super(itemView);
        questionRecycle = (RecyclerView) itemView.findViewById(R.id.recyclerview_images);
        txtQuestion = (TextView) itemView.findViewById(R.id.txt_question);
        txtTime = (TextView) itemView.findViewById(R.id.txt_time);
        txt_content = (TextView) itemView.findViewById(R.id.txt_content);
        txt_userName = (TextView) itemView.findViewById(R.id.txt_userName);
        txt_totalComment = (TextView) itemView.findViewById(R.id.txt_totalComment);
        txt_submitComment = (TextView) itemView.findViewById(R.id.txt_submitComment);
        txt_channelName = (TextView) itemView.findViewById(R.id.txt_channelName);
        txt_views = (TextView) itemView.findViewById(R.id.txt_views);
        txt_referendums = (TextView) itemView.findViewById(R.id.txt_referendums);
        txt_comments = (TextView) itemView.findViewById(R.id.txt_comments);
        imgShare = (ImageView) itemView.findViewById(R.id.img_share);
        imgChannel = (ImageView) itemView.findViewById(R.id.img_channel);
        edt_comment = (EditText) itemView.findViewById(R.id.edt_comment);

    }
}

public interface OnViewClick {
    void onClick(int position);
}


问:
Adding context to a UI control or NSObject
It's great to be able to addTarget on a UIButton.  I only wish there was some sneaky way I could attach state to the UIButton so that when the target method is invoked, I could magically pull that state (any id) from the sender.

Something like:

```<code>[button shoveMyObjectInThere:foo];
[button addTarget:self action:@selector(touchyTouchy:) forControlEvents:UIControlEventTouchUpInside];
</code>```

Followed by:

```<code>-(void) touchyTouchy:(id) sender {
    UIButton button = (UIButton*)sender;
    id foo = [button getByObjectBack];
    // do something interesting with foo
}
</code>```

Would be great if UIButton had an 'id context' property where developers could shove stuff, but that doesn't seem to be the case.  Objective-C is a very dynamic language though, so I wonder if there is some sneaky way I can add method or fields to an object at runtime?

答:
The official solution is to use the "tag" property:

```<code>[self.someMutableArray addObject:foo];
button.tag = self.someMutableArray.count - 1;

[button addTarget:self action:@selector(touchyTouchy:) forControlEvents:UIControlEventTouchUpInside];
</code>```

Then:

```<code>-(void) touchyTouchy:(id) sender {
    UIButton button = (UIButton*)sender;
    id foo = self.someMutableArray[button.tag];
    // do something interesting with foo
}
</code>```

In most situations you'd use an enum or constant for the tag, but an array is obviously more flexible.

Body:
It's great to be able to addTarget on a UIButton.  I only wish there was some sneaky way I could attach state to the UIButton so that when the target method is invoked, I could magically pull that state (any id) from the sender.

Something like:

[button shoveMyObjectInThere:foo];
[button addTarget:self action:@selector(touchyTouchy:) forControlEvents:UIControlEventTouchUpInside];

Followed by:

-(void) touchyTouchy:(id) sender {
    UIButton button = (UIButton*)sender;
    id foo = [button getByObjectBack];
    // do something interesting with foo
}

Would be great if UIButton had an 'id context' property where developers could shove stuff, but that doesn't seem to be the case.  Objective-C is a very dynamic language though, so I wonder if there is some sneaky way I can add method or fields to an object at runtime?

Body:
The official solution is to use the "tag" property:

[self.someMutableArray addObject:foo];
button.tag = self.someMutableArray.count - 1;

[button addTarget:self action:@selector(touchyTouchy:) forControlEvents:UIControlEventTouchUpInside];

Then:

-(void) touchyTouchy:(id) sender {
    UIButton button = (UIButton*)sender;
    id foo = self.someMutableArray[button.tag];
    // do something interesting with foo
}

In most situations you'd use an enum or constant for the tag, but an array is obviously more flexible.


问:
Split files using SQL
This is my first time posting a question, so please bear with me for any errors.
I am trying to Split the numeric values with a delimiter of ';' using sql into separate columns, i was able to achieve splitting part of it using the code below but i will like to split the rest of it within column 3 to separate columns
I have a table like this </p>

```<code>ID    catalogNumber    STEPID1
----------------------------
815326  FBRS415    499023;499027;726203
</code>```

```<code>with tmp(catalognumber,stepid1_split,stepid1) as (
select catalognumber,cast(LEFT(stepid1, CHARINDEX(';',stepid1+';')-1) as varchar),cast(STUFF(stepid1, 1, CHARINDEX(';',stepid1+';'), '') as varchar)
from EXACT_MATCH
union all
select catalognumber, cast(LEFT(stepid1, CHARINDEX(';',stepid1+';')-1) as varchar), cast(STUFF(stepid1, 1, CHARINDEX(';',stepid1+';'), '') as varchar)
from tmp
where stepid1> ''
)
select *
from tmp
</code>```

```<code>ID     catalogNumber    STEPID1    STEPID2    STEPID3
---------------------------------------------------
815326   FBRS415         499023      499027      726203
</code>```

答:
For that, you could try XML.. .node() method to split your comma values into individual columns note that this will always gives you three columns.

You will need to add some extra columns in order to display comma separated values as you define

```<code>select distinct
       a.ID,
       a.catalogNumber,
       c.value('/m[1]', 'varchar(max)') [STEPID1],
       c.value('/m[2]', 'varchar(max)') [STEPID2],
       c.value('/m[3]', 'varchar(max)') [STEPID3] from
(
    select ID ,   catalogNumber ,   cast('<m>'+replace(STEPID1, ';', '</m><m>')+'</m>' as xml) [STEPID1]  from <table>
) a cross apply STEPID1.nodes ('/m') as STEPID1(c)
</code>```

Result :

```<code>ID      catalogNumber   STEPID1  STEPID2  STEPID3
815326  FBRS415         499023   499027   726203
</code>```

Title: Split files using SQL

Body:
This is my first time posting a question, so please bear with me for any errors.
I am trying to Split the numeric values with a delimiter of ';' using sql into separate columns, i was able to achieve splitting part of it using the code below but i will like to split the rest of it within column 3 to separate columns
I have a table like this

ID    catalogNumber    STEPID1
----------------------------
815326  FBRS415    499023;499027;726203

with tmp(catalognumber,stepid1_split,stepid1) as (
select catalognumber,cast(LEFT(stepid1, CHARINDEX(';',stepid1+';')-1) as varchar),cast(STUFF(stepid1, 1, CHARINDEX(';',stepid1+';'), '') as varchar)
from EXACT_MATCH
union all
select catalognumber, cast(LEFT(stepid1, CHARINDEX(';',stepid1+';')-1) as varchar), cast(STUFF(stepid1, 1, CHARINDEX(';',stepid1+';'), '') as varchar)
from tmp
where stepid1> ''
)
select *
from tmp

ID     catalogNumber    STEPID1    STEPID2    STEPID3
---------------------------------------------------
815326   FBRS415         499023      499027      726203

Body:
For that, you could try XML.. .node() method to split your comma values into individual columns note that this will always gives you three columns.

You will need to add some extra columns in order to display comma separated values as you define

select distinct
       a.ID,
       a.catalogNumber,
       c.value('/m[1]', 'varchar(max)') [STEPID1],
       c.value('/m[2]', 'varchar(max)') [STEPID2],
       c.value('/m[3]', 'varchar(max)') [STEPID3] from
(
    select ID ,   catalogNumber ,   cast('<m>'+replace(STEPID1, ';', '</m><m>')+'</m>' as xml) [STEPID1]  from <table>
) a cross apply STEPID1.nodes ('/m') as STEPID1(c)

Result :

ID      catalogNumber   STEPID1  STEPID2  STEPID3
815326  FBRS415         499023   499027   726203


问:
when I use a library(RODBC), a error message alert" unable to load odbcji32.dll"
library(RODBC)
channel=odbcConnectExcel2007("d:/data/Salary.xlsx")  #when run this, it alert as " unable to load odbcji32.dll" and stop, how to slove the problem.</p>

答: Thanks for your helping. I downloaded AccessDatabaseEngine_X64.exe and installed it.Then all is running rightly.</p>


问:
Realtime database on AWS

Hello, I'm using Google Firebase Real-time Database.

It was so good. On nodejs, react, react-native and etc,

it was nice to be able to handle changes in database values as event.

But I wish to develop with Amazon AWS
because I want to know why so many people love AWS and decisively, our company has been supported for 2 years to use AWS.

I wannna implement Realtime database on AWS but I couldn't find information on realtime database on AWS Console.

Question

For Realtime Database with AWS, I think I have to use several features(maybe lambda, dynamoDB). Is it right?

On React, NodeJS or etc, can I handle change on database's value?
(like google firebase cloud function, realtime database)

答:
here is a good comparison of AWS real time db and Google firebase might helpful to you

https://db-engines.com/en/system/Amazon+DynamoDB%3BFirebase+Realtime+Database%3BRealm

Title: Realtime database on AWS


问:
SQL query using Like and Between in the same statement
so here is my problem I need to select records in between year 2000-2008 but the columns I need to search for is in type varchar example:

```<code>IntRecordID     VARCHARYear
    1            1990-2000
    2            2001-2005
    3            2005-2006
    4            2007-2008
    5            2009-2020
</code>```

select all record id that has VARCHARYear between 2000 and 2008

```<code>IntRecordID
    2
    3
    4
</code>```

what is the sql query that I need to achieve this?

答:
Please try following query:

Here I try to segregate year by using SUBSTRING and CHARINDEX function since you want to use BETWEEN clause on VARCHARYear column.

eg: SUBSTRING(VARCHARYear,1,(CHARINDEX('-', VARCHARYear)-1))

Then I try to collect same IntRecordID data/row of duration of year(such as: 1990-200) of same column by UNION.

eg:

SELECT IntRecordID
        ,SUBSTRING(VARCHARYear,1,(CHARINDEX('-', VARCHARYear)-1)) AS VARCHARYear
  FROM TABLE1
  UNION
  SELECT IntRecordID
         ,SUBSTRING(VARCHARYear,(CHARINDEX('-', VARCHARYear)+1),len(VARCHARYear)) AS VARCHARYear
    FROM TABLE1

Finally I use DISTINCT to fetch duplicate IntRecordID data one time.

Hope it'll be help full for you:

```<code>SELECT DISTINCT IntRecordID
FROM
(
 SELECT IntRecordID
        ,SUBSTRING(VARCHARYear,1,(CHARINDEX('-', VARCHARYear)-1)) AS VARCHARYear
  FROM TABLE1
  UNION
  SELECT IntRecordID
         ,SUBSTRING(VARCHARYear,(CHARINDEX('-', VARCHARYear)+1),len(VARCHARYear)) AS VARCHARYear
    FROM TABLE1
  )T
   WHERE CONVERT(INT,T.VARCHARYear) BETWEEN 2001 AND 2008
</code>```

Body:
so here is my problem I need to select records in between year 2000-2008 but the columns I need to search for is in type varchar example:

IntRecordID     VARCHARYear
    1            1990-2000
    2            2001-2005
    3            2005-2006
    4            2007-2008
    5            2009-2020

select all record id that has VARCHARYear between 2000 and 2008

IntRecordID
    2
    3
    4

what is the sql query that I need to achieve this?

Body:
Please try following query:

Here I try to segregate year by using SUBSTRING and CHARINDEX function since you want to use BETWEEN clause on VARCHARYear column.

eg: SUBSTRING(VARCHARYear,1,(CHARINDEX('-', VARCHARYear)-1))

Then I try to collect same IntRecordID data/row of duration of year(such as: 1990-200) of same column by UNION.

eg:

SELECT IntRecordID
        ,SUBSTRING(VARCHARYear,1,(CHARINDEX('-', VARCHARYear)-1)) AS VARCHARYear
  FROM TABLE1
  UNION
  SELECT IntRecordID
         ,SUBSTRING(VARCHARYear,(CHARINDEX('-', VARCHARYear)+1),len(VARCHARYear)) AS VARCHARYear
    FROM TABLE1

Finally I use DISTINCT to fetch duplicate IntRecordID data one time.

Hope it'll be help full for you:

SELECT DISTINCT IntRecordID
FROM
(
 SELECT IntRecordID
        ,SUBSTRING(VARCHARYear,1,(CHARINDEX('-', VARCHARYear)-1)) AS VARCHARYear
  FROM TABLE1
  UNION
  SELECT IntRecordID
         ,SUBSTRING(VARCHARYear,(CHARINDEX('-', VARCHARYear)+1),len(VARCHARYear)) AS VARCHARYear
    FROM TABLE1
  )T
   WHERE CONVERT(INT,T.VARCHARYear) BETWEEN 2001 AND 2008


问:
How to change the image of a list view item when it is clicked in Android Studio?
In my custom listView I want to change Image when the image is clicked. But currently when I click on Image, first row image is changed not the one on which I clicked. My customAdapter is posted below:

```<code>public class WordAdapter extends ArrayAdapter<Word>  {

private int mColorResourceId;

/**
 * Create a new {@link WordAdapter} object.
 *
 * @param context is the current context (i.e. Activity) that the adapter is being created in.
 * @param words is the list of {@link Word}s to be displayed.
 * @param colorResourceId is the resource ID for the background color for this list of words
 */
public WordAdapter(Context context, ArrayList<Word> words, int colorResourceId) {
    super(context, 0, words);
    mColorResourceId = colorResourceId;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Check if an existing view is being reused, otherwise inflate the view
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }

    // Get the {@link Word} object located at this position in the list
    Word currentWord = getItem(position);

    // Find the TextView in the list_item.xml layout with the ID miwok_text_view.
    TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
    // Get the Miwok translation from the currentWord object and set this text on
    // the Miwok TextView.
    miwokTextView.setText(currentWord.getMiwokTranslation());

    // Find the TextView in the list_item.xml layout with the ID default_text_view.
    TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
    // Get the default translation from the currentWord object and set this text on
    // the default TextView.
    defaultTextView.setText(currentWord.getDefaultTranslation());

    // Find the ImageView in the list_item.xml layout with the ID image.
    ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
    // Check if an image is provided for this word or not
    if (currentWord.hasImage()) {
        // If an image is available, display the provided image based on the resource ID
        imageView.setImageResource(currentWord.getImageResourceId());
        // Make sure the view is visible
        imageView.setVisibility(View.VISIBLE);
    } else {
        // Otherwise hide the ImageView (set visibility to GONE)
        imageView.setVisibility(View.GONE);
    }

    // Set the theme color for the list item
    View textContainer = listItemView.findViewById(R.id.text_container);
    // Find the color that the resource ID maps to
    int color = ContextCompat.getColor(getContext(), mColorResourceId);
    // Set the background color of the text container View
    textContainer.setBackgroundColor(color);

    // Return the whole list item layout (containing 2 TextViews) so that it can be shown in
    // the ListView.
    return listItemView;
}
}
</code>```

And my onItemClickListener is as:

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Release the media player if it currently exists because we are about to
            // play a different sound file
            releaseMediaPlayer();

            // Get the {@link Word} object at the given position the user clicked on
            Word word = words.get(position);

            // Create and setup the {@link MediaPlayer} for the audio resource associated
            // with the current word
            mMediaPlayer = MediaPlayer.create(ColorsActivity.this, word.getAudioResourceId());

            // Start the audio file
            mMediaPlayer.start();

            //To get the pause icon
            ImageView img=(ImageView) findViewById(R.id.image2);
            img.setImageResource(word.getPlayId());

            // Setup a listener on the media player, so that we can stop and release the
            // media player once the sound has finished playing.
            mMediaPlayer.setOnCompletionListener(mCompletionListener);
        }
    });
}
</code>```

I want to change the image of imageView of id=R.id.image2 when it is clicked.
Any help will be appreciated.

Thank you in advance.

答:
You need to write view.findViewById and not just findViewById -

Change -

ImageView img=(ImageView) findViewById(R.id.image2);

to

ImageView img=(ImageView) view.findViewById(R.id.image2);

Body:
In my custom listView I want to change Image when the image is clicked. But currently when I click on Image, first row image is changed not the one on which I clicked. My customAdapter is posted below:

public class WordAdapter extends ArrayAdapter<Word>  {

private int mColorResourceId;

/**
 * Create a new {@link WordAdapter} object.
 *
 * @param context is the current context (i.e. Activity) that the adapter is being created in.
 * @param words is the list of {@link Word}s to be displayed.
 * @param colorResourceId is the resource ID for the background color for this list of words
 */
public WordAdapter(Context context, ArrayList<Word> words, int colorResourceId) {
    super(context, 0, words);
    mColorResourceId = colorResourceId;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Check if an existing view is being reused, otherwise inflate the view
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }

    // Get the {@link Word} object located at this position in the list
    Word currentWord = getItem(position);

    // Find the TextView in the list_item.xml layout with the ID miwok_text_view.
    TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
    // Get the Miwok translation from the currentWord object and set this text on
    // the Miwok TextView.
    miwokTextView.setText(currentWord.getMiwokTranslation());

    // Find the TextView in the list_item.xml layout with the ID default_text_view.
    TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
    // Get the default translation from the currentWord object and set this text on
    // the default TextView.
    defaultTextView.setText(currentWord.getDefaultTranslation());

    // Find the ImageView in the list_item.xml layout with the ID image.
    ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
    // Check if an image is provided for this word or not
    if (currentWord.hasImage()) {
        // If an image is available, display the provided image based on the resource ID
        imageView.setImageResource(currentWord.getImageResourceId());
        // Make sure the view is visible
        imageView.setVisibility(View.VISIBLE);
    } else {
        // Otherwise hide the ImageView (set visibility to GONE)
        imageView.setVisibility(View.GONE);
    }

    // Set the theme color for the list item
    View textContainer = listItemView.findViewById(R.id.text_container);
    // Find the color that the resource ID maps to
    int color = ContextCompat.getColor(getContext(), mColorResourceId);
    // Set the background color of the text container View
    textContainer.setBackgroundColor(color);

    // Return the whole list item layout (containing 2 TextViews) so that it can be shown in
    // the ListView.
    return listItemView;
}
}

And my onItemClickListener is as:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Release the media player if it currently exists because we are about to
            // play a different sound file
            releaseMediaPlayer();

            // Get the {@link Word} object at the given position the user clicked on
            Word word = words.get(position);

            // Create and setup the {@link MediaPlayer} for the audio resource associated
            // with the current word
            mMediaPlayer = MediaPlayer.create(ColorsActivity.this, word.getAudioResourceId());

            // Start the audio file
            mMediaPlayer.start();

            //To get the pause icon
            ImageView img=(ImageView) findViewById(R.id.image2);
            img.setImageResource(word.getPlayId());

            // Setup a listener on the media player, so that we can stop and release the
            // media player once the sound has finished playing.
            mMediaPlayer.setOnCompletionListener(mCompletionListener);
        }
    });
}

I want to change the image of imageView of id=R.id.image2 when it is clicked.
Any help will be appreciated.

Thank you in advance.


问:
Increment and Decrement quantity in ListView using react-native
I am running sample project. I want to display the increment and decrement values. In my project increment and decrement values are not displayed. How to change the values in text.

Here is my code:

```<code>constructor(props){
      super(props);
      this.state={
         increment:0,
         decrement:1
    }
    }
  incrementFunc(){
        var countIncrement = this.state.increment
        this.setState({
          increment : countIncrement + 1
        },()=>{
          alert(this.state.increment)
        })
      }
      decrementFunc(){

            var countDecrement = this.state.increment

        this.setState({
          decrement : countDecrement- 1,

        },()=>{
          alert(this.state.decrement)
        })
      }

<View style={styles.arrowsView}>
          <TouchableOpacity onPress ={this.incrementFunc.bind(this)}>
          <Image style={styles.arrowStyle} source={require('@images/up-arrow.png')} />
          </TouchableOpacity>
          </View>
          <View style={styles.numberView}>
          <Text style={{fontSize:15, color:'black'}}>{this.state.increment}
          </Text>
          </View>
          <View style={styles.arrowsView}>
          <TouchableOpacity onPress ={this.decrementFunc.bind(this)}>
          <Image style={styles.arrowStyle} source={require('@images/down-arrow.png')} />
          </TouchableOpacity>
          </View>
here is my screenshot:
</code>```

Please give any suggestion. Thank You

答:
Here is the solution which i had made in my project , what i did

Firstly ->created an another component which will help us to have a quantity input functionality inside list element

Secondly ->This component needs to be called by the parent component inside list renderRow to make this component visible in all the rows.
and put this QuantityInput component class inside the same file where you want to use it...

Thirdly -> Run yours application and have a look like this...

Have a look to the file attached...

/*Use this component in yours parent view inside list to have a Quantity Input inside list , I have used native base as well if some thing gets miss please have native base in yours project...*/
{<QuantityInput item={this.state.data[rowID]} viewAddToCart={false} />}

/* QuantityInput */
class QuantityInput extends React.Component {
  userProductQty = Array.apply(null, Array(this.props.item.length)).map(Number.prototype.valueOf, 1);
  itemPosition = -1;

  constructor(props) {
    super(props);
    this.state = {
      viewAddToCart: this.props.viewAddToCart,
      item: this.props.item,
      style: { flex: 1 },
      styleTextInput: { backgroundColor: '#ffffff' },
      styleButton: { backgroundColor: '#000000' },
      styleImage: { width: 12, height: 12 },
      editable: true,
      stepsize: 1,
      initialValue: 1,
      min: 1,
      max: 100
    }
  }
  upBtnPressed = (dataSource, fieldName) => {
    if (dataSource.userQty < this.state.max) {
      let value = (parseInt(dataSource.userQty) + parseInt(this.state.stepsize)).toString();
      dataSource.userQty = value;
      this.setState({
        item: dataSource
      });
    }
  }

  downBtnPressed = (dataSource, fieldName, props) => {
    if (dataSource.userQty < this.state.min) {
      let value = (parseInt(dataSource.userQty) - parseInt(this.state.stepsize)).toString();
      dataSource.userQty = value;
      this.setState({
        item: dataSource
      });
    }
  }

  onChangeText = (text, item, fieldName, itemPosition) => {
    if (!isNaN(text)) {
      item.userQty = text.toString();
      this.setState({
        item: item
      });
    } else {
      item.userQty = 0;
      this.setState({
        item: item
      });
    }
  }

  render() {
    return (
      this.state.viewAddToCart ?
        /* Add to cart */
        <View style={[{ flexDirection: 'row' }]}>
          <Left style={{ flex: 0 }}>
            <Button rounded danger
              title="Add"
              color="white"
              style={[{ width: 70 }, { height: 30 }, { justifyContent: 'center' }]}
              onPress={() => { this.props.onAddToCart(this.state.item); this.setState({ viewAddToCart: false }) }}
            >
              <Text style={[{ color: 'white' }]}>{string.addToCart}</Text>
            </Button>
            {/*</TouchableOpacity>*/}
          </Left>
        </View>
        :
        /* Quantity Text */
        <View style={{ flexDirection: 'row' }}>
          <View style={stylesQuantityText.verticle}>
            <TouchableOpacity style={[styles.button, styles.transparentBkg, { backgroundColor: '#d9534f' }, { paddingLeft: 10 }, { borderTopLeftRadius: 5 }, { borderBottomLeftRadius: 5 }, { justifyContent: 'center' }, { alignItems: 'center' }]} onPress={() => { this.downBtnPressed(this.state.item, this.state.item.productId); }} >
              <Text style={[{ width: 20 }, { height: 26 }, { fontSize: 21 }, { alignSelf: 'center' }, { paddingBottom: 10 }, { fontWeight: 'bold' }]}>-</Text>
              {/*<Icon name={"remove"} />*/}
            </TouchableOpacity>
            <TextInput
              style={[stylesQuantityText.textinput, this.state.styleTextInput]}
              editable={this.state.editable}
              keyboardType={'numeric'}
              text={this.state.item.userQty.toString()}
              value={this.state.item.userQty.toString()}
              ref={"Qty" + this.state.item.productId}
              key={"Qty" + this.state.item.productId}
              onChangeText={(text) => { this.onChangeText(text, this.state.item, this.state.item.productId); this.props.onAddToCart(this.state.item); }} />

            <TouchableOpacity style={[styles.button, styles.transparentBkg, { backgroundColor: '#d9534f' }, { paddingLeft: 10 }, { borderTopRightRadius: 5 }, { borderBottomRightRadius: 5 }]} onPress={() => { this.upBtnPressed(this.state.item, this.state.item.productId); this.props.onAddToCart(this.props.item); }}>
              {/*<Icon name={"add"}
                size={27} />*/}
              <Text style={[{ width: 20 }, { height: 26 }, { fontSize: 19 }, { alignSelf: 'center' }]}>+</Text>
            </TouchableOpacity>
          </View>
        </View>

    );
  }
}

const stylesQuantityText = StyleSheet.create({
  wrapper: {
    flex: 1,
    backgroundColor: '#eeeeee'
  },
  verticle: {
    flexDirection: 'row',
    paddingLeft: 0,
    paddingRight: 0,

  },
  horizontal: {
    flexDirection: 'row'
  },
  textinput: {
    backgroundColor: '#eeeeee',
    textAlign: 'center',
    width: 30,
    borderColor: 'black',
    borderWidth: 1,
    height: 26
  },
  button: {
    backgroundColor: '#dedede',
    padding: 5
  },
  image: {
    width: 18,
    height: 18
  },
  buttonText: {
    alignSelf: 'center'
  }

});```

]1

Body:
I am running sample project. I want to display the increment and decrement values. In my project increment and decrement values are not displayed. How to change the values in text.

Here is my code:

constructor(props){
      super(props);
      this.state={
         increment:0,
         decrement:1
    }
    }
  incrementFunc(){
        var countIncrement = this.state.increment
        this.setState({
          increment : countIncrement + 1
        },()=>{
          alert(this.state.increment)
        })
      }
      decrementFunc(){

            var countDecrement = this.state.increment

        this.setState({
          decrement : countDecrement- 1,

        },()=>{
          alert(this.state.decrement)
        })
      }

<View style={styles.arrowsView}>
          <TouchableOpacity onPress ={this.incrementFunc.bind(this)}>
          <Image style={styles.arrowStyle} source={require('@images/up-arrow.png')} />
          </TouchableOpacity>
          </View>
          <View style={styles.numberView}>
          <Text style={{fontSize:15, color:'black'}}>{this.state.increment}
          </Text>
          </View>
          <View style={styles.arrowsView}>
          <TouchableOpacity onPress ={this.decrementFunc.bind(this)}>
          <Image style={styles.arrowStyle} source={require('@images/down-arrow.png')} />
          </TouchableOpacity>
          </View>
here is my screenshot:

Please give any suggestion. Thank You

Body:
Here is the solution which i had made in my project , what i did

Firstly ->created an another component which will help us to have a quantity input functionality inside list element

Secondly ->This component needs to be called by the parent component inside list renderRow to make this component visible in all the rows.
and put this QuantityInput component class inside the same file where you want to use it...

Thirdly -> Run yours application and have a look like this...

Have a look to the file attached...

/*Use this component in yours parent view inside list to have a Quantity Input inside list , I have used native base as well if some thing gets miss please have native base in yours project...*/
{<QuantityInput item={this.state.data[rowID]} viewAddToCart={false} />}

/* QuantityInput */
class QuantityInput extends React.Component {
  userProductQty = Array.apply(null, Array(this.props.item.length)).map(Number.prototype.valueOf, 1);
  itemPosition = -1;

  constructor(props) {
    super(props);
    this.state = {
      viewAddToCart: this.props.viewAddToCart,
      item: this.props.item,
      style: { flex: 1 },
      styleTextInput: { backgroundColor: '#ffffff' },
      styleButton: { backgroundColor: '#000000' },
      styleImage: { width: 12, height: 12 },
      editable: true,
      stepsize: 1,
      initialValue: 1,
      min: 1,
      max: 100
    }
  }
  upBtnPressed = (dataSource, fieldName) => {
    if (dataSource.userQty < this.state.max) {
      let value = (parseInt(dataSource.userQty) + parseInt(this.state.stepsize)).toString();
      dataSource.userQty = value;
      this.setState({
        item: dataSource
      });
    }
  }

  downBtnPressed = (dataSource, fieldName, props) => {
    if (dataSource.userQty < this.state.min) {
      let value = (parseInt(dataSource.userQty) - parseInt(this.state.stepsize)).toString();
      dataSource.userQty = value;
      this.setState({
        item: dataSource
      });
    }
  }

  onChangeText = (text, item, fieldName, itemPosition) => {
    if (!isNaN(text)) {
      item.userQty = text.toString();
      this.setState({
        item: item
      });
    } else {
      item.userQty = 0;
      this.setState({
        item: item
      });
    }
  }

  render() {
    return (
      this.state.viewAddToCart ?
        /* Add to cart */
        <View style={[{ flexDirection: 'row' }]}>
          <Left style={{ flex: 0 }}>
            <Button rounded danger
              title="Add"
              color="white"
              style={[{ width: 70 }, { height: 30 }, { justifyContent: 'center' }]}
              onPress={() => { this.props.onAddToCart(this.state.item); this.setState({ viewAddToCart: false }) }}
            >
              <Text style={[{ color: 'white' }]}>{string.addToCart}</Text>
            </Button>
            {/*</TouchableOpacity>*/}
          </Left>
        </View>
        :
        /* Quantity Text */
        <View style={{ flexDirection: 'row' }}>
          <View style={stylesQuantityText.verticle}>
            <TouchableOpacity style={[styles.button, styles.transparentBkg, { backgroundColor: '#d9534f' }, { paddingLeft: 10 }, { borderTopLeftRadius: 5 }, { borderBottomLeftRadius: 5 }, { justifyContent: 'center' }, { alignItems: 'center' }]} onPress={() => { this.downBtnPressed(this.state.item, this.state.item.productId); }} >
              <Text style={[{ width: 20 }, { height: 26 }, { fontSize: 21 }, { alignSelf: 'center' }, { paddingBottom: 10 }, { fontWeight: 'bold' }]}>-</Text>
              {/*<Icon name={"remove"} />*/}
            </TouchableOpacity>
            <TextInput
              style={[stylesQuantityText.textinput, this.state.styleTextInput]}
              editable={this.state.editable}
              keyboardType={'numeric'}
              text={this.state.item.userQty.toString()}
              value={this.state.item.userQty.toString()}
              ref={"Qty" + this.state.item.productId}
              key={"Qty" + this.state.item.productId}
              onChangeText={(text) => { this.onChangeText(text, this.state.item, this.state.item.productId); this.props.onAddToCart(this.state.item); }} />

            <TouchableOpacity style={[styles.button, styles.transparentBkg, { backgroundColor: '#d9534f' }, { paddingLeft: 10 }, { borderTopRightRadius: 5 }, { borderBottomRightRadius: 5 }]} onPress={() => { this.upBtnPressed(this.state.item, this.state.item.productId); this.props.onAddToCart(this.props.item); }}>
              {/*<Icon name={"add"}
                size={27} />*/}
              <Text style={[{ width: 20 }, { height: 26 }, { fontSize: 19 }, { alignSelf: 'center' }]}>+</Text>
            </TouchableOpacity>
          </View>
        </View>

    );
  }
}

const stylesQuantityText = StyleSheet.create({
  wrapper: {
    flex: 1,
    backgroundColor: '#eeeeee'
  },
  verticle: {
    flexDirection: 'row',
    paddingLeft: 0,
    paddingRight: 0,

  },
  horizontal: {
    flexDirection: 'row'
  },
  textinput: {
    backgroundColor: '#eeeeee',
    textAlign: 'center',
    width: 30,
    borderColor: 'black',
    borderWidth: 1,
    height: 26
  },
  button: {
    backgroundColor: '#dedede',
    padding: 5
  },
  image: {
    width: 18,
    height: 18
  },
  buttonText: {
    alignSelf: 'center'
  }

});

]1


问:
NHibernate: Mapping query results to a list property in mapping file
I have a Contact class and I want to provide the users with AutoComplete for City and Province.

I Thought I create two collections in the Contact object and load the Cities and Provinces from the contact table on them:

```<code>public class Contact {
    public virtual string Name { get; set; }
    public virtual string City { get; set; }
    public virtual string Province { get; set; }
    public virtual IList<String> Cities { get; set; }
    public virtual IList<String> Provinces { get; set; }
}
</code>```

And have the mapping file like this:

```<code><class name="Contact">
    <id name="Id">
        <generator class="native">
            <param name="sequence">contact_id_seq</param>
        </generator>
    </id>
<property name="Name" />
<property name="City" />
<property name="Province" />
<property name="Cities" type="string" formula="SELECT DISTINCT city FROM contact" />
<property name="Provinces" type="string" formula="SELECT DISTINCT province FROM contact" />
</class>
</code>```

But this does not work.  Is there any way this can be accomplished?

Thank you.

答: formula on property is an SQL expression that defines the value for the property, so the select should return a single value. In addition by working in the way you proposed you will duplicate those values on each entity, maybe is better to define it as a static list and fill the value by a custom hql when, for example, a new session is created. </p>

Body:
I have a Contact class and I want to provide the users with AutoComplete for City and Province.

I Thought I create two collections in the Contact object and load the Cities and Provinces from the contact table on them:

public class Contact {
    public virtual string Name { get; set; }
    public virtual string City { get; set; }
    public virtual string Province { get; set; }
    public virtual IList<String> Cities { get; set; }
    public virtual IList<String> Provinces { get; set; }
}

And have the mapping file like this:

<class name="Contact">
    <id name="Id">
        <generator class="native">
            <param name="sequence">contact_id_seq</param>
        </generator>
    </id>
<property name="Name" />
<property name="City" />
<property name="Province" />
<property name="Cities" type="string" formula="SELECT DISTINCT city FROM contact" />
<property name="Provinces" type="string" formula="SELECT DISTINCT province FROM contact" />
</class>

But this does not work.  Is there any way this can be accomplished?

Thank you.


问:
calling function on Picker item Selection react native
I am trying to call a function whenever i select an item from picker and display the selected item with alert.

Here's what i am doing :-

```<code>import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
  super(props);
  this.state = {
    isLoading: true,
    throttlemode:'',
  }
}
GetSelectedThrottleModeItem=(throttlemode)=>{
Alert.alert(this.state.throttlemode)
}
render() {
return (
    <View style={styles.MainContainerAddCamp}>
    <Text style={{fontSize: 12}}> Throttle Mode</Text>
    <Picker style={styles.PickerStyleClass}
  selectedValue={this.state.throttlemode}
  onValueChange={(throttlemodeValue, throttlemodeIndex) => this.GetSelectedThrottleModeItem(this.setState({throttlemode:throttlemodeValue}))}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
    </Picker>
   </View>
  );
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});
</code>```

This code is displaying the previously selected value. How can i make it to display current selected value.

Please suggest where i have missed.

答:
Use componentDidUpdate to see the selected picker value like this</p>

```<code>componentDidUpdate(){

this.handlePickerTest();

}

handlePickerTest = () => {

alert(this.state.throttlemode);

}
</code>```

Body:
I am trying to call a function whenever i select an item from picker and display the selected item with alert.

Here's what i am doing :-

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
  super(props);
  this.state = {
    isLoading: true,
    throttlemode:'',
  }
}
GetSelectedThrottleModeItem=(throttlemode)=>{
Alert.alert(this.state.throttlemode)
}
render() {
return (
    <View style={styles.MainContainerAddCamp}>
    <Text style={{fontSize: 12}}> Throttle Mode</Text>
    <Picker style={styles.PickerStyleClass}
  selectedValue={this.state.throttlemode}
  onValueChange={(throttlemodeValue, throttlemodeIndex) => this.GetSelectedThrottleModeItem(this.setState({throttlemode:throttlemodeValue}))}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
    </Picker>
   </View>
  );
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});

This code is displaying the previously selected value. How can i make it to display current selected value.

Please suggest where i have missed.

Body:
Use componentDidUpdate to see the selected picker value like this

componentDidUpdate(){

this.handlePickerTest();

}

handlePickerTest = () => {

alert(this.state.throttlemode);

}


问:
Why doesn't TS use Symbols for enums
ES6 symbols is a great fit for enums as they avoid collision. I thouhgt that TS enum type used Symbols for enums if target:'es6', but it doesn't:

```<code>enum Role {Employee, Manager, Admin}
let role: Role = Role.Employee;
</code>```

transpiles to

```<code>var Role;
(function (Role) {
    Role[Role["Employee"] = 0] = "Employee";
    Role[Role["Manager"] = 1] = "Manager";
    Role[Role["Admin"] = 2] = "Admin";
})(Role || (Role = {}));
let role = Role.Employee;
</code>```

any ideas why? With such approach Role.Employee has the value of 0, and any other enum with the value of 0 can be used instead of Role.Employee in runtime?

答:
ES Symbol is about uniqueness whereas TypeScript enum is about named constants. Being unique and being constant are two different things.

We can serialize enum structure as it is essentially just an object. But Symbol is a different story. You cannot serialize it.

So, when we say constant, we actually mean to use that value as it is which exactly what enum provides. But Symbol is not a value that you want to use. It is more like an identity that we wish to make that nobody should be able to clone/replicate.

A constant is something that stays constant. So some code that can run in two different environments, like Node.js and Browser, both will understand the constant value to be same (in simple words, the developer is creating a value for constant, ex. string or number). But for Symbol, imagine it to not have any notion of value. If we attempt to use it as value, then it means it is two separate things (because the runtime is creating those Symbol values, not developer).

In the same light, if you have used redux, we prefer string over Symbol to represent our action.

Further, in case of TypeScript, enum can also be used as ambient or substitution value. In this case, it is the only compiler for whom the enum value matters. During compilation, type erasure may remove enum reference altogether. Now, this is something you cannot do with Symbol. Creation of Symbol is runtime only activity. So if we use Symbol for enum, then we lose to the ability of enum to be compile-time only feature.

Thus not using Symbol for enum seems a sensible choice.

Title: Why doesn't TS use Symbols for enums

Body:
ES6 symbols is a great fit for enums as they avoid collision. I thouhgt that TS enum type used Symbols for enums if target:'es6', but it doesn't:

enum Role {Employee, Manager, Admin}
let role: Role = Role.Employee;

transpiles to

var Role;
(function (Role) {
    Role[Role["Employee"] = 0] = "Employee";
    Role[Role["Manager"] = 1] = "Manager";
    Role[Role["Admin"] = 2] = "Admin";
})(Role || (Role = {}));
let role = Role.Employee;

any ideas why? With such approach Role.Employee has the value of 0, and any other enum with the value of 0 can be used instead of Role.Employee in runtime?


问:
Create object of type specified in a string
I have a bunch of classes generated by EF that are simple tables and have similar structures:

```<code>public class Contact
{
    public int ID { get; set; }
    public string Description { get; set; }
}

public class Member
{
    public int ID { get; set; }
    public string Description { get; set; }
}
</code>```

I've also got a method for returning an object of a specified type:

```<code>public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}
</code>```

What I want to do is something like this:

```<code>public ActionResult GetAll(string ClassType)        // ClassType will be the name of one of the classes above
{
    Object LookupType = GetInstance<Object>(ClassType);

    List<LookupType> AllList = new List<LookupType>();

    AllList = repo.GetAll<LookupType>().ToList<LookupType>();    // some generic method that will return a list;
}
</code>```

This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list.  However, neither of these work either:

```<code>List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();
</code>```

Both cause an error - "Using generic type List requires 1 type argument".

Is there a proper way to do this?  Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?

答:
If you don't know the type ahead of time maybe using a list of dynamic objects can help.

```<code>    var item = GetInstance<Contact>("Namespace.Contact");
    var items = new List<dynamic>();

    items.Add(item);
</code>```

You can then access the types like so...

```<code>Contact contact = items[0];
</code>```

Just be aware that using dynamic can be expensive.

Body:
I have a bunch of classes generated by EF that are simple tables and have similar structures:

public class Contact
{
    public int ID { get; set; }
    public string Description { get; set; }
}

public class Member
{
    public int ID { get; set; }
    public string Description { get; set; }
}

I've also got a method for returning an object of a specified type:

public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}

What I want to do is something like this:

public ActionResult GetAll(string ClassType)        // ClassType will be the name of one of the classes above
{
    Object LookupType = GetInstance<Object>(ClassType);

    List<LookupType> AllList = new List<LookupType>();

    AllList = repo.GetAll<LookupType>().ToList<LookupType>();    // some generic method that will return a list;
}

This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list.  However, neither of these work either:

List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();

Both cause an error - "Using generic type List requires 1 type argument".

Is there a proper way to do this?  Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?

Body:
If you don't know the type ahead of time maybe using a list of dynamic objects can help.

    var item = GetInstance<Contact>("Namespace.Contact");
    var items = new List<dynamic>();

    items.Add(item);

You can then access the types like so...

Contact contact = items[0];

Just be aware that using dynamic can be expensive.


问:
ngIf to find substr
```<code>       <ul class="list-group" *ngFor="let head of channelDisplayHeads">
        <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1">
          <strong>{{ head }}</strong>
        </li>
      </ul>
</code>```

<p>Here the ngFor loop displays group heads like "A", "B", "C" etc. For each group head I am trying to list the channels starting with that letter in which the for loop is in. I am trying to accomplish this behavior using ngIf, but it doesn't seem to work as expected. Please advise! </p>

答:
There are a number of issues here.

Your syntax for ngIf is incorrect. It needs to be *ngIf.

You cannot have both *ngFor and *ngIf on the same element. Use ng-container for one of them. This is angular's element which will not be rendered in the html and is only for angular directives.

You seem to be passing the head variable as a string. If you want to check for the element, remove the quotes.

```<code> <ul class="list-group" *ngFor="let head of channelDisplayHeads">
   <ng-container *ngFor="let channel of channelList">
     <li class="list-group-item" *ngIf="channel.channel.indexOf(head) === 1">
        <strong>{{ head }}</strong>
     </li>
   </ng-container>
 </ul>
</code>```

Title: ngIf to find substr

Body:
          {{ head }}

Here the ngFor loop displays group heads like "A", "B", "C" etc. For each group head I am trying to list the channels starting with that letter in which the for loop is in. I am trying to accomplish this behavior using ngIf, but it doesn't seem to work as expected. Please advise!

Body:
There are a number of issues here.

Your syntax for ngIf is incorrect. It needs to be *ngIf.

You cannot have both *ngFor and *ngIf on the same element. Use ng-container for one of them. This is angular's element which will not be rendered in the html and is only for angular directives.

You seem to be passing the head variable as a string. If you want to check for the element, remove the quotes.

 <ul class="list-group" *ngFor="let head of channelDisplayHeads">
   <ng-container *ngFor="let channel of channelList">
     <li class="list-group-item" *ngIf="channel.channel.indexOf(head) === 1">
        <strong>{{ head }}</strong>
     </li>
   </ng-container>
 </ul>


问:
How to bind a control to an element of a XmlDocument in the ViewModel (MVVM Pattern)?
I'm trying to bind a TextBlock to an element of a XML document, it works fine if the source is a StaticResouce, but I cannot figure out the syntax to bind to the same XML document when exposed through ViewModel.

Here's the XML document:

```<code><Books>
    <Book ID="1" Name="ABC" />
    <Book ID="2" Name="DEF" />
    <Book ID="3" Name="XYZ" />
</Books>
</code>```

Binding to a StaticResource = SUCCESSFUL

The resource file contains a XmlDataProvider with reference to Books.xml:

```<code><XmlDataProvider x:Key="data" Source="Books.xml"/>
</code>```

And here's how I'm binding to the xml file.

```<code><TextBlock Text="{Binding Source={StaticResource data},XPath=/Books/Book/@Name}"/>
<XmlDataProvider x:Key="data" Source="../Views/Data.xml" />
</code>```

As I said before, the binding above works fine and it displays "ABC". However, that XmlDocument is supposed to come from SQL Server and exposed through ViewModel (MVVM Pattern).

Binding to ViewModel = FAILED

The Books property from the ViewModel is populated with the exactly same XML (see above):

```<code>public XmlDocument Books { get; set; }
</code>```

And here's the syntax that I'm using to bind to ViewModel:

```<code><TextBlock Text="{Binding Books,XPath=/Books/Book/@Name}" />
</code>```

It doesn't return anything and I'm getting the following error message:

BindingExpression with XPath cannot bind to non-XML object.

Any help is greatly appreciated.

答: In your example where you bind to a StaticResource, your Binding Path points to an XmlDataProvider which 'adapts' your XmlDocument. Whereas in your ViewModel example, your Path is the XmlDocument itself. To achieve an equivalent binding from your ViewModel, the property needs to expose a XmlDataProvider.</p>

Body:
I'm trying to bind a TextBlock to an element of a XML document, it works fine if the source is a StaticResouce, but I cannot figure out the syntax to bind to the same XML document when exposed through ViewModel.

Here's the XML document:

<Books>
    <Book ID="1" Name="ABC" />
    <Book ID="2" Name="DEF" />
    <Book ID="3" Name="XYZ" />
</Books>

Binding to a StaticResource = SUCCESSFUL

The resource file contains a XmlDataProvider with reference to Books.xml:

<XmlDataProvider x:Key="data" Source="Books.xml"/>

And here's how I'm binding to the xml file.

<TextBlock Text="{Binding Source={StaticResource data},XPath=/Books/Book/@Name}"/>
<XmlDataProvider x:Key="data" Source="../Views/Data.xml" />

As I said before, the binding above works fine and it displays "ABC". However, that XmlDocument is supposed to come from SQL Server and exposed through ViewModel (MVVM Pattern).

Binding to ViewModel = FAILED

The Books property from the ViewModel is populated with the exactly same XML (see above):

public XmlDocument Books { get; set; }

And here's the syntax that I'm using to bind to ViewModel:

<TextBlock Text="{Binding Books,XPath=/Books/Book/@Name}" />

It doesn't return anything and I'm getting the following error message:

BindingExpression with XPath cannot bind to non-XML object.

Any help is greatly appreciated.


答:
ngIf and ngFor on the same element isn't supported. use ngIf inside template

```<code><ul class="list-group" *ngFor="let head of channelDisplayHeads">
    <h1>{{ head }}</h1>
    <ng-container *ngFor="let channel of channelList">
        <li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"> <strong></strong> <strong>{{ channel.channel }} </strong> </li>
    </ng-container>
</ul>
</code>```

Title: ngIf to find substr

Body:
ngIf and ngFor on the same element isn't supported. use ngIf inside template

<ul class="list-group" *ngFor="let head of channelDisplayHeads">
    <h1>{{ head }}</h1>
    <ng-container *ngFor="let channel of channelList">
        <li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"> <strong></strong> <strong>{{ channel.channel }} </strong> </li>
    </ng-container>
</ul>


问:
Not able to add another table in sqlite database in android studio
I created several tables in the application and all worked well. after that I am trying to add one more table with the same approach but it always gives following error

android.database.sqlite.SQLiteException: no such table: patients_record (code 1): , while compiling: SELECT * FROM patients_record
                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                           at android.os.Looper.loop(Looper.java:154)
  Here is the query of the table.

```<code> private static final String PATIENT_TABLE_CREATE = "create table if not exists patients_record( patientId text primary key not null, "
            + "patientFirstName text not null, patientLastName text not null, patientDepartment text not null, patientDoctorId text not null, patientRoom text not null );";
</code>```

I added the string to onCreate() of Database Handler with other tables that are created previously.

答:
I also have stucked with the same situation where i was adding a new column in my existing table, I solved this problem by changing the Database version number variable, just increase you DB version and build your project again and try.

Reason : When you first create table the sqlite calls onCreate method after that it never calls it again until you call your onUpgrade method, so to make changes inside you DB just increase your DB version that will cal onUpgrade method.

Body:
I created several tables in the application and all worked well. after that I am trying to add one more table with the same approach but it always gives following error

android.database.sqlite.SQLiteException: no such table: patients_record (code 1): , while compiling: SELECT * FROM patients_record
                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                           at android.os.Looper.loop(Looper.java:154)
  Here is the query of the table.

 private static final String PATIENT_TABLE_CREATE = "create table if not exists patients_record( patientId text primary key not null, "
            + "patientFirstName text not null, patientLastName text not null, patientDepartment text not null, patientDoctorId text not null, patientRoom text not null );";

I added the string to onCreate() of Database Handler with other tables that are created previously.


问:
How to merge 3 queries into one recordset
I need to export to excel summary stats from three access SQL queries, as shown below. These are being programmed in vba:

```<code>strSQL2 = "SELECT * FROM qry_pp_prev2;"
strSQL3 = "SELECT * FROM qry_pp_prev3;"
strSQL4 = "SELECT * FROM qry_pp_prev4;"

'trying to merge the 3 queries above
Set db = CurrentDb()
Set rs = db.OpenRecordset(strSQL2)
Set rs1 = db.OpenRecordset(strSQL3)
Set rs2 = db.OpenRecordset(strSQL4)

'to create excel template
Set objXL = CreateObject("Excel.Application")
Set objWB = objXL.Workbooks.Add()
Set objWS = objWB.Worksheets("Sheet1")

With objWS
.cells(1, 1).Value = "X reporting tool"
.cells(2, 1).Value = "District"
.cells(2, 2).Value = Me!subd
 .......
</code>```

Problem in putting all queries in one file access says it's too complex and thus doesn't give output. However when i use the above to merge the SQL queries and have them all export the data into a template created from access vba as above the results are not accurate.

Currently the results are blank in most of the template created, with some values on some parts of the excel template?

hope this makes sense?

答:
Ok, so I know you're asking about how to do this with VBA, but there is a new(ish) solution that is specifically designed to do this without VBA code.

For Excel 2010 and 2013 it's an add-in called "Power Query".  In Excel 2016 it is integrated natively as "Get and Transform" under the data menu.

With this solution you would walk through a wizard to define the 3 connections and describe how merge the data into one table.  You can use DSNs or create the connection via the wizard and more.

BAM, that's it.

"Data Refresh All" will connect to the 3 data sources and combine them into one table.

I'm assuming you want to append the data.  It does this just fine.  But, if you are trying to join the tables, this is supported as well.

I've done what you want to do with VBA for years and I'm blown away with what "Power Query"/"Get and Transform" can do.  I can go back and get rid of most of my code.

Here are some resouces to look at:

Getting Started with Get and Transform

Introduction to Microsoft Power Query for Excel

Body:
I need to export to excel summary stats from three access SQL queries, as shown below. These are being programmed in vba:

strSQL2 = "SELECT * FROM qry_pp_prev2;"
strSQL3 = "SELECT * FROM qry_pp_prev3;"
strSQL4 = "SELECT * FROM qry_pp_prev4;"

'trying to merge the 3 queries above
Set db = CurrentDb()
Set rs = db.OpenRecordset(strSQL2)
Set rs1 = db.OpenRecordset(strSQL3)
Set rs2 = db.OpenRecordset(strSQL4)

'to create excel template
Set objXL = CreateObject("Excel.Application")
Set objWB = objXL.Workbooks.Add()
Set objWS = objWB.Worksheets("Sheet1")

With objWS
.cells(1, 1).Value = "X reporting tool"
.cells(2, 1).Value = "District"
.cells(2, 2).Value = Me!subd
 .......

Problem in putting all queries in one file access says it's too complex and thus doesn't give output. However when i use the above to merge the SQL queries and have them all export the data into a template created from access vba as above the results are not accurate.

Currently the results are blank in most of the template created, with some values on some parts of the excel template?

hope this makes sense?