I am working on the hr leave odoo 12, xlsx report by department , I have overwrite problem when print xlsx report for more than one department - odoo

I am working on the hr leave odoo 12, xlsx report by department , I have overwrite problem when print xlsx report for more than one department.
here is my code:
############################### for department #########################################
def get_all_date(self, data, empid):
domain = [('state', '=', 'validate'), ('employee_id', '=', empid)]
if data.get('date_from'):
domain.append(('date_from', '>=', data.get('date_from')))
if data.get('date_to'):
domain.append(('date_from', '<=', data.get('date_to')))
print(domain)
leave = self.env['hr.leave'].search(domain)
return leave
def generate_xlsx_report(self, workbook, data, record):
##################### for department ########
res = []
Employee = self.env['hr.employee']
if 'depts' in data:
for department in self.env['hr.department'].browse(data['depts']):
res.append(
{
'dept': department.name,
'data': []
}
)
for emp in Employee.search([('department_id', '=', department.id)]):
res[len(res) - 1]['data'].append(
{
# 'emp': emp.name,
'display': self.get_all_date(data['data'], emp.id)
}
)
sheet = workbook.add_worksheet('Leaves Report')
bold = workbook.add_format({'bold': True, 'align': 'center', 'bg_color': '#fffbed', 'border': True})
format = workbook.add_format({'num_format': 'd-m-yyyy'})
header_row_style = workbook.add_format({'bold': True, 'align': 'center', 'border': True})
format2 = workbook.add_format({'font_size': 10, 'bold': True, 'align': 'center', })
title = workbook.add_format(
{'bold': True, 'align': 'center', 'font_size': 20, 'bg_color': '#f2eee4', 'border': True})
sheet.merge_range('A1:E1', 'Leaves Summary Report', title)
# Header row
# Header row
sheet.set_column(0, 4, 18)
sheet.write(2, 0, 'Department', header_row_style)
sheet.write(3, 1, 'Employee', header_row_style)
sheet.write(3, 2, ' Start date', header_row_style)
sheet.write(3, 3, 'End date', header_row_style)
sheet.write(3, 4, 'Leave Type', header_row_style)
######################### for department #############################
for rows, i in enumerate(res):
print(i)
col=0
sheet.write(rows + 4, col, i['dept'], format2)
#rows+1
for j in i['data']:
print(j)
for rows ,k in enumerate(j['display']):
print(k)
# sheet.write(ro + 3, col, k.department_id.name, format2)
sheet.write(rows + 4, col + 1, k.employee_id.name, format2)
sheet.write(rows + 4, col + 2, k.date_from, format)
sheet.write(rows+ 4, col + 3, k.date_to, format)
sheet.write(rows + 4, col + 4, k.holiday_status_id.name, format2)
rows+ 1

Related

plot grid not visible in jupyter using matplotlib

Can someone help me identify why the gridlines are missing even though plt.grid() is already added in the code please. Thank you.
km = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)
y_means = km.fit_predict(x)
plt.scatter(x[y_means == 0, 0], x[y_means == 0, 1], s = 100, c = 'pink', label = 'Uninterested Customers')
plt.scatter(x[y_means == 1, 0], x[y_means == 1, 1], s = 100, c = 'yellow', label = 'General Customers')
plt.scatter(x[y_means == 2, 0], x[y_means == 2, 1], s = 100, c = 'cyan', label = 'Target Customers')
plt.scatter(km.cluster_centers_[:,0], km.cluster_centers_[:, 1], s = 50, c = 'blue' , label = 'centeroid')
plt.title('Administrative Duration vs Duration', fontsize = 20)
plt.grid()
plt.xlabel('Administrative Duration')
plt.ylabel('Bounce Rates')
plt.legend()
plt.show()

Python pandas data frame issue. How can I conditionally insert rows and get the subtotal of the numeric column? Already solved it but any improvement?

