问:
RecyclerView Multiple Layout View(s) in an Adapter class
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

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

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

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

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

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

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

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

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

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

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

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

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

                }
            });

        }

    }

}
</code>```

答:
Okay, If I got it right, you want to make the second adapter, the one providing the row lists, variable, so it supports different layouts, based not on its position, but on some data from the main adapter (the one providing the sections). Therefore, overriding getItemViewType won't work, because the section data is contained in the main adapter, it does not even get there. So, the best, and cleanest course, would be to use... abstraction. Forget about multiple viewholders. Use one, and into it, bind a custom view. The custom views will provide both the specific layout files and will set the controls included in them. The holder will do just what it is intended to do: save ram by reusing views. the adavantage of this, is that you can have a clean hierarchy, which can grow in complexity in time, instead of a big, fat adapter which will become too hard to maintain.Here it is:

Since this is a lot of code to put it in here, I took your example project and modified to provide what I understood you were trying to do. Here it is:

https://github.com/fcopardo/exampleCustomViewsInHolder/tree/master

The highlights:

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

    private ArrayList<SingleItemModel> itemsList;
    private Context context;
    private String section;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList, String sectionName) {
        this.itemsList = itemsList;
        this.context = context;
        this.section = sectionName;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        return new SingleItemRowHolder(RowFactory.getRow(context, section));
    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {
        holder.setData(itemsList.get(i));
    }

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

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected AbstractRowElement rowElement;

        public SingleItemRowHolder(AbstractRowElement view) {
            super(view);
            this.rowElement = view;
        }

        public void setData(SingleItemModel singleItemModel){
            rowElement.setItem(singleItemModel);
        }

    }

}
</code>```

this is the variable layout adapter. As you can see, it uses only one ViewHolder, and a factory to provide the view instances you need.

```<code>public class RowFactory {

    public static AbstractRowElement getRow(Context context, String name){
        switch (name){
            case "Section 1": return new FullRowElement(context);
            case "Section 2": return new TextRowElement(context);
            case "Section 3": return new ImageRowElement(context);
            default:
                Log.e("inflate", name);
                return new FullRowElement(context);
        }
    }
}
</code>```

this provides the custom views, each one using a different layout, but working with the same dataset, based on the section title.

```<code>public abstract class AbstractRowElement extends CardView{

    protected int layout = 0;
    protected SingleItemModel singleItemModel;

    public AbstractRowElement(Context context) {
        super(context);
        inflateBaseLayout();
    }

    public AbstractRowElement(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflateBaseLayout();
    }

    public AbstractRowElement(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflateBaseLayout();
    }

    protected void inflateBaseLayout() {
        this.setContainer();
        if(this.layout != 0) {
            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(layout, this, true);
            this.inflateComponents();
        }
    }

    protected abstract void setContainer();
    protected abstract void inflateComponents();

    public void setItem(SingleItemModel itemModel){
        this.singleItemModel = itemModel;
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), singleItemModel.getName()+"\n"+singleItemModel.getDescription(), Toast.LENGTH_SHORT).show();
            }
        });
        setData(singleItemModel);
    }
    public abstract void setData(SingleItemModel itemModel);

}
</code>```

Finally, this is the base view class for the adapter. Subclasses define the layout file to use, and put the desired data in the controls. The rest is pretty straightforward.

It would be totally possible to make this without custom views. You could just make something like :

```<code>int layoutFile = getLayoutForSection(section);
View v = LayoutInflater.from(viewGroup.getContext()).inflate(layoutFile, null);
</code>```

But since I don't know how complex is the view you intend to create, it is best to keep things nicely separated. Have fun!

Body:
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

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

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

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

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

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

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

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

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

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

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

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

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

                }
            });

        }

    }

}

Body:
Okay, If I got it right, you want to make the second adapter, the one providing the row lists, variable, so it supports different layouts, based not on its position, but on some data from the main adapter (the one providing the sections). Therefore, overriding getItemViewType won't work, because the section data is contained in the main adapter, it does not even get there. So, the best, and cleanest course, would be to use... abstraction. Forget about multiple viewholders. Use one, and into it, bind a custom view. The custom views will provide both the specific layout files and will set the controls included in them. The holder will do just what it is intended to do: save ram by reusing views. the adavantage of this, is that you can have a clean hierarchy, which can grow in complexity in time, instead of a big, fat adapter which will become too hard to maintain.Here it is:

Since this is a lot of code to put it in here, I took your example project and modified to provide what I understood you were trying to do. Here it is:

https://github.com/fcopardo/exampleCustomViewsInHolder/tree/master

The highlights:

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

    private ArrayList<SingleItemModel> itemsList;
    private Context context;
    private String section;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList, String sectionName) {
        this.itemsList = itemsList;
        this.context = context;
        this.section = sectionName;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        return new SingleItemRowHolder(RowFactory.getRow(context, section));
    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {
        holder.setData(itemsList.get(i));
    }

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

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected AbstractRowElement rowElement;

        public SingleItemRowHolder(AbstractRowElement view) {
            super(view);
            this.rowElement = view;
        }

        public void setData(SingleItemModel singleItemModel){
            rowElement.setItem(singleItemModel);
        }

    }

}

this is the variable layout adapter. As you can see, it uses only one ViewHolder, and a factory to provide the view instances you need.

public class RowFactory {

    public static AbstractRowElement getRow(Context context, String name){
        switch (name){
            case "Section 1": return new FullRowElement(context);
            case "Section 2": return new TextRowElement(context);
            case "Section 3": return new ImageRowElement(context);
            default:
                Log.e("inflate", name);
                return new FullRowElement(context);
        }
    }
}

this provides the custom views, each one using a different layout, but working with the same dataset, based on the section title.

public abstract class AbstractRowElement extends CardView{

    protected int layout = 0;
    protected SingleItemModel singleItemModel;

    public AbstractRowElement(Context context) {
        super(context);
        inflateBaseLayout();
    }

    public AbstractRowElement(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflateBaseLayout();
    }

    public AbstractRowElement(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflateBaseLayout();
    }

    protected void inflateBaseLayout() {
        this.setContainer();
        if(this.layout != 0) {
            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(layout, this, true);
            this.inflateComponents();
        }
    }

    protected abstract void setContainer();
    protected abstract void inflateComponents();

    public void setItem(SingleItemModel itemModel){
        this.singleItemModel = itemModel;
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), singleItemModel.getName()+"\n"+singleItemModel.getDescription(), Toast.LENGTH_SHORT).show();
            }
        });
        setData(singleItemModel);
    }
    public abstract void setData(SingleItemModel itemModel);

}

Finally, this is the base view class for the adapter. Subclasses define the layout file to use, and put the desired data in the controls. The rest is pretty straightforward.

It would be totally possible to make this without custom views. You could just make something like :

int layoutFile = getLayoutForSection(section);
View v = LayoutInflater.from(viewGroup.getContext()).inflate(layoutFile, null);

But since I don't know how complex is the view you intend to create, it is best to keep things nicely separated. Have fun!


来源: stackexchange

问:
How to make PHP code like this?
```<code>$this->admin_model->list_user()
</code>```

I am writing most of the time my programs in OOP PHP. but I am writing like this...

```<code>$this->hello_world().
</code>```

The above code is CodeIgniter and I think CakePHP also following same coding style.

Please give me simple example how to make my "hello_world" like

```<code>$this->something->hello_world().
</code>```

Thanks you on advance.

Surya

答:
something is just an object of a type which has hello_world() method.

So:

```<code>class Something
{
    public function hello_world()
    {
        echo 'Hello, big world!';
        // Do work.
    }
}

class Program
{
    private $something;

    public function Run()
    {
        $this->something = new Something();
        $this->something->hello_world()
    }
}

$program = new Program();
$program->Run();
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to make PHP code like this?

Body:
$this->admin_model->list_user()

I am writing most of the time my programs in OOP PHP. but I am writing like this...

$this->hello_world().

The above code is CodeIgniter and I think CakePHP also following same coding style.

Please give me simple example how to make my "hello_world" like

$this->something->hello_world().

Thanks you on advance.

Surya

Body:
something is just an object of a type which has hello_world() method.

So:

class Something
{
    public function hello_world()
    {
        echo 'Hello, big world!';
        // Do work.
    }
}

class Program
{
    private $something;

    public function Run()
    {
        $this->something = new Something();
        $this->something->hello_world()
    }
}

$program = new Program();
$program->Run();


问:
GoPro Hero5 livestream to desktop
I try to get a live stream from my new GoPro Hero5 to my desktop.
This can be done for all the GoPro's until version 4.

But the Hero5 doesn't seem to support the http://10.5.5.9:8080/live/ URL

Any idea's how to do this with a GoPro Hero5?

答:
On Hero4 and newer you can start a UDP stream by getting this url:

```<code>http://10.5.5.9/gp/gpControl/execute?p1=gpStream&a1=proto_v2&c1=restart
</code>```

This will open a UDP stream at:

```<code>udp://10.5.5.9:8554
</code>```

Reading this stream is a little trickier. This Python script opens the stream using FFMPEG. Note the "keep alive" message this script sends at regular intervals: without these messages the camera will soon stop streaming.

I'm using elements of that script, along with an OpenCV VideoCapture object to programmatically access the stream from a Hero5 Session. The relevant code looks something like this:

```<code>cap = cv2.VideoCapture("udp://:8554", cv2.CAP_FFMPEG)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
last_message = time.time()

