I'm having a page that contains several dropdownlists, all filled with the same values. I would like to compare them on the client as well as on the server side.
The problem is though, that the dropdownlists are generated dynamically because their quantity can vary.
Client side comparing:
<script type="text/javascript">
function CompareSelectedValues(dropDown1ID, dropDown2ID) {
var DropDownList1 = document.getElementById(dropDown1ID);
var DropDownList2 = document.getElementById(dropDown2ID);
if (DropDownList1.selectedIndex != -1 && DropDownList2.selectedIndex != -1) {
if (DropDownList1.options[DropDownList1.selectedIndex].value != DropDownList2.options[DropDownList2.selectedIndex].value)
alert('not same');
}
}
</script>
Classic server side comparing with C#:
private bool AreDropDownListValuesEqual(DropDownList ddlist1, DropDownList ddlist2)
{
// Check for invalid input or different number of items for early return
if (ddlist1 == null || ddlist2 == null || ddlist1.Items.Count != ddlist2.Items.Count)
{
return false;
}
// Check items one by one. We need a nested loop because the list could be sorted differently while having the same values!
foreach (ListItem outerItem in ddlist1.Items)
{
bool hasMatch = false;
foreach (ListItem innerItem in ddlist2.Items)
{
if (innerItem.Value == outerItem.Value && innerItem.Text == outerItem.Text)
{
hasMatch = true;
break;
}
}
if (!hasMatch)
{
return false;
}
}
// All items from ddlist1 had a match in ddlist2 and we know that the number of items is equal, so the 2 dropdownlist are matching!
return true;
}
What kind of comparison do you need? If you don't keep them in a List and that list in Session, you can never do anything with them since you add them dynamically. Add your dropdownlists where you create them (this should me when Page.IsPostBack == false) and keep that list in session. On postbacks, load your dropdowns from the list. You can compare them using the list you keep.
Related
I have a list of states, which are defined to be ordered by min to max. the sequence is the following:
Cancelled - complete - draft - reservation - reserved - ordered - confirmed
So the cancelled is the minimum state, and confirmed is the maximum state. I may have different instances with different states, so I use a for-each loop to run through all states, and select the minimum state present in the loop.
That is: if in a list I have states [complete, reserved, draft, ordered] I need to check all the values and select complete -as it appears to be the minimum state. OR
if I have [reserved, confirmed, ordered, draft, cancelled, confirmed, confirmed] I need to select the cancelled value, as it appears to be the minimum.
I am doing the following check, but it does not seem to be working:
string globstatus = " ";
foreach (var currentstatus in list)
{
if (currentstatus == "cancelled")
{
globstatus = "cancelled";
}
else
{
if (globstatus == "cancelled")
{
return globstatus;
}
else
{
if (currentstatus == "complete")
{
globstatus = "complete";
}
else
{
if (globstatus == "complete")
{
return globstatus;
}
else
{
if (currentstatus == "draft")
{
globstatus = "draft";
}
else
{
if (globstatus == "reservation")
{
return globstatus;
}
else
{
if (currentstatus == "reserved")
{
globstatus = "reserved";
}
else
{
if (globstatus == "ordered")
{
return globstatus;
}
else
{
if (currentstatus == "confirmed")
{
globstatus = "confirmed";
}
else
{
return currentstatus;
}
}
}
}
}
}
}
}
}
}
return globstatus;
What can be the best solution to achieve the desired behavior?
I find a rule of thumb helpful that if I need more than three levels of braces, I need to rethink my code. It's hard to follow, easy to make mistakes, and a nightmare to debug. I suggest that applies here - trying to follow the flow of what all those nested if..else statements is extremely difficult.
Using Enum
My preferred solution is to achieve this using an Enum, e.g.:
var list = new List<Status>
{
Status.Complete,
Status.Draft,
Status.Draft,
Status.Confirmed
};
var minStatus = (Status)list.Select(l => (int)l).Min();
// minStatus = Status.Complete
public enum Status
{
Cancelled,
Complete,
Draft,
Reservation,
Reserved,
Ordered,
Confirmed
}
How it works: by default Enums give each value a zero-based integer, i.e. Cancelled = 0, Complete = 1 and so on. You can override this with your own values if you wish (e.g. 1/2/4/8/16 if you want to combine multiple values).
I recommend using Enum types for things like this, rather than strings. It helps avoid typos, gives someone else looking at your code a clear understanding of how your program works and its flow, and represents hierarchy in a way in which simple strings don't. (For example - does 'complete' come before or after 'draft'? Without context, I imagine most people would say after, but in this case it comes before - that is much more obvious when using an Enum.)
Parse strings to Enum
However if the statuses have to be strings, you could parse them into an enum like so:
var stringList = new List<string>
{
"complete",
"draft",
"draft",
"confirmed",
"this will be ignored"
};
var statusList = new List<int>();
foreach (var str in stringList)
{
if(Enum.TryParse(typeof(Status), str, ignoreCase: true, out object? parsed) && parsed is Status status)
{
statusList.Add((int)status);
}
}
var minStatus = (Status)statusList.Min();
// minStatus = Status.Complete
However, if it's possible to refactor your code to use the Enum in the first place, that would be a better solution, and much quicker as parsing strings has an overhead that would be good to avoid.
I have a list of items and I want to edit its values before using it. I am using the map function to update each item in it. But the catch here is, I want to only update the items when the list size is 1. I want to return the list as it is if the size is larger than 1. How can I achieve this?
myList.map {
if(resources.getBoolean(R.bool.is_tablet) && it.itemList.size<6 && it.layerType == DOUBLE_LIST) {
it.layerType = SINGLE_LIST_AUTO
it.itemList.forEach {sectionItem->
sectionItem.layerType = SINGLE_LIST_AUTO
}
it
}else{
it
}
}
You can try using filter before map:
.filter { it.itemList.size == 1 }
I am assuming you want to modify the items in your list only if some conditions are met else return the same list unmodified.
You can consider using takeIf { } for this scenario if you desire to add some syntactic sugar
fun updateItemsInMyList(myList:List<SomeClass>): List<SomeClass> {
return myList
.takeIf {
// condition to modify items in your list
it.size > 1 && otherConditions
}
?.apply {
//update your items inside the list
}
?: myList // return the unmodified list if conditions are not met
}
If I understand your question correctly, you want to check if myList contains only one value else, you want update the values and return it. You could do something along the following lines,
myList.singleOrNull ?: myList.map {
if(resources.getBoolean(R.bool.is_tablet) && it.itemList.size<6 && it.layerType == DOUBLE_LIST) {
it.layerType = SINGLE_LIST_AUTO
it.itemList.forEach {sectionItem->
sectionItem.layerType = SINGLE_LIST_AUTO
}
it
}else{
it
}
}
return myList
Basically, check if there's only a single value in the list, if so, then return the value. In the case that there isn't (you get null), then you can map the value.
I am trying to read Excel file through apache poi. In a column I am having the data `"9780547692289". After iterating all the columns, in the output, the number is displaying like this "9.780547692289E12". I mean number changed automatically to the string(because it has'E'). I have to keep this as number only(as it is). What should I do..?
It is probably just a display setting. The "E" is just for scientific notation for displaying the number.
//while getting values from excel u can use this method
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + "";
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + "";
}
else {
return null;
}
}
This worked for me
if (cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA )
{
int i = (int)cell.getNumericCellValue();
String cellText = String.valueOf(i);
}
I've got a flat list of items in a ObservableCollection. These items have the properties item.Id and item.Parent.Id.
I've been given the id of the parent (top level), now with this id I need to iterate through the list and find the children of this parent. Each child can only have one parent, a parent can have multiple childs.
How can I do this effectively?
You can use:
var childrenOfParent = theCollection.Where(item => item.Parent.Id == parentId);
Edit in response to comments:
Given that you have a hierarchical dataset, I would personally make a routine that checks to see if a given item has a specific item as a parent recursively, like so:
bool HasParent(Item item, int parentId)
{
if (item.Parent == null)
return false;
else if (item.Parent.Id == parentId)
return true;
else
return HasParent(item.Parent, parentId);
}
Given this, you could use:
var childrenOfParent = theCollection.Where(item => HasParnet(item, parentId));
Well I got it, however, if anyone can optimize/refactor this code into something more efficient please let me know and I'll mark your reaction as an answer. As long as I learn :).
foreach (var item in myitemlist) // first put the top level parent in the queue
{
if (parentitem.Id == item.Id)
{
filteredChildrenQueue.Enqueue(item);
}
}
while (!stillsearching)
{
if (filteredChildrenQueue.Count == 0)
{
stillsearching = true;
return;
}
FindParentChild();
}
Keep calling this method and work the first item in the queue
private void FindParentChild()
{
foreach (var item in myitemlist)
{
if (item.Parent.Id == filteredChildrenQueue.ElementAt(0).Id)
{
filteredChildrenQueue.Enqueue(item);
}
}
filteredChildrenList.Add(filteredChildrenQueue.ElementAt(0));
filteredChildrenQueue.Dequeue();
}
filteredChildrenList will contain the top level parent + all childs it contains.
I'm trying to write a chess game and find that I cannot find solutions to find a stalemate situation. I'm trying to google, but can't find anything. Is there a well-known algorithm or something?
Your move generator will be one of two different designs;
either it checks for legality while generating the moves
or you generate all possible moves and remove those that are illegal afterwards.
The former is better as it doesn't need post-processing.
A stalemate condition is simply one where there are no legal moves and the moving-side's king is not in check. A checkmate condition is one where there are no legal moves but the moving-side's king is in check.
In other words if you've figured out how to detect check and checkmate, you've already got everything necessary to detect stalemate.
Here is an Open-source code with all the rules for the classic Chess game:
https://github.com/cjortegon/basic-chess
You can run the project right after cloning the project (Android, iOS, Desktop and Web), or you can use the main logic, which is here: https://github.com/cjortegon/basic-chess/tree/master/libgdx/core/src/com/mountainreacher/chess/model
I based my solution on a 3-moments algorithm, first moment is when the player selects a piece from the board, then when the destination of this piece has been chosen and finally when the piece reaches that position (considering that it is an animated game, if not, you can merge step 2 and 3).
The following code has been implemented in Java. From the properties of the model class:
boolean turn;
GenericPiece selected, conquest;
ClassicBoard board;
List<int[]> possibleMovements;
int checkType;
The first method will handle moments 1, 2 and the special 'conquest' moment (applied to pawn piece only):
public boolean onCellClick(int row, int column) {
if (row == -1 && conquest != null) {
checkType = 0;
conquest.changeFigure(column);
return true;
} else if (selected != null) {
if (possibleMovements != null) {
for (int[] move : possibleMovements) {
if (move[0] == row && move[1] == column) {
// Move the PieceActor to the desired position
if (selected.moveTo(row, column)) {
turn = !turn;
}
break;
}
}
}
selected = null;
possibleMovements = null;
return true;
} else {
selected = board.getSelected(turn ? Piece.WHITE_TEAM : Piece.BLACK_TEAM, row, column);
if (selected != null) {
possibleMovements = new ArrayList<>();
possibleMovements.addAll(((GenericPiece) selected).getMoves(board, false));
// Checking the movements
board.checkPossibleMovements(selected, possibleMovements);
if (possibleMovements.size() == 0) {
possibleMovements = null;
selected = null;
return false;
} else {
return true;
}
}
}
return false;
}
And the following method will handle the 3rd moment (when animation finishes):
public void movedPiece(Piece piece) {
Gdx.app.log(TAG, "movedPiece(" + piece.getType() + ")");
// Killing the enemy
Piece killed = board.getSelectedNotInTeam(piece.getTeam(),
piece.getRow(), piece.getColumn());
if (killed != null) {
killed.setAvailable(false);
}
// Checking hacks
GenericPiece[] threat = board.kingIsInDanger();
if (threat != null) {
checkType = board.hasAvailableMoves(threat[0].getTeam()) ? CHECK : CHECK_MATE;
} else {
checkType = NO_CHECK;
}
// Checking castling
if (piece.getFigure() == Piece.ROOK && ((GenericPiece) piece).getMovesCount() == 1) {
Piece king = board.getSelected(piece.getTeam(),
piece.getRow(), piece.getColumn() + 1);
if (king != null && king.getFigure() == Piece.KING && ((GenericPiece) king).getMovesCount() == 0) {
// Left Rook
if (board.getSelected(piece.getRow(), piece.getColumn() - 1) == null) {
king.moveTo(piece.getRow(), piece.getColumn() - 1);
}
} else {
king = board.getSelected(piece.getTeam(),
piece.getRow(), piece.getColumn() - 1);
if (king != null && king.getFigure() == Piece.KING && ((GenericPiece) king).getMovesCount() == 0) {
// Right Rook
if (board.getSelected(piece.getRow(), piece.getColumn() + 1) == null) {
king.moveTo(piece.getRow(), piece.getColumn() + 1);
}
}
}
}
// Conquest
else if (piece.getFigure() == Piece.PAWN && (piece.getRow() == 0 || piece.getRow() == board.getRows() - 1)) {
conquest = (GenericPiece) piece;
checkType = CONQUEST;
}
}
That code covers all the rules from the classic chess, including: regular piece movements, castling, check, check-mate and conquests of pawns.