Apply borders in many cells openpyxl - border

I'm new, I want to know if you can help me I do not understand how to select multiple cells with openpyxl and apply a border,if you could please give me an example.Thanks

Now you can iterate directly in the worksheet. I adapted the code
def set_border(ws, cell_range):
rows = list(ws[cell_range])
side = Side(border_style='thin', color="FF000000")
rows = list(rows) # we convert iterator to list for simplicity, but it's not memory efficient solution
max_y = len(rows) - 1 # index of the last row
for pos_y, cells in enumerate(rows):
max_x = len(cells) - 1 # index of the last cell
for pos_x, cell in enumerate(cells):
border = Border(
left=cell.border.left,
right=cell.border.right,
top=cell.border.top,
bottom=cell.border.bottom
)
if pos_x == 0:
border.left = side
if pos_x == max_x:
border.right = side
if pos_y == 0:
border.top = side
if pos_y == max_y:
border.bottom = side
# set new border only if it's one of the edge cells
if pos_x == 0 or pos_x == max_x or pos_y == 0 or pos_y == max_y:
cell.border = border
And just call it like that:
set_border(ws, 'A16:I17')

property is called border (not borders)
Try this:
def set_border(ws, cell_range):
rows = list(ws.iter_rows(cell_range))
side = Side(border_style='thin', color="FF000000")
rows = list(rows) # we convert iterator to list for simplicity, but it's not memory efficient solution
max_y = len(rows) - 1 # index of the last row
for pos_y, cells in enumerate(rows):
max_x = len(cells) - 1 # index of the last cell
for pos_x, cell in enumerate(cells):
border = Border(
left=cell.border.left,
right=cell.border.right,
top=cell.border.top,
bottom=cell.border.bottom
)
if pos_x == 0:
border.left = side
if pos_x == max_x:
border.right = side
if pos_y == 0:
border.top = side
if pos_y == max_y:
border.bottom = side
# set new border only if it's one of the edge cells
if pos_x == 0 or pos_x == max_x or pos_y == 0 or pos_y == max_y:
cell.border = border

Related

Can't save data using push button (MATLAB)