while some_condition():

    # Get an image
    ret, img = cap.read()

    # Do something with img
    cv2.imshow("My Window", img)
    cv2.waitKey(1)

    # Keep alive.
    current_time = time.time()
    if current_time - last_message >= keep_alive_period/1000:
        logger.info("Sending keep alive message to %s.", self.host)
        sock.sendto(message, ("10.5.5.9", 8554))
        last_message = current_time

cv2.destroyWindow(window_name)
cap.release()
</code>```

More info here.

ContentLicense: CC BY-SA 3.0

Title: GoPro Hero5 livestream to desktop

Body:
On Hero4 and newer you can start a UDP stream by getting this url:

http://10.5.5.9/gp/gpControl/execute?p1=gpStream&a1=proto_v2&c1=restart

This will open a UDP stream at:

udp://10.5.5.9:8554

Reading this stream is a little trickier. This Python script opens the stream using FFMPEG. Note the "keep alive" message this script sends at regular intervals: without these messages the camera will soon stop streaming.

I'm using elements of that script, along with an OpenCV VideoCapture object to programmatically access the stream from a Hero5 Session. The relevant code looks something like this:

cap = cv2.VideoCapture("udp://:8554", cv2.CAP_FFMPEG)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
last_message = time.time()

while some_condition():

    # Get an image
    ret, img = cap.read()

    # Do something with img
    cv2.imshow("My Window", img)
    cv2.waitKey(1)

    # Keep alive.
    current_time = time.time()
    if current_time - last_message >= keep_alive_period/1000:
        logger.info("Sending keep alive message to %s.", self.host)
        sock.sendto(message, ("10.5.5.9", 8554))
        last_message = current_time

cv2.destroyWindow(window_name)
cap.release()

More info here.


问:
How to make synchronous call with mongoose and nodejs
I'm designing a client/server synchronization feature. The client sends a bunch of changed events to server. The server will do creation, deletion or modification upon requested item status. After the database operation, the server need send a summary back to client.

Below is excerpt from my server side code, designed with mongoose and restify.

```<code>var EventModel = mongoose.model('Event', eventSchema);
server.post("/sync", function (req, res, next) {
    var events = req.params.events;
    var created = [], deleted = [], updated = [];
    events.forEach(function (elem) {
        if (elem.status == 0) {
            // Delete
            EventModel.remove({ _id: elem.uuid }, function (err, event) {
                if (!err) deleted.push({uuid: elem.uuid});
            });
        } else if (elem.status == 1) {
            // Create and update uuid
            var event = new EventModel(elem);
            event.save(function (err, doc) {
                if (!err) {
                    elem.uuid = event._doc._id;
                    created.push(elem);
                }
            });
        } else if (elem.status == 2) {
              // Update
            EventModel.findOne({ _id: elem.uuid }, function (err, event) {
                event.save(function (err, doc) {
                    if (!err) updated.push({uuid:elem.uuid});
                });
            });
        }
    });
    // Notify client what are processed.
    // PROBLEM: created, deleted, updated are always empty!
    res.send({processed: {created: created, deleted: deleted, updated: updated}});
});
</code>```

Since mongoose do CRUD in async way, the response created,deleted and updated are always empty.
Is there any way to let the mongoose operation in series?

答:
As stated in the comments you could use the npm async module.

Alternatively, you may prefer to nest callbacks (but this might lead to what is known as callback hell, viz many nested callbacks) or take advantage of the mongoose .then() method - see http://mongoosejs.com/docs/promises.html

Here you can do ..

```<code>EventModel.remove(args).then((removeResponse) => {
  return EventModel.findOne(args);
}).then((findResponse) => {
  // etc
})
</code>```

These requests will happen synchronously.

Body:
I'm designing a client/server synchronization feature. The client sends a bunch of changed events to server. The server will do creation, deletion or modification upon requested item status. After the database operation, the server need send a summary back to client.

Below is excerpt from my server side code, designed with mongoose and restify.

var EventModel = mongoose.model('Event', eventSchema);
server.post("/sync", function (req, res, next) {
    var events = req.params.events;
    var created = [], deleted = [], updated = [];
    events.forEach(function (elem) {
        if (elem.status == 0) {
            // Delete
            EventModel.remove({ _id: elem.uuid }, function (err, event) {
                if (!err) deleted.push({uuid: elem.uuid});
            });
        } else if (elem.status == 1) {
            // Create and update uuid
            var event = new EventModel(elem);
            event.save(function (err, doc) {
                if (!err) {
                    elem.uuid = event._doc._id;
                    created.push(elem);
                }
            });
        } else if (elem.status == 2) {
              // Update
            EventModel.findOne({ _id: elem.uuid }, function (err, event) {
                event.save(function (err, doc) {
                    if (!err) updated.push({uuid:elem.uuid});
                });
            });
        }
    });
    // Notify client what are processed.
    // PROBLEM: created, deleted, updated are always empty!
    res.send({processed: {created: created, deleted: deleted, updated: updated}});
});

Since mongoose do CRUD in async way, the response created,deleted and updated are always empty.
Is there any way to let the mongoose operation in series?

Body:
As stated in the comments you could use the npm async module.

Alternatively, you may prefer to nest callbacks (but this might lead to what is known as callback hell, viz many nested callbacks) or take advantage of the mongoose .then() method - see http://mongoosejs.com/docs/promises.html

Here you can do ..

EventModel.remove(args).then((removeResponse) => {
  return EventModel.findOne(args);
}).then((findResponse) => {
  // etc
})

These requests will happen synchronously.


问:
Is there a way to choose the names of the evolutions file in Play?
I'm using the evolutions from Play! (2.5) and since my project is growing I'm ending with a 23.sql file (after 22 n.sql files in my evolutions conf folder).

It begins to be difficult to retrieve informations.

Is there a way to name these files differently, as, for example addEventTable.sql instead of 24.sql?

答: Currently not using the default evolutions mechanism. But you can use something like flyway-play which enables you to have evolutions file named like V1__Create_person_table.sql, V2__Add_people.sql, etc.


问:
Fixing the width of the table being binded in the datagrid
I am working on a windows application.

I am binding a column of a table from the database in a datagrid.But when it is populated its getting its actual dimention and some space is left blank in the datagrid...is it possible that the column of the table would rather take the actual full dimention of the datagrid while populating.

Waiting for your reply...

答:
Set the AutoSizeColumnsMode property of the DataGridView to Fill.

The DataGridViewColumn also has an AutoSize property, so you can set the behavior for each column individually if you want to have them sized differently.


问:
Get sunday date between two date and last day from one month mysql
I want to get all sunday date between two dates and get last day between two date, how can i do that in mysql?
Example :

```<code>start date | end date
2017-03-01 | 2017-03-31
</code>```

then the results are :

```<code>2017-03-05
2017-03-12
2017-03-19
2017-03-26
2017-03-31
</code>```

Start date and end date possible to change, please advise me.
Thank you

答:
MySQL has a DAYOFWEEK() function which would return 1 for any date which is a Sunday:

```<code>SELECT date_column
FROM yourTable
WHERE (date_column BETWEEN '2017-03-01' AND '2017-03-31' AND
       DAYOFWEEK(date_column) = 1) OR        -- any Sunday
      date_column = '2017-03-31'             -- or the last date in the range