With the change of Function, I want empty rows inserted below and the subtotal of Amount in the empty row below.
How can I imporve the code? A better or shorter way?
insertROW_df = pd.read_clipboard()
insertROW_df
insertROW_df['match'] = insertROW_df['Function'].eq(insertROW_df['Function'].shift(-1))
insertROW_df['insert_row_below?'] = insertROW_df['match'].apply(lambda x: 'Yes' if x == False else "No")
index_changed_row = insertROW_df.index[insertROW_df['match']==False]
type(insertROW_df)
line = pd.DataFrame({"Function": np.nan, "Budget": np.nan, "Amount":np.nan,"match":np.nan,"insert_row_below?":np.nan }, index=index_changed_row)
df = insertROW_df.append(line, ignore_index=False)
df = df.sort_index().reset_index(drop=True)
df['Total'] = df.groupby(['Function'])['Amount'].transform('sum')
df['Total'] = df['Total'].fillna(method="ffill")
df['Amount'] = df['Amount'].fillna(df['Total'])
print(df)
print(df[['Function', 'Budget', 'Amount']])
df.to_excel(r'Z:\Claiming FY17, 18, 19, 20, 21 & 22\November 2021\Pythonic approach\InsertBlankRows.xlsx', index=False, header=True)
DATAFRAME = pd.DataFrame({'Function':['AAA', 'AAA', 'AAA', 'AAA', 'BBB', 'BBB', 'BBB', 'CCC', 'CCC'],
'Budget': [550,550,550,680,550,550,550,860,860,],
'Amount': [14850,8640,2150,3210,5540,6660,2210,5555,5595,]
})

Why doesn't the class attribute update when I change the input value? Tkinter Python 3

I am trying to develop a simple application with tkinter and I want to create a class that performs a search in a dataframe, the search's value it is linked to the information typed in an entry that belongs to another class, however when I run the code, the value of the search is not modified when changing the value of the input. Here the code so far
from tkinter import *
import numpy as np
import pandas as pd
cat = {'N°_Cel': pd.Series(['3007441467', '3164992937', '3212400100', '3258172402', '3169995802'], index= [0, 1, 2, 3, 4]),
'Names': pd.Series(['Jairo Moreno', 'Laura Mesa', 'Camilo Baquero', 'Daniela Smith', 'Ximena Sterling'], index= [0, 1, 2, 3, 4]),
'Adress': pd.Series(['Cll 158 # 96A 25','Cll 132 # 100A 63', 'Cll 158 # 100A 63', 'Cll 148 # 97A 41', 'Cll 172A # 8 20'], index= [0, 1, 2, 3, 4]),
'Schedule': pd.Series(['N.A.', 'Evening.', 'N.A.', 'After 14', 'Morning'], index= [0, 1, 2, 3, 4]),
'Payment': pd.Series(['Credit', 'Cash', 'Credit', 'Credit', 'Cash'], index= [0, 1, 2, 3, 4])}
customer_cat = pd.DataFrame(cat)
class Search_Client():
def __init__(self, info, dataframe, colname):
self.info = info
self.dataframe = dataframe
self.colname = colname
def search(self):
if self.info == '':
result = ''
else:
result = self.dataframe.loc[self.dataframe[self.colname]==self.info]
if result.empty == True:
result = ''
else:
results = result
print(results)
class Order_Document():
def __init__(self, parent):
self.parent = parent
self.parent.geometry('')
self.parent.title('Order document')
self.cellphone_number = StringVar()
Label(self.parent, text= 'Order Document', bg= 'light gray', font= 'Verdana 13', relief= RIDGE).grid(row= 0, column= 0, columnspan= 3) # Se debe centrar al finalizar el diseño de la ventana
Label(self.parent, text= 'Cellphone Number: ', bg = 'white smoke', font= 'Arial 11 bold', justify= 'left').grid(row= 5, column= 0, sticky= 'we')
Entry(self.parent, textvariable= self.cellphone_number, font= 'Arial 11').grid(row=5, column= 1, sticky= 'we')
self.search_client = Search_Client(self.cellphone_number.get(), customer_cat, 'N°_Cel')
Button(self.parent, text= 'Buscar', command= self.search_client.search, bg= 'gold', font= 'Verdana 13').grid(row= 5, column= 3, sticky= 'we')
app = Tk()
ejec = Order_Document(app)
app.mainloop()
I don't know what I could be doing wrong, I hope you can help me.