I'm trying to create a figure where the user can select cells to turn on or off. Then, the user can click a button 'Enter' to save the board as an array. I successfully found a way to create interactivity in my plot thanks to a very useful explanation I found here. I just made some changes to suit my needs.
However, I can't find a way to save the board. The button is working (or at least isn't not working), but the data isn't saved. And I don't know how to fix that. Any help would be appreciated.
Here is my code:
function CreatePattern
hFigure = figure;
hAxes = axes;
axis equal;
axis off;
hold on;
% create a button to calculate the difference between 2 points
h = uicontrol('Position',[215 5 150 30],'String','Enter','Callback', #SaveArray);
function SaveArray(ButtonH, eventdata)
global initial
initial = Board;
close(hFigure)
end
N = 1; % for line width
M = 20; % board size
squareEdgeSize = 1;
% create the board of patch objects
hPatchObjects = zeros(M,M);
for j = M:-1:1
for k = 1:M
hPatchObjects(M - j+ 1, k) = rectangle('Position', [k*squareEdgeSize,j*squareEdgeSize,squareEdgeSize,squareEdgeSize], 'FaceColor', [0 0 0],...
'EdgeColor', 'w', 'LineWidth', N, 'HitTest', 'on', 'ButtonDownFcn', {#OnPatchPressedCallback, M - j+ 1, k});
end
end
%global Board
Board = zeros(M,M);
playerColours = [1 1 1; 0 0 0];
xlim([squareEdgeSize M*squareEdgeSize]);
ylim([squareEdgeSize M*squareEdgeSize]);
function OnPatchPressedCallback(hObject, eventdata, rowIndex, colIndex)
% change FaceColor to player colour
value = Board(rowIndex,colIndex);
if value == 1
set(hObject, 'FaceColor', playerColours(2, :));
Board(rowIndex,colIndex) = 0; % update board
else
set(hObject, 'FaceColor', playerColours(1, :));
Board(rowIndex,colIndex) = 1; % update board
end
end
end
%imwrite(~pattern,'custom_pattern.jpeg')

how to delete the same number of photos in mein dataset in python

Hi i use python and made a Dataframe of Food, which has 1000 photos for each food.
i wanna drop some pictures of food ex)ice_cream 100 pictures, omelette 100pictures... etc)
def get_df_from_file(path, is_valid):
img_df = pd.read_csv(path, delimiter='/', header=None, names=['label', 'name'])
# Append .jpg extension to all file names
img_df['name'] = img_df['label'].astype(str) + '/' + img_df['name'].astype(str) + '.jpg'
# Join extracted values and set is_valid
img_df['is_valid'] = is_valid
#img_df=img_df.loc[(img_df['label'] == 'ramen')]
return img_df
# Load the train set
train_df = get_df_from_file(path/'train.txt', False)
print(train_df.shape)
# Load the validation set
test_df = get_df_from_file(path/'test.txt', True)
print(test_df.shape)
# Concatenate train and test sets
image_df = pd.concat([train_df, test_df])
display(image_df.sample(10))
print(image_df.shape)
train_df0=train_df.loc[(train_df['label'] == df.label[0])]
drop_indices = np.random.choice(train_df0.index,50, replace=False)
train_df0 = train_df0.drop(drop_indices)
train_df1=train_df.loc[(train_df['label'] == df.label[1])]
drop_indices = np.random.choice(train_df1.index,50, replace=False)
train_df1 = train_df1.drop(drop_indices)
train_df2=train_df.loc[(train_df['label'] == df.label[2])]
drop_indices = np.random.choice(train_df2.index,50, replace=False)
train_df2 = train_df2.drop(drop_indices)
train_df3=train_df.loc[(train_df['label'] == df.label[3])]
drop_indices = np.random.choice(train_df3.index,50, replace=False)
train_df3 = train_df3.drop(drop_indices)
train_df4=train_df.loc[(train_df['label'] == df.label[4])]
drop_indices = np.random.choice(train_df4.index,50, replace=False)
train_df4 = train_df4.drop(drop_indices)
train_df5=train_df.loc[(train_df['label'] == df.label[5])]
drop_indices = np.random.choice(train_df5.index,50, replace=False)
train_df5 = train_df5.drop(drop_indices)
so 100 pictures each of 101category must be erased
i try to drop pictures of each dataframe but wenn i do this i should repeat this 100 times... how can i solve this problem with short syntax?

Getting warning message

I am trying to run this code:
x = 0
y = 0
newdata <- subset(data, subject_ids == 25773861)
for(i in newdata$classification_id){
if(newdata$value == "Yes"){
x = x + 1
} else {
y = y + 1
}
}
But keep getting this warning:
Warning messages:
1: In if (newdata$value_simple == 0) { :
the condition has length > 1 and only the first element will be used
2: In if (newdata$value_simple == 0) { :
the condition has length > 1 and only the first element will be used
Any advice or help in solving this?
The general code of
if(condition){
some code
}else{
some code}
only look at the first value in the vector. So it is basically warning you that it is only looking at the first value in the object newdata$value. I am assuming you are getting all in either x or y not a split like you would want.
The two things I would fix in that code, start at the first two lines of the for loop
x = 0
y = 0
newdata <- subset(data, subject_ids == 25773861)
for(i in seq_along(newdata$classification_id)){ #seq_along makes a vector 1 to the length of your vector
if(newdata$value[[i]] == "Yes"){ #This will subset the newdata$Value into single values
x = x + 1
} else {
y = y + 1
}
}
Another option is to use the tidyverse, assuming you have it installed
library(tidyverse)
data %>%
filter(subject_ids == 25773861) %>%
group_by(value) %>%
count()

When calling different functions in the same class, only the first function is ever called(Python) [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I'm having a bit of trouble with my class functions. On my class I have 3 different functions but whenever I call one of the functions outside of the class, it only ever calls the first one despite me typing in the correct function name.
This is the class below with the different functions, although I have only included two as I don't want you to have to search through lots of code.
class mage(baseclass):
def __init__(self, name, level, attack, defence, hp):
baseclass.__init__(self, name, level, hp)
self.attack = attack
self.defence = defence
def __str__(self):
return "You are now a Mage, your new stats are:\n Level: {0}\n Attack: {1}\n Defence: {2}\n HP: {3}".format(self.level, self.attack, self.defence, self.hp)
def flamevortex(self, x, y, z):
print("You used Flame Vortex")
time.sleep(1.5)
damageofmove = 3
damagedone = damageofmove*y
damagedoneafterdefence = damagedone - z
x = x - damagedoneafterdefence
print("The monster's health is now " + str(x))
time.sleep(1.5)
return x
def lightningbolt(self, x, y, z):
print("You used Lightning Bolt")
time.sleep(1.5)
damageofmove = 3
damagedone = damageofmove*y
damagedoneafterdefence = damagedone - z
x = x - damagedoneafterdefence
print("The monster's health is now " + str(x))
time.sleep(1.5)
return x
This is the place where I am calling the functions:
if Userattack.upper() == "FLAMEVORTEX" or "FLAME VORTEX":
monster1.hp = p1.flamevortex(monster1.hp, p1.attack, monster1.defence)
if chosenmove == monsterattacks[0]:
p1.hp = monsterlasersword(p1.hp)
elif chosenmove == monsterattacks[1]:
p1.hp = monsterswipe(p1.hp)
elif chosenmove == monsterattacks[2]:
monster1.hp = monsterregen(monster1.hp)
time.sleep(1.5)
print("After the monster's attacks, your hp is now " + str(p1.hp))
elif Userattack.upper() == "LIGHTNINGBOLT" or "LIGHTNING BOLT":
monster1.hp = p1.lightningbolt(monster1.hp, p1.attack, monster1.defence)
if chosenmove == monsterattacks[0]:
p1.hp = monsterlasersword(p1.hp)
elif chosenmove == monsterattacks[1]:
p1.hp = monsterswipe(p1.hp)
elif chosenmove == monsterattacks[2]:
monster1.hp = monsterregen(monster1.hp)
time.sleep(1.5)
print("After the monster's attacks, your hp is now " + str(p1.hp))
No matter what the user inputs, it only ever calls the first function.
I know this is a lot to process and appreciate any help. Thanks
if Userattack.upper() == "FLAMEVORTEX" or "FLAME VORTEX": means is userattack.upper() equal to "FLAMEVORTEX", or does the string "FLAME VORTEX" have True value.
Now since empty strings are False and non-empty strings are True, Userattack.upper() == "FLAMEVORTEX" or "FLAME VORTEX" is always True, and that's not what you meant.
Try: Userattack.upper() == "FLAMEVORTEX" or Userattack.upper()=="FLAME VORTEX"

tictactoe iteration issue. Function error

I am new to programming (About 2 months in to teaching myself). I am attempting to create a game of tic tac toe and use it as an opportunity to practice using functions and passing parameters.
I have got most of what I want to work working (for now I will add AI and a computer opponent) but when one of the human players win the endgame() function is called but it does not work as expected. It calls itself somehow and you have got to say N to end the game three times before the program is terminated. I am unable to see the wood for the trees on this one folks so help would be appreciated.
I know some of my coding will not be great so no trolling please.
Thanks
Shaun
def start():
choices = [" "," "," "," "," "," "," "," "," "]
while checkwin(choices)==False:
board(choices)
getchoice(choices)
def board(choices):
print("+---+---+---+")
print("+ "+choices[0]+" + "+choices[1]+" + "+choices[2]+" +")
print("+---+---+---+")
print("+ "+choices[3]+" + "+choices[4]+" + "+choices[5]+" +")
print("+---+---+---+")
print("+ "+choices[6]+" + "+choices[7]+" + "+choices[8]+" +")
print("+---+---+---+")
def endgame(winner):
print("The winner is "+ winner)
playagain=input("Another game? Y/N")
playagain = playagain.upper()
if playagain == "N":
print("Thanks, hope to see you again soon.")
else:
start()
def getchoice(choices):
userchoice = int(input ("Where would you like to put your X?"))
index = userchoice-1
while choices[index]!=" ":
userchoice = int(input ("That space is taken. Where would you like to put your X?"))
index = userchoice-1
choices[index]="X"
board(choices)
if checkwin(choices)==False:
userchoice = int(input ("Where would you like to put your O?"))
index = userchoice-1
while choices[index]!=" ":
userchoice = int(input ("That space is taken. Where would you like to put your O?"))
index = userchoice-1
choices[index]="O"
checkwin(choices)
return choices
def checkwin (c):
if checkwin1(c)==False:
if checkwin2 (c)==False:
return False
else:
endgame("Player 2")
else:
endgame("Player 1")
def checkwin1(c):
return ((c[0]=="X" and c[1]=="X" and c[2]=="X") or
(c[3]=="X"and c[4]=="X" and c[5] =="X") or
(c[6]=="X"and c[7]=="X" and c[8] =="X") or
(c[0]=="X"and c[3]=="X" and c[6] =="X" )or
(c[1]=="X"and c[4]=="X" and c[7] =="X") or
(c[2]=="X"and c[5]=="X" and c[8] =="X") or
(c[0]=="X"and c[4]=="X" and c[8] =="X") or
(c[6]=="X"and c[4]=="X" and c[2] =="X"))
def checkwin2(c):
return ((c[0]=="O" and c[1]=="O" and c[2]=="O") or
(c[3]=="O"and c[4]=="O" and c[5] =="O") or
(c[6]=="O"and c[7]=="O" and c[8] =="O") or
(c[0]=="O"and c[3]=="O" and c[6] =="O" )or
(c[1]=="O"and c[4]=="O" and c[7] =="O") or
(c[2]=="O"and c[5]=="O" and c[8] =="O") or
(c[0]=="O"and c[4]=="O" and c[8] =="O") or
(c[6]=="O"and c[4]=="O" and c[2] =="O"))
start()
Let's imagine that X wins (because this is probably what caused it to "end") three times.
You then get to if checkwin(choices)==False: within getchoice(),
'checkwin()' happily calls endgame(). endgame() returns, and then getchoice() continues executing.
At the end of getchoice(), checkwin() is called again, with the same result.
After getchoice() returns we get back to while checkwin(choices)==False: within start(), once again with the same result.
Also note that you will see this happening even more times if you actually played multiple games in a row.
Also try making O win, I think you will only have to say no to your prompt twice in that case.
EDIT:
class TicTacToeGame:
INCOMPLETE = 0
WINNER_PLAYER_1 = 1
WINNER_PLAYER_2 = 2
DRAW = 3
SYMBOLS=["X","O"," "]
def __init__(self,player_1, player_2):
self.board = [[-1]*3,[-1]*3,[-1]*3]
self.players = [player_1,player_2]
self.current_turn = 0;
def advance(self):
if self.calcGameState() != TicTacToeGame.INCOMPLETE:
return
while True:
x,y = self.players[self.current_turn].getMove();
if x < 0 or x > 2 or y < 0 or y>2 :
continue
if self.board[y][x] == -1:
break
self.board[y][x] = self.current_turn
self.current_turn += 1
self.current_turn %= 2
def stringify(self):
re = ""
fr = True
for row in self.board:
if fr:
fr=False
else:
re+= "\n" + "---+" * 2 + "---\n"
fe = True
for el in row :
if fe:
fe = False;
else:
re += "|"
re += " " + TicTacToeGame.SYMBOLS[el] + " "
return re
def calcGameState(self):
for i in range(0,3):
#col
if all(self.board[i][j] == self.board[i][0] for j in range(0,3)) and self.board[i][0] != -1:
return self.board[i][0] + 1
#row
if all(self.board[j][i] == self.board[0][i] for j in range(0,3)) and self.board[0][i] != -1:
return self.board[0][i] + 1
if all(self.board[i][i] == self.board[0][0] for i in range(0,3)) and self.board[0][0] != -1:
return self.board[0][0] + 1
if all(self.board[i][2-i] == self.board[0][2] for i in range(0,3)) and self.board[0][2] != -1:
return self.board[0][2] + 1
if all(self.board[i][j] != -1 for i in range(0,3) for j in range(0,3)):
return TicTacToeGame.DRAW
return TicTacToeGame.INCOMPLETE
def stringResult(self):
res = self.calcGameState()
if res == TicTacToeGame.INCOMPLETE:
return "Incomplete"
if res == TicTacToeGame.DRAW:
return "Draw"
return "Player " + self.SYMBOLS[res-1] + " Won!"
class HumanPlayer:
def __init__(self):
self.board = None
def setGame(self,game):
self.game = game
def getMove(self):
print(self.game.stringify())
print("Current turn is: " + self.game.SYMBOLS[self.game.current_turn])
print("enter row for move")
y = input()
print("enter col for move")
x = input()
return int(x)-1,int(y)-1
def playAgain():
playagain=input("Another game? Y/N\n > ")
playagain = playagain.upper()
if playagain == "N":
print("Thanks, hope to see you again soon.")
return False
return True
while True:
p = HumanPlayer()
t = TicTacToeGame(p,p)
p.setGame(t)
while t.calcGameState() == TicTacToeGame.INCOMPLETE:
t.advance()
print(t.stringResult())
if not playAgain():
break;