</code>```

I am assuming that yourTable already has dates in it.  If you need help with populating a table with a range of dates, this problem has been covered well before on Stack Overflow, q.v. here:

How to populate a table with a range of dates?

Demo here:

Rextester

Body:
I want to get all sunday date between two dates and get last day between two date, how can i do that in mysql?
Example :

start date | end date
2017-03-01 | 2017-03-31

then the results are :

2017-03-05
2017-03-12
2017-03-19
2017-03-26
2017-03-31

Start date and end date possible to change, please advise me.
Thank you

Body:
MySQL has a DAYOFWEEK() function which would return 1 for any date which is a Sunday:

SELECT date_column
FROM yourTable
WHERE (date_column BETWEEN '2017-03-01' AND '2017-03-31' AND
       DAYOFWEEK(date_column) = 1) OR        -- any Sunday
      date_column = '2017-03-31'             -- or the last date in the range

I am assuming that yourTable already has dates in it.  If you need help with populating a table with a range of dates, this problem has been covered well before on Stack Overflow, q.v. here:

How to populate a table with a range of dates?

Demo here:

Rextester


问:
Android - Custom EditText with different input types
I'm trying to make a custom EditText for currency which means I need to have a prefix of it for the currency and I have to limit users' input to numbers only.

This is my custom EditText code

```<code>public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

private void applyCustomFont(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);

    ...

    // Prefix
    String prefix = a.getString(R.styleable.OpenSansET_prefix);
    if (prefix != null) {
        mPrefix = prefix;
    } else {
        mPrefix = "";
    }

    // Prefix Color
    int prefixColor = a.getColor(R.styleable.OpenSansET_prefixColor, 0);
    if (prefix != null) {
        mPrefixColor = prefixColor;
    } else {
        mPrefixColor = ContextCompat.getColor(context, R.color.miBlack);
    }

    a.recycle();
}

...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")) {
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        paint.setColor(mPrefixColor);
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), paint);
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}
</code>```

This is how I use it in xml :

```<code><com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMinRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/min"
    android:textColor="@color/miBlack"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />

<com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMaxRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/max"
    android:inputType="number"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />
</code>```

Which yields :

Only the first one without inputType as number has the currency sign shown, whereas the second ET doesn't have its currency sign shown.

How to achieve currency prefix as text and still keeping inputType to numbers only for user? And I don't want to use two views, namely EditText and TextView to left of it, both inside a ViewGroup to achieve that.

答:
For this type of scenarios I use Compound views. Please see below code for more information.

First create a layout for your custom view like below.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txt_prefix"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="$" />

    <EditText
        android:id="@+id/et_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:inputType="number" />
</LinearLayout>
</code>```

Now create a new class which should extends the LinearLayout. See below code.

```<code>public class OpenSansEditText extends LinearLayout {
    private TextView txtPrefix;
    private EditText etValue;
    private String prefix = "$";
    private int prefixColor = Color.BLACK;

    public OpenSansEditText(Context context) {
        super(context);
        initializeViews(context, null);
    }

    public OpenSansEditText(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initializeViews(context, attrs);
    }

    public OpenSansEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initializeViews(context, attrs);
    }

    private void initializeViews(Context context, AttributeSet attrs) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.opensansedittext_view, this,true);

        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.OpenSansEditText);
            prefix = a.getString(R.styleable.OpenSansEditText_prefix);
            prefixColor = a.getColor(R.styleable.OpenSansEditText_prefixColor, Color.BLACK);
        }
    }

    public  CharSequence getValue(){
        return etValue.getText();
    }

    public CharSequence getPrefix(){
        return txtPrefix.getText();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        txtPrefix = (TextView) findViewById(R.id.txt_prefix);
        etValue  = (EditText) findViewById(R.id.et_value);

        txtPrefix.setText(prefix);
        txtPrefix.setTextColor(prefixColor);
    }
}
</code>```

And then add your attributes to attribute xml file Ex: (attrs.xml in my case)

```<code><resources>

    <declare-styleable name="OpenSansEditText">
        <attr name="prefix" format="string"/>
        <attr name="prefixColor" format="color"/>
    </declare-styleable>

</resources>
</code>```

Now you can use it anywhere in the project as below

```<code>  <com.asta.www.classes.OpenSansEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:prefix="$"
        app:prefixColor="#f00"/>
</code>```

Hope this will help you to solve your problem. Thanks...

Body:
I'm trying to make a custom EditText for currency which means I need to have a prefix of it for the currency and I have to limit users' input to numbers only.

This is my custom EditText code

public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

private void applyCustomFont(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);

    ...

    // Prefix
    String prefix = a.getString(R.styleable.OpenSansET_prefix);
    if (prefix != null) {
        mPrefix = prefix;
    } else {
        mPrefix = "";
    }

    // Prefix Color
    int prefixColor = a.getColor(R.styleable.OpenSansET_prefixColor, 0);
    if (prefix != null) {
        mPrefixColor = prefixColor;
    } else {
        mPrefixColor = ContextCompat.getColor(context, R.color.miBlack);
    }

    a.recycle();
}

...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")) {
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        paint.setColor(mPrefixColor);
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), paint);
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}

This is how I use it in xml :

<com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMinRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/min"
    android:textColor="@color/miBlack"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />

<com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMaxRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/max"
    android:inputType="number"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />

Which yields :

Only the first one without inputType as number has the currency sign shown, whereas the second ET doesn't have its currency sign shown.

How to achieve currency prefix as text and still keeping inputType to numbers only for user? And I don't want to use two views, namely EditText and TextView to left of it, both inside a ViewGroup to achieve that.

Body:
For this type of scenarios I use Compound views. Please see below code for more information.

First create a layout for your custom view like below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txt_prefix"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="$" />

    <EditText
        android:id="@+id/et_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:inputType="number" />
</LinearLayout>

Now create a new class which should extends the LinearLayout. See below code.

public class OpenSansEditText extends LinearLayout {
    private TextView txtPrefix;
    private EditText etValue;
    private String prefix = "$";
    private int prefixColor = Color.BLACK;

    public OpenSansEditText(Context context) {
        super(context);
        initializeViews(context, null);
    }

    public OpenSansEditText(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initializeViews(context, attrs);
    }

    public OpenSansEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initializeViews(context, attrs);
    }

    private void initializeViews(Context context, AttributeSet attrs) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.opensansedittext_view, this,true);

        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.OpenSansEditText);
            prefix = a.getString(R.styleable.OpenSansEditText_prefix);
            prefixColor = a.getColor(R.styleable.OpenSansEditText_prefixColor, Color.BLACK);
        }
    }

    public  CharSequence getValue(){
        return etValue.getText();
    }

    public CharSequence getPrefix(){
        return txtPrefix.getText();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        txtPrefix = (TextView) findViewById(R.id.txt_prefix);
        etValue  = (EditText) findViewById(R.id.et_value);

        txtPrefix.setText(prefix);
        txtPrefix.setTextColor(prefixColor);
    }
}

And then add your attributes to attribute xml file Ex: (attrs.xml in my case)

<resources>

    <declare-styleable name="OpenSansEditText">
        <attr name="prefix" format="string"/>
        <attr name="prefixColor" format="color"/>
    </declare-styleable>

</resources>

Now you can use it anywhere in the project as below

  <com.asta.www.classes.OpenSansEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:prefix="$"
        app:prefixColor="#f00"/>

Hope this will help you to solve your problem. Thanks...


问:
Xamarin Android - custom KeyEvent
I created a custom Android keyboard with keys for hexadecimal numbers (0..9, A..F). It does not have a Shift/CapsLock key.
The custom keyboard's layout is defined in an .xml file  like this:

```<code><Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="33%p" android:horizontalGap="0px" android:verticalGap="0px" android:keyHeight="50dip">
  <Row>
    <Key android:codes="7" android:keyLabel="0" android:keyEdgeFlags="left" />
    <Key android:codes="8" android:keyLabel="1" />
    <Key android:codes="9" android:keyLabel="2" />
    <Key android:codes="10" android:keyLabel="3" />
    <Key android:codes="11" android:keyLabel="4" android:keyEdgeFlags="right" />
  </Row>
  <Row>
    <Key android:codes="12" android:keyLabel="5" android:keyEdgeFlags="left" />
    <Key android:codes="13" android:keyLabel="6" />
    <Key android:codes="14" android:keyLabel="7" />
    <Key android:codes="15" android:keyLabel="8" />
    <Key android:codes="16" android:keyLabel="9" android:keyEdgeFlags="right" />
  </Row>
  <Row>
    <Key android:codes="29" android:keyLabel="A" android:keyEdgeFlags="left" />
    <Key android:codes="30" android:keyLabel="B" />
    <Key android:codes="31" android:keyLabel="C" />
    <Key android:codes="32" android:keyLabel="D" />
    <Key android:codes="33" android:keyLabel="E" android:keyEdgeFlags="right" />
  </Row>
  <Row>
    <Key android:codes="67" android:keyIcon="@drawable/sym_keyboard_delete" android:iconPreview="@drawable/sym_keyboard_delete" android:keyEdgeFlags="left" />
    <Key android:codes="34" android:keyLabel="F" />
    <Key android:codes="66" android:keyEdgeFlags="right" android:keyIcon="@drawable/sym_keyboard_feedback_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" />
  </Row>
</Keyboard>
</code>```

