Showing only none in output instead of changing numeric value to capitilized alphabets - python-3.8

def convert_digits(input_string, start_position, end_position):
# The ending index was required as it was not returning the whole sentence
new_string = input_string[:end_position]
newstring = " "
# return new_string
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
if start_position >= 1:
if end_position <= len(new_string):
if start_position < end_position:
for index in range(start_position - 1, end_position):
if input_string[index].isdigit():
mapped = digit_mapping[input_string[index]]
newstring += " " + mapped + " "
else:
newstring += input_string[index]
else:
return "INVALID"
else:
return "INVALID"
else:
return "INVALID"
return newstring
if name == 'main':
print(convert_digits("you are a 4king 5shole", 1, 21))

Use this code.
Your problem was in line 39, you add 2 tabs place 1.
def convert_digits(input_string, start_position, end_position):
# The ending index was required as it was not returning the whole sentence
new_string = input_string[:end_position]
newstring = " "
# return new_string
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
if start_position >= 1:
if end_position <= len(new_string):
if start_position < end_position:
for index in range(start_position - 1, end_position):
if input_string[index].isdigit():
mapped = digit_mapping[input_string[index]]
newstring += " " + mapped + " "
else:
newstring += input_string[index]
else:
return "INVALID"
else:
return "INVALID"
else:
return "INVALID"
return newstring
if __name__ == '__main__':
print(convert_digits("you are a 4king 5shole", 1, 21))

Related

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

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

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,]
})

Python program Convert middle digits into its corresponding alphabets form in between start position and end position

take string and two integers from user and convert middle digits into its corresponding alphabetical form in between start and end position
def convert_digits( input_string, start_position, end_position ) :
new_string = input_string[:start_position]
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
for index in range(start_position, end_position):
if input_string[index].isdigit():
mapped = digit_mapping[input_string[index]]
new_string = mapped
new_string += input_string[end_position + 1:]
return new_string
def convert_digits(input_string, start_position, end_position):
len_str = len(input_string)
if end_position > len_str:
end_position = len_str
if start_position < 0:
start_position = 0
elif start_position >= end_position:
start_position = end_position - 1
input_string = input_string[start_position:end_position]
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
input_string = list(input_string)
for index, char in enumerate(input_string):
if char.isdigit():
input_string[index] = digit_mapping[char]
return "".join(input_string)
print(convert_digits("ajoegh12ioh12oih", 0, 14))

Not able to populate Athena script in AWS Lambda

import awswrangler as wr
def main():
database = 'temp'
output_table = 'Output Table'
output_s3_location = "'s3:Location'"
output_s3_storage_format = "'Parquet'" # "'TEXTFILE'" # "'Parquet'"
create_query = "CREATE TABLE " + database + "." + output_table + " \
WITH ( \
format = "+output_s3_storage_format+", \
external_location = "+ output_s3_location +", \
partitioned_by = ARRAY['run_date']) AS "
insert_query = "INSERT INTO "+database+"."+output_table+" "
select_query = """with temp AS
(SELECT CONCAT(period,' ',date1) AS new_Date,text,text1
FROM
(SELECT Substr(CAST(year AS varchar),3,4) AS date1,
test,
text1,
CASE
WHEN period='JAN' THEN 'Jan'
WHEN period='FEB' THEN 'Feb'
WHEN period='MAR' THEN 'Mar'
WHEN period='APR' THEN 'Apr'
WHEN period='MAY' THEN 'May'
WHEN period='JUN' THEN 'Jun'
WHEN period='JUL' THEN 'Jul'
WHEN period='AUG' THEN 'Aug'
WHEN period='SEP' THEN 'Sep'
WHEN period='OCT' THEN 'Oct'
WHEN period='NOV' THEN 'Nov'
WHEN period='DEC' THEN 'Dec'
END AS period
FROM Table_Name
WHERE text1='Car' ) ) ,
temp1 AS
(SELECT temp.* from A left join temp
ON A.value=temp.value)
Select * from temp2";"""
if create:
wr.athena.read_sql_query(sql="DROP TABLE " + database +"." + output_table + ";", database=database, ctas_approach=False)
wr.athena.read_sql_query(sql=create_query+select_query, database=database, ctas_approach=False)
else:
wr.athena.read_sql_query(sql=insert_query+select_query, database=database, ctas_approach=False)
def lambda_handler(event, context):
main()
return "True"
I am getting the below error while writing this script in Lambda function and testing it:
Response:
{
"errorMessage": "An error occurred (InvalidRequestException) when calling the StartQueryExecution operation: line 24:23: mismatched input '.' expecting {',', ')', 'FROM', 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'UNION', 'EXCEPT', 'INTERSECT'}",
"errorType": "InvalidRequestException",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 134, in lambda_handler\n main()\n",
" File \"/var/task/lambda_function.py\", line 128, in main\n wr.athena.read_sql_query(sql=create_query+select_query, database=database, ctas_approach=False)\n",
" File \"/opt/python/awswrangler/_config.py\", line 263, in wrapper\n return function(**args)\n",

Karate match expression

I am using schema validation to validate a response, value returns a number or 'NA' and below is response and schema validation.
Response:
{
"ID": "ES123D74590Z",
"companyName": "ABC Corp",
"hourMs": 67890000000,
"date": "2020-06-09T00:00:00.000Z",
"scores": {
"AllScore": 61,
"MaxScore": 59,
"ScoreA": 75,
"ScoreB": "NA",
"ScoreC": 49,
"ScoreD": "NA"
},
"movement": {},
"amt": {}
}
Schema Assertion:
{
"ID": '#string',
"companyName": '#string',
"hourMs": '#number',
"date": '#regex[^\d\d\d\d-([0-9]{2})-([0-9]{2})(\T)([0-9]{3}):([0-9]{3}):([0-9]{3})\.[0-9]{3}\Z)$]',
"scores": {
"AllScore": '##number? _ >= 0 && _ <=100 || _ == "NA"',
"MaxScore": '##number? _ >= 0 && _ <=100 || _ == "NA"',
"ScoreA": '##number? _ >= 0 && _ <=100 || _ == "NA"',
"ScoreB": '##number? _ >= 0 && _ <=100 || _ == "NA"',
"ScoreC": '##number? _ >= 0 && _ <=100 || _ == "NA"',
"ScoreD": '##number? _ >= 0 && _ <=100 || _ == "NA"'
},
"movement": {},
"amt": {}
}
Error message received :
com.intuit.karate.exception.KarateException: score.feature:19 - path: $.scores.ScoreB, actual: 'NA', expected: '##number? _ >= 0 && _ <=100 || _ == "NA"', reason: not a number
How can I correct the match expression?
Here you go. Try to take the help of someone to review your code. And read the docs carefully. And next time, simplify your question like this.
* def response =
"""
{
"AllScore": 61,
"MaxScore": 59,
"ScoreA": 75,
"ScoreB": "NA",
"ScoreC": 49,
"ScoreD": "NA"
}
"""
* def isNum = function(x){ if (x === 'NA') return true; return typeof x === 'number' }
* def schema =
"""
{
"AllScore": '#? isNum(_)',
"MaxScore": '#? isNum(_)',
"ScoreA": '#? isNum(_)',
"ScoreB": '#? isNum(_)',
"ScoreC": '#? isNum(_)',
"ScoreD": '#? isNum(_)'
}
"""
* match response == schema
Also I suggest you look at this date validation example for more ideas: https://stackoverflow.com/a/55938480/143475