Pandas extract value from a key-value pair

I have a Datafrmae with output as shown below, I am trying to extract specific text
id,value
101,*sample value as shown below*
I am trying to extract the value corresponding to key in this text
Expected output
id, key, id_new
101,Ticket-123, 1001
Given below is how the data looks like:
{
'fields': {
'status': {
'statusCategory': {
'colorName': 'yellow',
'name': 'In Progress',
'key': 'indeterminate',
'id': 4
},
'description': '',
'id': '11000',
'name': 'In Progress'
},
'summary': 'Sample Text'
},
'key': 'Ticket-123',
'id': '1001'
}
Use Series.str.get:
df['key'] = df['value'].str.get('key')
df['id_new'] = df['value'].str.get('id')
print (df)
id value key id_new
0 101 {'fields': {'status': {'statusCategory': {'col... Ticket-123 1001
Tested Dataframe:
v = {
'fields': {
'status': {
'statusCategory': {
'colorName': 'yellow',
'name': 'In Progress',
'key': 'indeterminate',
'id': 4
},
'description': '',
'id': '11000',
'name': 'In Progress'
},
'summary': 'Sample Text'
},
'key': 'Ticket-123',
'id': '1001'
}
df = pd.DataFrame({'id':101, 'value':[v]})

How to subtract one row to other rows in a grouped by dataframe?

I've got this data frame with some 'init' values ('value', 'value2') that I want to subtract to the mid term value 'mid' and final value 'final' once I've grouped by ID.
import pandas as pd
df = pd.DataFrame({
'value': [100, 120, 130, 200, 190,210],
'value2': [2100, 2120, 2130, 2200, 2190,2210],
'ID': [1, 1, 1, 2, 2, 2],
'state': ['init','mid', 'final', 'init', 'mid', 'final'],
})
My attempt was tho extract the index where I found 'init', 'mid' and 'final' and subtract from 'mid' and 'final' the value of 'init' once I've grouped the value by 'ID':
group = df.groupby('ID')
group['diff_1_f'] = group['value'].iloc[group.index[group['state'] == 'final'] - group['value'].iloc[group.index[dfs['state'] == 'init']]]]
group['diff_2_f'] = group['value2'].iloc[group.index[group['state'] == 'final'] - group['value'].iloc[group.index[dfs['state'] == 'init']]]
group['diff_1_m'] = group['value'].iloc[group.index[group['state'] == 'mid'] - group['value'].iloc[group.index[dfs['state'] == 'init']]]
group['diff_2_m'] = group['value2'].iloc[group.index[group['state'] == 'mid'] - group['value'].iloc[group.index[dfs['state'] == 'init']]]
But of course it doesn't work. How can I obtain the following result:
df = pd.DataFrame({
'diff_value': [20, 30, -10,10],
'diff_value2': [20, 30, -10,10],
'ID': [ 1, 1, 2, 2],
'state': ['mid', 'final', 'mid', 'final'],
})
Also in it's grouped form.
Use:
#columns names in list for subtract
cols = ['value', 'value2']
#new columns names created by join
new = [c + '_diff' for c in cols]
#filter rows with init
m = df['state'].ne('init')
#add init rows to new columns by join and filter no init rows
df1 = df.join(df[~m].set_index('ID')[cols], lsuffix='_diff', on='ID')[m]
#subtract with numpy array by .values for prevent index alignment
df1[new] = df1[new].sub(df1[cols].values)
#remove helper columns
df1 = df1.drop(cols, axis=1)
print (df1)
value_diff value2_diff ID state
1 20 20 1 mid
2 30 30 1 final
4 -10 -10 2 mid
5 10 10 2 final