The custom keyboard works fine, my only problem is that the keys 'A' to 'F' actually generate lower-case chars, and I'd like them to be shifted to upper-cases.

My custom keyboard's Key event handler is like this:

```<code>mHexKeyboardView.Key += (sender, e) => {
    long eventTime = JavaSystem.CurrentTimeMillis();

    // Create a new key event
    // KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags)
    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    this.DispatchKeyEvent(ev);
};
</code>```

And I'd like to force a "conversion" to upper-case in the Key event handler (not anywhere else). For example when key 'A' is pressed,
    e.PrimaryCode = Android.Views.Keycode.A, and my EditView shall receive char 'A' and not 'a'.

I guess that I should provide some 'metaState' value to the KeyEvent() constructor and have the key 'shifted', maybe?

Any suggestions/examples on this topic?

Thanks!

答:
You need to indicate you want the value shifted using a MetaState of MetaKeyStates.ShiftLeftOn as the 6th parameter in the KeyEvent constructor. But you need to do this only for the letters (A to B) for the numbers you need to keep sending 0.

For that you can create something like:

```<code>var shiftedArray = new [] { "A", "B", "C", "D", "E", "F"};

mKeyboardView.Key += (sender, e) => {
    long eventTime = JavaSystem.CurrentTimeMillis();

    var isShifted = shiftedArray.Any (a => a == e.PrimaryCode.ToString());

    MetaKeyStates metaKeyState = isShifted ? MetaKeyStates.ShiftLeftOn : 0;

    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, metaKeyState , 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    this.DispatchKeyEvent(ev);
};
</code>```

Any value you enter in the shiftedArray will be shifted. You can replace this with IFs, switch/case or any other algorithm you find more suitable for you, did it like this for simplicity.

Hope this helps!

Title: Xamarin Android - custom KeyEvent

Body:
I created a custom Android keyboard with keys for hexadecimal numbers (0..9, A..F). It does not have a Shift/CapsLock key.
The custom keyboard's layout is defined in an .xml file  like this:

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="33%p" android:horizontalGap="0px" android:verticalGap="0px" android:keyHeight="50dip">
  <Row>
    <Key android:codes="7" android:keyLabel="0" android:keyEdgeFlags="left" />
    <Key android:codes="8" android:keyLabel="1" />
    <Key android:codes="9" android:keyLabel="2" />
    <Key android:codes="10" android:keyLabel="3" />
    <Key android:codes="11" android:keyLabel="4" android:keyEdgeFlags="right" />
  </Row>
  <Row>
    <Key android:codes="12" android:keyLabel="5" android:keyEdgeFlags="left" />
    <Key android:codes="13" android:keyLabel="6" />
    <Key android:codes="14" android:keyLabel="7" />
    <Key android:codes="15" android:keyLabel="8" />
    <Key android:codes="16" android:keyLabel="9" android:keyEdgeFlags="right" />
  </Row>
  <Row>
    <Key android:codes="29" android:keyLabel="A" android:keyEdgeFlags="left" />
    <Key android:codes="30" android:keyLabel="B" />
    <Key android:codes="31" android:keyLabel="C" />
    <Key android:codes="32" android:keyLabel="D" />
    <Key android:codes="33" android:keyLabel="E" android:keyEdgeFlags="right" />
  </Row>
  <Row>
    <Key android:codes="67" android:keyIcon="@drawable/sym_keyboard_delete" android:iconPreview="@drawable/sym_keyboard_delete" android:keyEdgeFlags="left" />
    <Key android:codes="34" android:keyLabel="F" />
    <Key android:codes="66" android:keyEdgeFlags="right" android:keyIcon="@drawable/sym_keyboard_feedback_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" />
  </Row>
</Keyboard>

The custom keyboard works fine, my only problem is that the keys 'A' to 'F' actually generate lower-case chars, and I'd like them to be shifted to upper-cases.

My custom keyboard's Key event handler is like this:

mHexKeyboardView.Key += (sender, e) => {
    long eventTime = JavaSystem.CurrentTimeMillis();

    // Create a new key event
    // KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags)
    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    this.DispatchKeyEvent(ev);
};

And I'd like to force a "conversion" to upper-case in the Key event handler (not anywhere else). For example when key 'A' is pressed,
    e.PrimaryCode = Android.Views.Keycode.A, and my EditView shall receive char 'A' and not 'a'.

I guess that I should provide some 'metaState' value to the KeyEvent() constructor and have the key 'shifted', maybe?

Any suggestions/examples on this topic?

Thanks!

Body:
You need to indicate you want the value shifted using a MetaState of MetaKeyStates.ShiftLeftOn as the 6th parameter in the KeyEvent constructor. But you need to do this only for the letters (A to B) for the numbers you need to keep sending 0.

For that you can create something like:

var shiftedArray = new [] { "A", "B", "C", "D", "E", "F"};

mKeyboardView.Key += (sender, e) => {
    long eventTime = JavaSystem.CurrentTimeMillis();

    var isShifted = shiftedArray.Any (a => a == e.PrimaryCode.ToString());

    MetaKeyStates metaKeyState = isShifted ? MetaKeyStates.ShiftLeftOn : 0;

    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, metaKeyState , 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    this.DispatchKeyEvent(ev);
};

Any value you enter in the shiftedArray will be shifted. You can replace this with IFs, switch/case or any other algorithm you find more suitable for you, did it like this for simplicity.

Hope this helps!


问:
How to split a text file into multiple files?
In C#, what is the most efficient method to split a text file into multiple text files (the splitting delimiter being a blank line), while preserving the character encoding?</p>

答:
I would use the StreamReader and StreamWriter classes:

```<code> public void Split(string inputfile, string outputfilesformat) {
     int i = 0;
     System.IO.StreamWriter outfile = null;
     string line;

     try {
          using(var infile = new System.IO.StreamReader(inputfile)) {
               while(!infile.EndOfStream){
                   line = infile.ReadLine();
                   if(string.IsNullOrEmpty(line)) {
                       if(outfile != null) {
                           outfile.Dispose();
                           outfile = null;
                       }
                       continue;
                   }
                   if(outfile == null) {
                       outfile = new System.IO.StreamWriter(
                           string.Format(outputfilesformat, i++),
                           false,
                           infile.CurrentEncoding);
                   }
                   outfile.WriteLine(line);
               }

          }
     } finally {
          if(outfile != null)
               outfile.Dispose();
     }
 }
</code>```

You would then call this method like this:

```<code> Split("C:\\somefile.txt", "C:\\output-files-{0}.txt");
</code>```

Body:
I would use the StreamReader and StreamWriter classes:

 public void Split(string inputfile, string outputfilesformat) {
     int i = 0;
     System.IO.StreamWriter outfile = null;
     string line;

     try {
          using(var infile = new System.IO.StreamReader(inputfile)) {
               while(!infile.EndOfStream){
                   line = infile.ReadLine();
                   if(string.IsNullOrEmpty(line)) {
                       if(outfile != null) {
                           outfile.Dispose();
                           outfile = null;
                       }
                       continue;
                   }
                   if(outfile == null) {
                       outfile = new System.IO.StreamWriter(
                           string.Format(outputfilesformat, i++),
                           false,
                           infile.CurrentEncoding);
                   }
                   outfile.WriteLine(line);
               }

          }
     } finally {
          if(outfile != null)
               outfile.Dispose();
     }
 }

You would then call this method like this:

 Split("C:\\somefile.txt", "C:\\output-files-{0}.txt");


问:
ssh remote host identification has changed
I've reinstalled my server and I am getting these messages:

```<code>[user@hostname ~]$ ssh root@pong
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
6e:45:f9:a8:af:38:3d:a1:a5:c7:76:1d:02:f8:77:00.
Please contact your system administrator.
Add correct host key in /home/hostname /.ssh/known_hosts to get rid of this message.
Offending RSA key in /var/lib/sss/pubconf/known_hosts:4
RSA host key for pong has changed and you have requested strict checking.
Host key verification failed.
</code>```

I have tried various solutions that I found on the Internet. My known_hosts file (normally in ~/.ssh/known_hosts) is in /var/lib/sss/pubconf/known_hosts. I've tried to edit it, but it remains in one state. I have installed ipa-client and have Fedora 19. How do I resolve this warning?

