I am trying to do a text justification on the following array and transform it into a chat system as pictured. So far I am able to get the alignment right but I am stuck on trying to make it looks like a chat conversation
"1", "2" indicate the user, and their message, and the array should determine the alternating order of the alignment. Width is the total width of a line, user width is the max width that a user can take in one line. user 1 is aligned to the left, and user 2 to the right.
So far I have the following code:
messages = [["1", "Bob hello"], ["2", "Alice hi"], ["1", "How is your life"], ["1", "Better than before"],
["2", "M super"], ["1", "Wow pro"]]
userWidth = 6
width = 15
def chat(messages, userWidth, width):
user1 = []
user2 = []
sep_num = []
order = []
for message in messages:
user = message[0]
convo = message[1]
windowStart = 0
sep_num.append(len(convo) // userWidth + 1)
order.append(user)
for windowEnd in range(len(convo)):
if windowEnd > 0:
if (windowEnd + 1) % userWidth == 0:
if user == "1":
left_aligned = convo[windowStart:windowEnd + 1]
user1.append(left_aligned)
else:
right_aligned = convo[windowStart:windowEnd + 1]
user2.append(right_aligned)
windowStart = windowEnd + 1
if windowEnd == len(convo) - 1:
if user == "1":
left_aligned = convo[windowStart:windowEnd + 1]
if len(left_aligned) == 1 and user1[-1][-3] != " ":
left_aligned = "".join([user1[-1][-1],left_aligned])
user1[-1] = user1[-1][:-1]
if len(left_aligned) == 1 and user1[-1][-3] == " ":
left_aligned = "".join([user1[-1][-3:], left_aligned])
user1[-1] = user1[-1][:-3]
user1.append(left_aligned)
else:
right_aligned = convo[windowStart:windowEnd + 1]
if len(right_aligned) == 1 and user2[-1][-3] != " ":
right_aligned = "".join([user2[-1][-1], right_aligned])
user2[-1] = user2[-1][:-1]
if len(right_aligned) == 1 and user1[-1][-3] == " ":
right_aligned = "".join([user1[-1][-3:], right_aligned])
user1[-1] = user1[-1][:-3]
user2.append(right_aligned)
constructor(user1, user2, width, order, sep_num)
def constructor(user1, user2, width, order, sep_num):
for i in range(len(user1)):
if (len(user1[i])) > 1:
if user1[i][0] == " ":
user1[i] = user1[i][1:]
space = width - len(user1[i])
line = "|" + user1[i] + (" " * space)
print(line)
for i in range(len(user2)):
if (len(user2[i])) > 1:
if user2[i][-1] == " ":
user2[i] = user2[i][:-1]
space = width - len(user2[i])
line = (" " * space) + user2[i] + "|"
print(line)
which makes it look like this:
|Bob he
|llo
|How is
|your
|life
|Better
|than
|before
|Wow
|pro
Alice|
hi|
M sup|
er|
But how can I transform it into the following:
You can try something like this:
from textwrap import wrap
messages = [["1", "Bob hello"], ["2", "Alice hi"], ["1", "How is your life"], ["1", "Better than before"],
["2", "M super"], ["1", "Wow pro"]]
win = 15
lw = 6
print("+" + "*" * win + "+")
for num, msg in messages:
pad = "<" if num == "1" else ">"
print("\n".join(f"|{s:{pad}{win}}|" for s in wrap(msg, lw)))
print("+" + "*" * win + "+")
It gives:
+***************+
|Bob |
|hello |
| Alice|
| hi|
|How is |
|your |
|life |
|Better |
|than |
|before |
| M|
| super|
|Wow |
|pro |
+***************+
Related
I am trying to store the values obtained from excel sheet cells to a list. The code provided basically collects data from different continuous rows and columns and creates a string of those values. I could work upt o storing the string value but I don't really know how to store the strings in a list, Can anyone help me with this?
for i in range(NR):
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
# need to create a list here to store the commentstr for each iteration
NR = no. of rows, NC = no. of columns
my_list=[]
for i in range(NR):
x=0
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
my_list[x]=Commentstr
x+=1
I'd like to use python selenium to search at https://book.spicejet.com/Search.aspx
I reviewed this question but it is not the right answer what I am looking for.
I searched for a flight from Kolkata to Goa with 2 adults and 2 Infants. When I am giving passenger details I couldn't able to select infants Date of birth.
import time
import selenium
from selenium import webdriver
from selenium.webdriver.support.ui import Select
browser = webdriver.Chrome()
booking_url = "https://book.spicejet.com/Search.aspx"
browser.get(booking_url)
departureButton = browser.find_element_by_id("ControlGroupSearchView_AvailabilitySearchInputSearchVieworiginStation1_CTXT").click()
browser.find_element_by_partial_link_text("Kolkata").click()
arivalButton = browser.find_element_by_id("ControlGroupSearchView_AvailabilitySearchInputSearchViewdestinationStation1_CTXT")
arivalButton.click()
time.sleep(.3)
arivalButton.send_keys("Goa")
time.sleep(1)
search_date = "20-September 2019"
dep_date = search_date.split("-")
dep_month = dep_date[1]
dep_day = dep_date[0]
while browser.find_element_by_class_name("ui-datepicker-title").text != dep_month:
browser.find_element_by_css_selector("a[title='Next']").click()
browser.find_element_by_xpath("//table//a[text()='"+dep_day+"']").click()
time.sleep(1)
try:
return_date_close = browser.find_element_by_class_name("date-close").click
except:
pass
pax_selct = browser.find_element_by_id("divpaxinfo").click()
time.sleep(.2)
# __________Adult number_____________
for i in range(0, 2 - 1):
adults = browser.find_element_by_id("hrefIncAdt")
adults.click()
# ____________Set Num of Children___________________
for i in range(0, 0):
childrens = browser.find_element_by_id("hrefIncChd")
childrens.click()
# ____________Set Num of Infant(s)___________________
for i in range(0, 2):
infants = browser.find_element_by_id("hrefIncInf")
infants.click()
donebttn = browser.find_element_by_id("btnclosepaxoption").click()
searchBtn = browser.find_element_by_class_name("bookbtn").click()
browser.switch_to.default_content()
flightarr = []
tbl_row = browser.find_elements_by_class_name("fare-row")
time_select=3
price_select=1
new_time_serial = 0
tr_cont = 4
for item in tbl_row:
if item.is_displayed():
if new_time_serial == time_select:
col = item
cont = str(tr_cont)
if price_select == 0:
price1 = col.find_element_by_xpath('//*[#id="availabilityTable0"]/tbody/tr['+cont+']/td[3]/p').click()
elif price_select == 1:
price2 = col.find_element_by_xpath('//*[#id="availabilityTable0"]/tbody/tr['+cont+']/td[4]/p').click()
new_time_serial = new_time_serial + 1
tr_cont = tr_cont + 1
time.sleep(1)
cntn_btn = browser.find_element_by_class_name("button-continue").click()
passen_serial = 0
passen_serial_inf = 0
#inf = 1
birth_year = "2017"
birth_month = "Nov"
birth_day = "30"
all_pass_frm = browser.find_element_by_class_name("multicontent")
all_pass_entry = all_pass_frm.find_elements_by_class_name("sectionContent")
for passen in all_pass_entry:
pass_type = passen.find_element_by_class_name("guest-heading").text.split(' ',1)[0]
pass_type2 = passen.find_element_by_class_name("guest-heading").text.split(' ',1)[1]
if pass_type == "Adult":
deg_sel_name = Select(passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_DropDownListTitle_" + str(passen_serial) + ""))
deg_sel_name.select_by_index(1)
first_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxFirstName_" + str(passen_serial) + "")
first_name_in.send_keys("imam")
last_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxLastName_" + str(passen_serial) + "")
last_name_in.send_keys("Hossain")
elif pass_type == "Child":
deg_sel_name = Select(passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_DropDownListGender_" + str(passen_serial) + ""))
deg_sel_name.select_by_index(2)
first_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxFirstName_" + str(passen_serial) + "")
first_name_in.send_keys("Korim")
last_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxLastName_" + str(passen_serial) + "")
last_name_in.send_keys("Hossain")
elif pass_type == "Infant":
deg_sel_name = Select(passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_DropDownListGender_"+ str(passen_serial_inf) + "_" + str(passen_serial_inf) + ""))
deg_sel_name.select_by_index(2)
first_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxFirstName_"+ str(passen_serial_inf) + "_" + str(passen_serial_inf) + "")
first_name_in.send_keys("Aqiba")
last_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxLastName_"+ str(passen_serial_inf) + "_" + str(passen_serial_inf) + "")
last_name_in.send_keys("Hassan")
dob = passen.find_element_by_id("inputDateContactInfant" +str(pass_type2)+ "").click()
dob_cal = browser.find_element_by_class_name("datepickerViewYears")
dob_cal_year = dob_cal.find_element_by_class_name("datepickerYears")
inf_birth_year = dob_cal.find_element_by_xpath('.//*[#class="datepickerYears"]/tr/td/a/span[text()="'+birth_year+'"]').click()
inf_birth_mon = dob_cal.find_element_by_xpath('.//*[#class="datepickerMonths"]/tr/td/a/span[text()="'+birth_month+'"]').click()
inf_birth_day = dob_cal.find_element_by_xpath('.//*[#class="datepickerDays"]/tr/td/a/span[text()="'+birth_day+'"]').click()
# inf = inf +1
passen_serial_inf = passen_serial_inf + 1
passen_serial = passen_serial + 1
print("Done")
I tried with xPath it works for 1st infant but it is not working for 2nd infant. What should i need to do now? is there any way except XPath? And what can i do when passenger number is different?
I have extracted the var declarations and the var increments, there seems to be a mismatch at the declaration statements that could be causing the problem, don't the var declarations need to start at the same number? Set them equal and re-try.
var declaration
passen_serial_inf = 0
inf = 1
var increments
inf = inf +1
passen_serial_inf = passen_serial_inf + 1
passen_serial = passen_serial + 1
I am doing an homework and I need to return a tree as string. I have solved the problem and when I print is all right. The problem is that the homework asks to return the string and when I return, it prints /n chars without considering them as new line.
If I print it this is the result:
04
|
05
|
01
|
06
|
03
And this should be the string I have to return.
But if I use the return instead the print it returns this:
04 \n | \n 05 \n | \n 01 \n | \n 06 \n |
\n 03
This is the class I'm using:
class Albero:
def __init__(self,V):
self.id=V
self.f=[]
n=Albero("04")
n1=Albero("05")
n2=Albero("01")
n3=Albero("06")
n4=Albero("03")
n.f=[n1]
n1.f=[n2]
n3.f=[n4]
def treeLines(node,getInfo):
nodeId,nodeChildren = getInfo(node)
subNodes = [treeLines(child,getInfo) for child in nodeChildren]
widths = [ len(childText[0]) for childText in subNodes ]
totalWidth = sum(widths) + 2*len(widths) - 1
totalWidth = max(totalWidth,len(nodeId))
nodeLine = nodeId.center(totalWidth," ")
result = [nodeLine]
if not nodeChildren: return result
linksLine = " ".join("|".center(width," ") for width in widths)
linksLine = linksLine.center(totalWidth," ")
leftIndent = linksLine.index("|") + 1
rightIndent = linksLine[::-1].index("|") + 1
spanWidth = totalWidth - leftIndent - rightIndent - 1
leftSpan = nodeLine.index(nodeId)-leftIndent+(len(nodeId)-1)//2
rightSpan = spanWidth - leftSpan
spanLine = " "*leftIndent + "_"*leftSpan + "|" + "_"*rightSpan + " "*rightIndent
if len(nodeChildren) > 1 : result.append(spanLine)
result.append(linksLine)
maxHeight = max(len(subNode) for subNode in subNodes)
subNodes = [ subNode + [" "*len(subNode[0])]*(maxHeight-len(subNode)) for subNode in subNodes ]
result += [" ".join([subNode[i] for subNode in subNodes]).center(totalWidth," ") for i in range(maxHeight) ]
return result
def treeText(node,getInfo): return "\n".join(treeLines(node,getInfo))
print( treeText(Albero.radice,lambda n:(n.id,n.f)) )
How can I return the string format as in the print ?
This small scripts makes exactly what I need.
#!/usr/bin/python
import os
import fileinput
import sys
import shutil
import glob
import time
def replaceAll1(files,searchExp,replaceExp):
for line in fileinput.input(files, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
param1 = [1,2,3]
param2 = [1,2,3]
param3 = [1,2,3]
for i in xrange(len(param1)):
for ii in xrange(len(param2)):
for iii in xrange(len(param3)):
os.system("cp -a cold.in input.in")
old_param1 = "param1 = 1"
old_param2 = "param2 = 1"
old_param3 = "param3 = 1"
new_param1 = "param1 = " + str(param1[i])
new_param2 = "param2 = " + str(param2[ii])
new_param3 = "param3 = " + str(param3[iii])
replaceAll1('input.in',old_param1,new_param1)
replaceAll1('input.in',old_param2,new_param2)
replaceAll1('input.in',old_param3,new_param3)
time.sleep(4)
It enters in a configuration file and replaces sequentially the input parameters according to the lists that are accessed by the loop indexes. It is simple a combination of all the three parameters between each other.
# Input file
param1 = 1 # --- Should be [1,2,3]
param2 = 1 # --- Should be [1,2,3]
param3 = 1 # --- Should be [1,2,3]
The problem is that his big brother is not behaving like it. When it loops through the lists, it gets lost in scheme = 2 and puts dissp_scheme = 2 (freezed) when it should be dissp_scheme = 1. I printed out every single variable that goes inside the function replaceAll marked with comments but when I turn on the other calls it mess up everything. Here is the script.
#!/usr/bin/python
import os
import fileinput
import sys
import shutil
import glob
import time
os.chdir(os.getcwd())
# Replaces the input file parameters
def replaceAll(files,searchExp,replaceExp):
for line in fileinput.input(files, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
# Gets a number inside my input file.
def get_parameter(variable,file_name):
f = open(file_name,'r').readlines()
for i in xrange(len(f)):
index = f[i].find(variable)
if index != -1:
pre_found = f[i].split('=')[1]
return pre_found
# Gets the discretization scheme name.
def get_sheme(number):
if number == 1:
return "Simple Centered Scheme"
elif number == 2:
return "Lax-Wendroff Scheme"
elif number == 3:
return "MacCormack Scheme"
elif number == 4:
return "Beam-Warming Scheme"
elif number == 5:
return "Steger-Warming 1st Order Scheme"
elif number == 6:
return "Steger-Warming 2nd Order Scheme"
elif number == 7:
return "Van Leer 1st Order Scheme"
elif number == 8:
return "Van Leer 2nd Order Scheme"
elif number == 9:
return "Roe Scheme"
elif number == 10:
return "AUSM Scheme"
# Gets the dissipation scheme name.
def get_dissip(number):
if number == 1:
return "Pullian Non-Linear dissipation"
elif number == 2:
return "Second difference dissipation"
elif number == 3:
return "Fourth difference dissipation"
elif number == 4:
return "B&W dissipation"
# Generates the density gnuplot scripts.
def gnuplot(variable,pressure_ratio,scheme,dissip_scheme):
#gnuplot('Density',10,get_sheme(3),'Pullian')
# Building name of the output file.
outFileName = variable.lower() + '_ratio' + str(int(pressure_ratio)) + '_' + scheme.replace(" ","") + '_dissp' + dissip_scheme.replace(" ","") + '.tex'
gnuFileName = variable.lower() + '_ratio' + str(int(pressure_ratio)) + '_' + scheme.replace(" ","") + '_dissp' + dissip_scheme.replace(" ","") + '.gnu'
# Build title of the plot
title = 'Analytical vs Numerical | ' + scheme
f = open(gnuFileName,'w')
f.write("set term cairolatex monochrome size 15.0cm, 8cm\n")
f.write('set output "' + outFileName + '"\n')
f.write("set grid\n")
f.write('set xtics font "Times-Roman, 10\n')
f.write('set ytics font "Times-Roman, 10\n')
f.write('set xlabel "x position" center\n')
f.write('set ylabel "' + variable + '" center\n')
f.write('set title "Analytical vs Numerical Results | ' + variable + '" \n')
f.write('set pointsize 0.5\n')
f.write('set key font ",10"\n')
fortran_out_analytical = 'a' + variable.lower() + '.out'
fortran_out_numerical = variable.lower() + 'Output.out'
f.write('plot "' + fortran_out_analytical +'" u 1:2 with linespoints lt -1 lw 1 pt 4 title "Analytical",\\\n')
f.write( '"' + fortran_out_numerical + '" u 1:2 with lines lw 5 title "Numerical"\n')
f.close()
# Generate latex code.
def generate_latex(text_image_file,caption):
latex.write("\\begin{figure}[H]\n")
latex.write(" \centering\n")
latex.write(" \input{" + text_image_file + "}\n")
latex.write(" \caption{"+ caption +"}\n")
latex.write(" \label{fig:digraph}\n")
latex.write("\\end{figure}\n")
latex.write("\n\n")
# -----------------------------------------------------------------------
# Main loop.
# -----------------------------------------------------------------------
pressure_ratios = [5.0]
schemes = [1,2,3]
dissips = [1,2,3]
# Define replace lines for replace all.
scheme_line = "scheme = "
dissip_line = "dissp_scheme = "
# Open Latex export file.
latex = open("bizu.txt",'w')
i = 0
# ratios.
for i in xrange(len(pressure_ratios)):
print "----------------------------------------"
print " + Configuring File for pressure ratio: " + str(pressure_ratios[i])
print "----------------------------------------\n"
# Schemes
for jj in xrange(len(schemes)):
print " + Configuring file for scheme: " + get_sheme(schemes[jj]) + "\n"
for kkk in xrange(len(dissips)):
print " + Configuring file for dissip: " + get_dissip(dissips[kkk])
# We always work with a brand new file.
os.system("rm input.in")
os.system("cp -a cold.in input.in")
# Replace pressures.
p1_line_old = 'p1 = 5.0d0'
rho1_line_old = 'rho1 = 5.0d0'
p1_line_new = 'p1 = ' + str(pressure_ratios[i]) + 'd0'
rho1_line_new = 'rho1 = ' + str(pressure_ratios[i]) + 'd0'
replaceAll('input.in',p1_line_old,p1_line_new)
replaceAll('input.in',rho1_line_old,rho1_line_new)
# Replace discretization scheme.
old_scheme = scheme_line + "1"
new_scheme = scheme_line + str(schemes[jj])
#==========================================================
# This call is messing everything up when scheme turns to 2
#==========================================================
replaceAll('input.in',old_scheme,new_scheme)
# Replace dissipation scheme.
old_dissp_scheme = dissip_line + "1"
new_dissp_scheme = dissip_line + str(dissips[kkk])
print p1_line_old
print new_scheme
print new_dissp_scheme
replaceAll('input.in',old_dissp_scheme, new_dissp_scheme)
time.sleep(3)
# ### Calling program
# os.system("./sod")
#
latex.close()
And the input file that the it works on is:
&PAR_physical
p1 = 5.0d0
p4 = 1.0d0
rho1 = 5.0d0
rho4 = 1.0d0
fgamma = 1.4d0
R_const = 287.0d0
F_Cp = 1004.5
F_Cv = 717.5
/
&PAR_geometry
total_mesh_points = 1001
start_mesh_point = -5.0d0
final_mesh_point = 5.0d0
print_step = 100
/
&PAR_numeric
scheme = 3
iterations = 10000
time_step = 0.0001d0
/
&PAR_dissip
dissp_scheme = 3
dissip_omega = 0.5d0
/
Thank you all !
In the invoice, I want to convert total amount to words in Indian numbering system(hundreds, thousands, lakhs, crores). I cant use amount_to_text library module since it has been set in euro currency. So how to write function in python to achieve this? (dont worry abt indendation,its correct in my system) When i tried this code in my custom module, i get this error
TypeError: _int2word() takes exactly 1 argument (7 given)
class account_invoice(models.Model):
_inherit = "account.invoice"
print "hello"
ones = ["", "one ","two ","three ","four ", "five ", "six ","seven ","eight ","nine "]
tens = ["ten ","eleven ","twelve ","thirteen ", "fourteen ","fifteen ","sixteen ","seventeen ","eighteen ","nineteen "]
twenties = ["","","twenty ","thirty ","forty ","fifty ","sixty ","seventy ","eighty ","ninety "]
thousands = ["","thousand ","lakh ", "crore "]
def _int2word(amount_total):
n = amount_total
n3 = []
r1 = ""
ns = str(n)
for k in range(3, 33, 3):
r = ns[-k:]
q = len(ns) - k
if q < -2:
break
else:
if q >= 0:
n3.append(int(r[:3]))
elif q >= -1:
n3.append(int(r[:2]))
elif q >= -2:
n3.append(int(r[:1]))
r1 = r
nw = ""
for i, x in enumerate(n3):
b1 = x % 10
b2 = (x % 100)//10
b3 = (x % 1000)//100
#print b1, b2, b3 # test
if x == 0:
continue # skip
else:
t = thousands[i]
if b2 == 0:
nw = ones[b1] + t + nw
elif b2 == 1:
nw = tens[b1] + t + nw
elif b2 > 1:
nw = twenties[b2] + ones[b1] + t + nw
if b3 > 0:
nw = ones[b3] + "hundred " + nw
return nw
_columns = {
'amount_words': fields.function(_int2word, string='In Words', type="char"),
}
You could use amount_to_text_en function from openerp.tools this function takes 3 parameters the_value , the_partner.lang and the currency_name then it will be not just Euro it will return any currency you pass to it.