All the answers answered so far work only if you do not have Freeipa installed.

The right answer for freeipa in comments below from adrin is here.

答:
As many have already said, use ssh-keygen, i.e.

```<code>ssh-keygen -R pong
</code>```

Also, you may like to consider temporarily turning off host key checking:

```<code>ssh -oStrictHostKeyChecking=no root@pong
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've reinstalled my server and I am getting these messages:

[user@hostname ~]$ ssh root@pong
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
6e:45:f9:a8:af:38:3d:a1:a5:c7:76:1d:02:f8:77:00.
Please contact your system administrator.
Add correct host key in /home/hostname /.ssh/known_hosts to get rid of this message.
Offending RSA key in /var/lib/sss/pubconf/known_hosts:4
RSA host key for pong has changed and you have requested strict checking.
Host key verification failed.

I have tried various solutions that I found on the Internet. My known_hosts file (normally in ~/.ssh/known_hosts) is in /var/lib/sss/pubconf/known_hosts. I've tried to edit it, but it remains in one state. I have installed ipa-client and have Fedora 19. How do I resolve this warning?

All the answers answered so far work only if you do not have Freeipa installed.

The right answer for freeipa in comments below from adrin is here.

Body:
As many have already said, use ssh-keygen, i.e.

ssh-keygen -R pong

Also, you may like to consider temporarily turning off host key checking:

ssh -oStrictHostKeyChecking=no root@pong


问:
How to define typeclass instance for higher kinded types in Scala?
I'm implementing a typeclass of serializable types in Scala. It's easy for simple types

```<code>trait Serializer[T] {
  def toBytes(a: T): Array[Byte]
}

implicit object StringSerializer extends Serializer[String] {
    override def toBytes(x: String) = ...
}

// similar codes for other simple types
</code>```

But I got stuck in defining an instance for higher kinded types like Option[T], List[T], etc. Naturally, List[T] is serializable only if T is serializable. But how to express the constraint in Scala? My unsuccessful try:

```<code>implicit object ListSerializer extends Serializer[List[_]] {
  // won't compile
  override def toBytes[T: Serializer](a: List[T]): Array[Byte] = ...
}
</code>```

答:
The thing is, you are using a existencial in Serializer[List[_]] effectively the only thing that an overriding method can accept then is List[_]. The way is to somehow provide a concrete type List[T] to the serializer. The trick:

```<code>scala> :paste
// Entering paste mode (ctrl-D to finish)
// trait Serializer and the implicit object removed for brevity, the former was implemented with x.getBytes

implicit def listIsSerializable[T:Serializer]:Serializer[List[T]] =
  new Serializer[List[T]] {
    def toBytes(xs:List[T])=xs.map(implicitly[Serializer[T]].toBytes).toArray.flatten
  }

// Exiting paste mode, now interpreting.

defined trait Serializer
defined object StringSerializer
listIsSerializable: [T](implicit evidence$1: Serializer[T])Serializer[List[T]]

scala> implicitly[Serializer[List[String]]].toBytes(List("A","B"))
res0: Array[Byte] = Array(65, 66)
</code>```

Body:
I'm implementing a typeclass of serializable types in Scala. It's easy for simple types

trait Serializer[T] {
  def toBytes(a: T): Array[Byte]
}

implicit object StringSerializer extends Serializer[String] {
    override def toBytes(x: String) = ...
}

// similar codes for other simple types

But I got stuck in defining an instance for higher kinded types like Option[T], List[T], etc. Naturally, List[T] is serializable only if T is serializable. But how to express the constraint in Scala? My unsuccessful try:

implicit object ListSerializer extends Serializer[List[_]] {
  // won't compile
  override def toBytes[T: Serializer](a: List[T]): Array[Byte] = ...
}

Body:
The thing is, you are using a existencial in Serializer[List[_]] effectively the only thing that an overriding method can accept then is List[_]. The way is to somehow provide a concrete type List[T] to the serializer. The trick:

scala> :paste
// Entering paste mode (ctrl-D to finish)
// trait Serializer and the implicit object removed for brevity, the former was implemented with x.getBytes

implicit def listIsSerializable[T:Serializer]:Serializer[List[T]] =
  new Serializer[List[T]] {
    def toBytes(xs:List[T])=xs.map(implicitly[Serializer[T]].toBytes).toArray.flatten
  }

// Exiting paste mode, now interpreting.

defined trait Serializer
defined object StringSerializer
listIsSerializable: [T](implicit evidence$1: Serializer[T])Serializer[List[T]]

scala> implicitly[Serializer[List[String]]].toBytes(List("A","B"))
res0: Array[Byte] = Array(65, 66)


问:
Swift 3 ios: UILabel needs to appear on top of a UIImage when the Image appears
So I am trying to give the user the ability to design their own virtual business card where the user can drag a label around the UIView, they can change background color of the UIView, as well as the color of the UILabel.  The card itself is represented by a nib and the user selects the different color choices or template image choices through a UIPickerView.  I want the Label to appear on top of the Image when it appears and is dragged to that part of the View, however it is not currently doing that.  Changing colors of the background for the UIView and the text work just fine; I am also able to add and remove the Template image (which is a PNG) by using .isHidden().

My Problem is that when the UIImage is added to the UIView it is on top of the UILabel.  If part of the UILabel overlaps with part of the png image it disappears behind it, and I would like it to appear over the image.

The code for the nib is in userCardView.swift and the picker view is on the mainViewController where I set the UserDefaults which works fine.

```<code>class userCardView: UIView {

   @IBOutlet var cardView: UIView!
   @IBOutlet weak var testLBL: UILabel!
   @IBOutlet weak var templateImage: UIImageView!

   var colorIndex = ["Black", "White", "Gray"]
   var templateIndex = ["None", "Triangle"]

   override func awakeFromNib() {
       super.awakeFromNib()

       cardView.clipToBounds = true

       let backColorObject = UserDefaults.standard.object(forKey: "backGroundColor") as? String
       let textColorObject = UserDefaults.standard.object(forKey: "textColor") as? String
       let templateColorObject = UserDefaults.standard.object(forKey: "templateColor") as? String
       let templateImageObject = UserDefaults.standard.object(forKey: "templateImage") as? String

       for _ in templateIndex {
           if templateImageObject == templateIndex[1] {
               templateImage.isHidden = false
               templateImage.image = UIImage(named: "test_triangle.png")
               //testLBL.bringSubview(toFront: templateImage)
               templateImage.bringSubview(toFront: testLBL)
           } else if templateImageObject == templateIndex[0] {
               templateImage.isHidden = true
           } else {
               templateImage.isHidden = true
           }
       }
</code>```

I'm Still pretty new to using swift so any help at all would be greatly appreciated, thank you.

答:
You need to ask testLBL's superview to bring it to the front. Your code templateImage.bringSubview(toFront: testLBL) won't work if templateImage is not the parent view of testLBL because testLBL is not in templateImage's view hierarchy.

So try to use the superview of testLBL

```<code><testLBL's parent view>.bringSubview(toFront: testLBL)
</code>```

or

```<code>testLBL.parentView.bringSubview(toFront: testLBL)
</code>```

Hope it solves your problem

Body:
So I am trying to give the user the ability to design their own virtual business card where the user can drag a label around the UIView, they can change background color of the UIView, as well as the color of the UILabel.  The card itself is represented by a nib and the user selects the different color choices or template image choices through a UIPickerView.  I want the Label to appear on top of the Image when it appears and is dragged to that part of the View, however it is not currently doing that.  Changing colors of the background for the UIView and the text work just fine; I am also able to add and remove the Template image (which is a PNG) by using .isHidden().

My Problem is that when the UIImage is added to the UIView it is on top of the UILabel.  If part of the UILabel overlaps with part of the png image it disappears behind it, and I would like it to appear over the image.

The code for the nib is in userCardView.swift and the picker view is on the mainViewController where I set the UserDefaults which works fine.

class userCardView: UIView {

   @IBOutlet var cardView: UIView!
   @IBOutlet weak var testLBL: UILabel!
   @IBOutlet weak var templateImage: UIImageView!

   var colorIndex = ["Black", "White", "Gray"]
   var templateIndex = ["None", "Triangle"]

   override func awakeFromNib() {
       super.awakeFromNib()

       cardView.clipToBounds = true

       let backColorObject = UserDefaults.standard.object(forKey: "backGroundColor") as? String
       let textColorObject = UserDefaults.standard.object(forKey: "textColor") as? String
       let templateColorObject = UserDefaults.standard.object(forKey: "templateColor") as? String
       let templateImageObject = UserDefaults.standard.object(forKey: "templateImage") as? String

       for _ in templateIndex {
           if templateImageObject == templateIndex[1] {
               templateImage.isHidden = false
               templateImage.image = UIImage(named: "test_triangle.png")
               //testLBL.bringSubview(toFront: templateImage)
               templateImage.bringSubview(toFront: testLBL)
           } else if templateImageObject == templateIndex[0] {
               templateImage.isHidden = true
           } else {
               templateImage.isHidden = true
           }
       }

I'm Still pretty new to using swift so any help at all would be greatly appreciated, thank you.

Body:
You need to ask testLBL's superview to bring it to the front. Your code templateImage.bringSubview(toFront: testLBL) won't work if templateImage is not the parent view of testLBL because testLBL is not in templateImage's view hierarchy.

So try to use the superview of testLBL

<testLBL's parent view>.bringSubview(toFront: testLBL)

or

testLBL.parentView.bringSubview(toFront: testLBL)

Hope it solves your problem


问:
DataTemplate doesn't properly bind the properties as specified
I have the following DataTemplate in DataTemplates.xaml

```<code><DataTemplate DataType="{x:Type local:ExcelReportVM}">
    <local:ExcelReport DoubleClickHandler="{Binding}">
        <local:ExcelReport.RowColorConverter>
            <local:ReportRowColorConverter/>
        </local:ExcelReport.RowColorConverter>
    </local:ExcelReport>
</DataTemplate>
</code>```

I make sure that this DataTemplate is usable within the application scope via the following App.xaml definition:

```<code><Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="DataTemplates.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
</code>```

And this is my control ExcelReport.xaml:

```<code><UserControl x:Class="WpfApplication1.ExcelReport"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              ....
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <TextBlock TextAlignment="Center" Text="{Binding .}" TextWrapping="WrapWithOverflow" />
        </DataTemplate>

    </UserControl.Resources>
    <UserControl.DataContext>
        <local:ExcelReportVM/>
    </UserControl.DataContext>
    <syncfusion:SfDataGrid ItemsSource="{Binding Entries}" x:Name="grid" Background="White"
                           HeaderTemplate="{StaticResource HeaderTemplate}"

                           SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=UserControl}}">
    </syncfusion:SfDataGrid>
</UserControl>
</code>```

My code behind: ExcelReport.xaml.cs

```<code>   public partial class ExcelReport : UserControl
    {

  public static readonly DependencyProperty RowColorConverterProperty = DependencyProperty.Register(
              "RowColorConverter",
              typeof(IValueConverter),
              typeof(ExcelReport),
              new FrameworkPropertyMetadata(new PropertyChangedCallback(OnRowColorConverterChanged))
            );

    public IValueConverter RowColorConverter
        {
            get { return (IValueConverter)GetValue(RowColorConverterProperty); }
            set { SetValue(RowColorConverterProperty, value); }
        }

   public ExcelReport()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
        }

 private void OnLoaded(object sender, RoutedEventArgs e)
{
    Debug.Assert(DataContext.GetType()==typeof(ExcelReportVM)); //DataContext is correct
    Debug.Assert(RowColorConverter!=null); //but this is null
  }
}
</code>```

I've no idea why I can successfully bind the DataContext, but the <DataTemplate DataType="{x:Type local:ExcelReportVM}"> that I define is not used, I thought everything inside the DataTemplates.xaml is accessible to ExcelReport.xaml?

Note: There is no error in the output window, and there is no exception been thrown anywhere in the code.

答: If it is a ContentControl, then you have to set its Content as <ContentControl Content="{Binding SomeProperty}"/> , then based on DataType of SomeProperty correct DataTemplate is picked up.

Body:
I have the following DataTemplate in DataTemplates.xaml

<DataTemplate DataType="{x:Type local:ExcelReportVM}">
    <local:ExcelReport DoubleClickHandler="{Binding}">
        <local:ExcelReport.RowColorConverter>
            <local:ReportRowColorConverter/>
        </local:ExcelReport.RowColorConverter>
    </local:ExcelReport>
</DataTemplate>

I make sure that this DataTemplate is usable within the application scope via the following App.xaml definition:

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="DataTemplates.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

And this is my control ExcelReport.xaml:

<UserControl x:Class="WpfApplication1.ExcelReport"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              ....
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <TextBlock TextAlignment="Center" Text="{Binding .}" TextWrapping="WrapWithOverflow" />
        </DataTemplate>

    </UserControl.Resources>
    <UserControl.DataContext>
        <local:ExcelReportVM/>
    </UserControl.DataContext>
    <syncfusion:SfDataGrid ItemsSource="{Binding Entries}" x:Name="grid" Background="White"
                           HeaderTemplate="{StaticResource HeaderTemplate}"

                           SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=UserControl}}">
    </syncfusion:SfDataGrid>
</UserControl>

My code behind: ExcelReport.xaml.cs

   public partial class ExcelReport : UserControl
    {

  public static readonly DependencyProperty RowColorConverterProperty = DependencyProperty.Register(
              "RowColorConverter",
              typeof(IValueConverter),
              typeof(ExcelReport),
              new FrameworkPropertyMetadata(new PropertyChangedCallback(OnRowColorConverterChanged))
            );

    public IValueConverter RowColorConverter
        {
            get { return (IValueConverter)GetValue(RowColorConverterProperty); }
            set { SetValue(RowColorConverterProperty, value); }
        }

   public ExcelReport()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
        }

 private void OnLoaded(object sender, RoutedEventArgs e)
{
    Debug.Assert(DataContext.GetType()==typeof(ExcelReportVM)); //DataContext is correct
    Debug.Assert(RowColorConverter!=null); //but this is null
  }
}

I've no idea why I can successfully bind the DataContext, but the <DataTemplate DataType="{x:Type local:ExcelReportVM}"> that I define is not used, I thought everything inside the DataTemplates.xaml is accessible to ExcelReport.xaml?

Note: There is no error in the output window, and there is no exception been thrown anywhere in the code.


问:
I'm getting NoSuchElement exception error
I have shared the below code please let me know the correction

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}
</code>```

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

答:
as @Guy pointed out, you try to access 3 different classes and thus cannot use the By.className method with all classes.

I think Guy had the right approach, but it works only if your use-case is exactly like Guy understood it to be

What is your use-case?

Do you want to access all elements that are either class lst, lst-tbb or sbibps OR

Do you want to access all elements that are of all 3 classes lst, lst-tbb or sbibps OR

Do you want to access all elements that are of class sbibps, which is a subclass of lst-tbb, which is a subclass of lst (i.e. .lst.lst-tbb.sbibps)

Solutions

for the first use-case this should suffice(see Selenium Webdriver w/Java: locating elements with multiple class names with one command)

driver.findElements(By.cssSelector(".lst,.lst-tbb,.sbibps");

for the second use-case I found this(see Find div element by multiple class names?)

driver.findElements(By.xpath("//*[@class='lst lst-tbb sbibps]"));

or this, if you don't know if it has more classes

driver.findElements(By.xpath("//*[contains(@class, 'lst lst-tbb sbibps')]"));

for the last use-case this should work(credit to @Guy)

driver.findElements(By.cssSelector(".lst.lst-tbb.sbibps"));

Attention! I used the findElements method and not the findElement method, it results in a List and doesn't throw an exception, rather the list is just empty if the condition is not met.

Also:
see Need to find element in selenium by css for reference

Body:
I have shared the below code please let me know the correction

import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds


问:
Fill a ListView from Postgres Database in WPF C#
I'm using WPF C# Visual Studio 2012. I have a Listview in my xaml like:

```<code><ListView
    Name="listview"
    Grid.Column="0"
    Grid.ColumnSpan="2"
    Grid.Row="1"
    Grid.RowSpan="15"
    Margin="5"
    BorderThickness="0"
    Background="WhiteSmoke">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn
                    Header="column1"
                    DisplayMemberBinding="{Binding path}" />
                <!--other path-->
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>
</code>```

The code behind to fill this Listview (in xaml.cs):

```<code>NpgsqlConnection connection = new NpgsqlConnection("Server = " + myModule.Server + ";Port = " + myModule.Port + ";User ID = " + myModule.UserID + ";Password = " + myModule.Password + ";Database = " + myModule.Database);
connection.Open();
NpgsqlCommand command = new NpgsqlCommand("select * from tblstudents_secure order by stud_id ASC", connection);

command.Connection = connection;
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command);

DataSet ds=new DataSet ();
adapter.Fill(ds);
listview.ItemsSource = ds.Tables[0].DefaultView;
</code>```

When I run my program, I know that it fills the listview because I can see it's rows when I hover my mouse on that, but I cannot see any text on those rows!

What did I miss?

答:
I found this solution:

In my XAML:

```<code><ListView
    Margin="10"
    Name="lvDataBinding">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Student Number" Width="100" DisplayMemberBinding="{Binding list_studid}" />
            <GridViewColumn Header="First Name" Width="100" DisplayMemberBinding="{Binding list_studfname}" />
            <GridViewColumn Header="Middle Name" Width="100" DisplayMemberBinding="{Binding list_studmname}" />
            <GridViewColumn Header="Last Name" Width="100" DisplayMemberBinding="{Binding list_studlname}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

In my xaml.cs:

```<code>public class User
{
    public string list_studid { get; set; }
    public string list_studfname { get; set; }
    public string list_studmname { get; set; }
    public string list_studlname { get; set; }
}

public void cmdSearch_Click(object sender, RoutedEventArgs e)
{
    NpgsqlConnection iConnect = new NpgsqlConnection
                                    ("Server = " + myModule.Server + ";
                                      Port = " + myModule.Port + ";
                                      User ID = " + myModule.UserID + ";
                                      Password = " + myModule.Password + ";
                                      Database = " + myModule.Database);
    iConnect.Open();
    NpgsqlCommand iQuery = new NpgsqlCommand("Select * from tblstudents_secure", iConnect);
    iQuery.Connection = iConnect;
    NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

    DataSet iDataSet = new DataSet();
    iAdapter.Fill(iDataSet, "LIST");

    int lstCount = iDataSet.Tables["LIST"].Rows.Count;//lstCount holds the total count of the list from database

    int i = 0;//used as counter
    List<User> items = new List<User>();
    while (lstCount > i)
    {

        items.Add(new User()
        {
            list_studid = iDataSet.Tables["LIST"].Rows[i]["stud_id"].ToString(),
            list_studfname = iDataSet.Tables["LIST"].Rows[i]["stud_fname"].ToString(),
            list_studmname = iDataSet.Tables["LIST"].Rows[i]["stud_mname"].ToString(),
            list_studlname = iDataSet.Tables["LIST"].Rows[i]["stud_lname"].ToString()
        });

        lvDataBinding.ItemsSource = items;//lvDataBinding is the name of my ListView

        i++;
    }
}
</code>```

Explanation:

In my design (XAML), the DisplayMemberBinding property of the GridViewColumn holds the Binding List, which from code behind is list_studid, list_studfname, list_studmname, list_studlname. Now, we have a "catcher" on our design, we set the "thrower" from our code behind.

The public class User holds and initializes the binding list – list_studid, list_studfname, etc.

Upon user CLICK on my button (cmdSearch), we call the database, open it, perform select query, fill it into the dataset, and loop until the end of the list.

Now the "thrower" starts on the loop, including the List<User> items = new List<User>(); . While looping, the list_studid, etc. holds the data from the database (list_studid = iDataSet.Tables["LIST"].Rows[i]["stud_id"].ToString()) and converts it to string (.ToString()).

Then we "throw" it to the listview in lvDataBinding.ItemsSource = items;. And as I have said, the design (XAML) "catches" this "throw", and loads it to the listview.

Body:
I'm using WPF C# Visual Studio 2012. I have a Listview in my xaml like:

<ListView
    Name="listview"
    Grid.Column="0"
    Grid.ColumnSpan="2"
    Grid.Row="1"
    Grid.RowSpan="15"
    Margin="5"
    BorderThickness="0"
    Background="WhiteSmoke">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn
                    Header="column1"
                    DisplayMemberBinding="{Binding path}" />

            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

The code behind to fill this Listview (in xaml.cs):

NpgsqlConnection connection = new NpgsqlConnection("Server = " + myModule.Server + ";Port = " + myModule.Port + ";User ID = " + myModule.UserID + ";Password = " + myModule.Password + ";Database = " + myModule.Database);
connection.Open();
NpgsqlCommand command = new NpgsqlCommand("select * from tblstudents_secure order by stud_id ASC", connection);

command.Connection = connection;
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command);

DataSet ds=new DataSet ();
adapter.Fill(ds);
listview.ItemsSource = ds.Tables[0].DefaultView;

When I run my program, I know that it fills the listview because I can see it's rows when I hover my mouse on that, but I cannot see any text on those rows!

What did I miss?

Body:
I found this solution:

In my XAML:

<ListView
    Margin="10"
    Name="lvDataBinding">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Student Number" Width="100" DisplayMemberBinding="{Binding list_studid}" />
            <GridViewColumn Header="First Name" Width="100" DisplayMemberBinding="{Binding list_studfname}" />
            <GridViewColumn Header="Middle Name" Width="100" DisplayMemberBinding="{Binding list_studmname}" />
            <GridViewColumn Header="Last Name" Width="100" DisplayMemberBinding="{Binding list_studlname}" />
        </GridView>
    </ListView.View>
</ListView>

In my xaml.cs:

public class User
{
    public string list_studid { get; set; }
    public string list_studfname { get; set; }
    public string list_studmname { get; set; }
    public string list_studlname { get; set; }
}

public void cmdSearch_Click(object sender, RoutedEventArgs e)
{
    NpgsqlConnection iConnect = new NpgsqlConnection
                                    ("Server = " + myModule.Server + ";
                                      Port = " + myModule.Port + ";
                                      User ID = " + myModule.UserID + ";
                                      Password = " + myModule.Password + ";
                                      Database = " + myModule.Database);
    iConnect.Open();
    NpgsqlCommand iQuery = new NpgsqlCommand("Select * from tblstudents_secure", iConnect);
    iQuery.Connection = iConnect;
    NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

    DataSet iDataSet = new DataSet();
    iAdapter.Fill(iDataSet, "LIST");

    int lstCount = iDataSet.Tables["LIST"].Rows.Count;//lstCount holds the total count of the list from database

    int i = 0;//used as counter
    List<User> items = new List<User>();
    while (lstCount > i)
    {

        items.Add(new User()
        {
            list_studid = iDataSet.Tables["LIST"].Rows[i]["stud_id"].ToString(),
            list_studfname = iDataSet.Tables["LIST"].Rows[i]["stud_fname"].ToString(),
            list_studmname = iDataSet.Tables["LIST"].Rows[i]["stud_mname"].ToString(),
            list_studlname = iDataSet.Tables["LIST"].Rows[i]["stud_lname"].ToString()
        });

        lvDataBinding.ItemsSource = items;//lvDataBinding is the name of my ListView

        i++;
    }
}

Explanation:

In my design (XAML), the DisplayMemberBinding property of the GridViewColumn holds the Binding List, which from code behind is list_studid, list_studfname, list_studmname, list_studlname. Now, we have a "catcher" on our design, we set the "thrower" from our code behind.

The public class User holds and initializes the binding list – list_studid, list_studfname, etc.

Upon user CLICK on my button (cmdSearch), we call the database, open it, perform select query, fill it into the dataset, and loop until the end of the list.

Now the "thrower" starts on the loop, including the List<User> items = new List<User>(); . While looping, the list_studid, etc. holds the data from the database (list_studid = iDataSet.Tables["LIST"].Rows[i]["stud_id"].ToString()) and converts it to string (.ToString()).

Then we "throw" it to the listview in lvDataBinding.ItemsSource = items;. And as I have said, the design (XAML) "catches" this "throw", and loads it to the listview.


问:
How do I convert the time stamps from a PostgreSQL DB into user-time-zone times?
I'm using SQLAlchemy and PostgreSQL here, in a web application.

My SQLA model is defined (roughly) as follows:

```<code>class MyModel(Base):
    ts_field = Column(DateTime(timezone=True))
    # more here, obviously
</code>```

My web app users have a timezone property whose format I have not yet specified (that's part of this question) that determines how to display time stamps to them. They're not all in the locale of the server, obviously, so the system time zone isn't exactly useful.

I want to have an easy way to get out timestamps formatted for each user depending on their selected time zone.

(I'm a bit fuzzy on a lot of the terminology of time zone conversion, so if I'm asking this vaguely -- and I'll bet I am! -- please feel free to comment and help me clarify!)

答:
OK, when you create a timestamp with timezone (shortcut name timestamptz) pg creates a timestamp, and converts between the current timezone to GMT when storing it.

When you pull it out, you change the timezone setting to whatever you want to change it to some other offset.  For example:

```<code> smarlowe=# set timezone='est';
 SET
 smarlowe=# select now();
               now
 2010-11-30 00:38:32.683625-05
 (1 row)

 smarlowe=# set timezone='mst';
 SET
 smarlowe=# select now();
               now
 2010-11-29 22:38:48.293708-07
</code>```

You can shorten this up by using "at time zone" nomenclature:

```<code>smarlowe=# set timezone='mst';
SET
smarlowe=# select now();
              now
-------------------------------
 2010-11-29 22:40:15.854833-07
(1 row)

smarlowe=# select now() at time zone 'est';
          timezone
----------------------------
 2010-11-30 00:40:17.243828
</code>```

no need to set each time zone over and over, just in the statement each time according to the proper timezone.

Body:
I'm using SQLAlchemy and PostgreSQL here, in a web application.

My SQLA model is defined (roughly) as follows:

class MyModel(Base):
    ts_field = Column(DateTime(timezone=True))
    # more here, obviously

My web app users have a timezone property whose format I have not yet specified (that's part of this question) that determines how to display time stamps to them. They're not all in the locale of the server, obviously, so the system time zone isn't exactly useful.

I want to have an easy way to get out timestamps formatted for each user depending on their selected time zone.

(I'm a bit fuzzy on a lot of the terminology of time zone conversion, so if I'm asking this vaguely -- and I'll bet I am! -- please feel free to comment and help me clarify!)

Body:
OK, when you create a timestamp with timezone (shortcut name timestamptz) pg creates a timestamp, and converts between the current timezone to GMT when storing it.

When you pull it out, you change the timezone setting to whatever you want to change it to some other offset.  For example:

 smarlowe=# set timezone='est';
 SET
 smarlowe=# select now();
               now
 2010-11-30 00:38:32.683625-05
 (1 row)

 smarlowe=# set timezone='mst';
 SET
 smarlowe=# select now();
               now
 2010-11-29 22:38:48.293708-07

You can shorten this up by using "at time zone" nomenclature:

smarlowe=# set timezone='mst';
SET
smarlowe=# select now();
              now
-------------------------------
 2010-11-29 22:40:15.854833-07
(1 row)

smarlowe=# select now() at time zone 'est';
          timezone
----------------------------
 2010-11-30 00:40:17.243828

no need to set each time zone over and over, just in the statement each time according to the proper timezone.


问:
MVC Razor Engine Renderpartial View From Custom Location and also need to support fallback search location
I need to render the Partial view from Custom Locations but also want to support the fallback search location if custom location not found. How do I achieve this in MVC5.

```<code>@HTML.Partial("~/Parent/Child1/1.cshtml")
</code>```

If it found here then OK. But if not then it should search in default location.

```<code>@HTML.Partial("~/Parent/Default/1.cshtml")
</code>```

I did some thing like this but not works.

```<code>  var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().First();
        razorEngine.ViewLocationFormats = razorEngine.ViewLocationFormats.Concat(new string[]
        {
            "~/Parent/Default/{0}.cshtml"
        }).ToArray();
        razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Concat(new string[]
        {
            "~/Parent/Default/{0}.cshtml"
        }).ToArray();
</code>```

答:
I solved it by overriding the FindPartialView method of RazorViewEngine.
Here is my solution that works for me.</p>

```<code>public class CustomeViewEngine : RazorViewEngine
{
    public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
    {
        ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext, partialViewName, null);

        if (result.View == null && partialViewName.StartsWith("~/Parent"))
        {
            var pathArr = partialViewName.Split('/');
            pathArr[pathArr.Length - 2] = "Default";
            partialViewName = string.Join("/", pathArr);
        }
        else
        {
            return result;
        }
        return base.FindPartialView(controllerContext, partialViewName, useCache);
    }
}
</code>```

Body:
I need to render the Partial view from Custom Locations but also want to support the fallback search location if custom location not found. How do I achieve this in MVC5.

@HTML.Partial("~/Parent/Child1/1.cshtml")

If it found here then OK. But if not then it should search in default location.

@HTML.Partial("~/Parent/Default/1.cshtml")

I did some thing like this but not works.

  var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().First();
        razorEngine.ViewLocationFormats = razorEngine.ViewLocationFormats.Concat(new string[]
        {
            "~/Parent/Default/{0}.cshtml"
        }).ToArray();
        razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Concat(new string[]
        {
            "~/Parent/Default/{0}.cshtml"
        }).ToArray();

Body:
I solved it by overriding the FindPartialView method of RazorViewEngine.
Here is my solution that works for me.

public class CustomeViewEngine : RazorViewEngine
{
    public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
    {
        ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext, partialViewName, null);

        if (result.View == null && partialViewName.StartsWith("~/Parent"))
        {
            var pathArr = partialViewName.Split('/');
            pathArr[pathArr.Length - 2] = "Default";
            partialViewName = string.Join("/", pathArr);
        }
        else
        {
            return result;
        }
        return base.FindPartialView(controllerContext, partialViewName, useCache);
    }
}


问:
jquery update total based on checkboxes
I have a form where based on checkbox total value will be updated

Here is my form

```<code><label class="checkbox">
        <input type="checkbox" class="check" value="23">SEO
    </label>
    <label class="checkbox">
        <input type="checkbox" class="check" value="34">XYZ
    </label>
    <label class="checkbox">
            <input type="checkbox" class="check" value="45">Logo Design
    </label>

    <span class="product-price" id="total" >45</span>
</code>```

jQuery I have used

```<code>  $('input[type=checkbox]').change(function () {
        var val = parseFloat(this.value),
            totalVal = parseFloat($('#total').val());
        if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }
    });
</code>```

But nothing get updated.What could be the possible Error?
Any solution please

答:
Simply do with Array#map function .simply add with checked values only on each time check or uncheck .no need subtraction for below method

$('input[type=checkbox]').change(function() {
var tot=0;
$('input:checked').map(function(a){
 tot += parseInt($(this).val())
})
  $('#total').val(tot.toFixed(2));

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<label class="checkbox">
        <input type="checkbox" class="check" value="23">SEO
    </label>
<label class="checkbox">
        <input type="checkbox" class="check" value="34">XYZ
    </label>
<label class="checkbox">
            <input type="checkbox" class="check" value="45">Logo Design
    </label>
    <input id="total"></code>```

Title: jquery update total based on checkboxes

Body:
I have a form where based on checkbox total value will be updated

Here is my form

        <input type="checkbox" class="check" value="23">SEO

        <input type="checkbox" class="check" value="34">XYZ

            <input type="checkbox" class="check" value="45">Logo Design

    45

jQuery I have used

  $('input[type=checkbox]').change(function () {
        var val = parseFloat(this.value),
            totalVal = parseFloat($('#total').val());
        if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }
    });

But nothing get updated.What could be the possible Error?
Any solution please

Body:
Simply do with Array#map function .simply add with checked values only on each time check or uncheck .no need subtraction for below method

$('input[type=checkbox]').change(function() {
var tot=0;
$('input:checked').map(function(a){
 tot += parseInt($(this).val())
})
  $('#total').val(tot.toFixed(2));

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<label class="checkbox">
        <input type="checkbox" class="check" value="23">SEO
    </label>
<label class="checkbox">
        <input type="checkbox" class="check" value="34">XYZ
    </label>
<label class="checkbox">
            <input type="checkbox" class="check" value="45">Logo Design
    </label>
    <input id="total">


问:
CodeIgniter: removing 'index.php' from URL
I have answered this question previously and even posted the answer to it by myself. I tried most of the answered questions, but it still didn't work. The first question is regarding placement of the .htaccess file, should I keep it with application folder or inside it? and the next question is 'How should I remove the index.php from URL'?

.htaccess code:

```<code>RewriteEngine On
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

Config.php code:

```<code>$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
</code>```

and if possible do also suggest a detailed tutorial regarding how to customize TankAuth or any other authentication library which can be easier. I am using Windows 8.1 and Wamp Server.

Any suggestion or help is appreciated.

答:
it works on me, I use v2.2.6 by the way

Create .htacccess on the same dir as your index.php

Modify index_page and base_url value in /application/config/config.php

here is what it looks like

picture image link

Body:
I have answered this question previously and even posted the answer to it by myself. I tried most of the answered questions, but it still didn't work. The first question is regarding placement of the .htaccess file, should I keep it with application folder or inside it? and the next question is 'How should I remove the index.php from URL'?

.htaccess code:

RewriteEngine On
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Config.php code:

$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

and if possible do also suggest a detailed tutorial regarding how to customize TankAuth or any other authentication library which can be easier. I am using Windows 8.1 and Wamp Server.

Any suggestion or help is appreciated.