Launch libreoffice-calc:
soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
Launch python shell to write data into the calc:
import uno
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
svcmgr = context.ServiceManager
desktop = svcmgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
oDoc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
oSheet = oDoc.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:C3")
Write data into oRange.
oRange.setDataArray((('a1','a2','a3'),('b1','b2','b3'),('c1','c2','c3'),))
The calc's appearance now:
I want to merge all data in oRange and format it with vertical and horizontal alignment.
My desired effect in the editing calc.
oRange.merge()
oCell = oSheet.getCellByPosition(0, 0)
oCell.HoriJustify = 2
oCell.VertJustify = 2
Merged data with vertical and horizontal alignment ,previous data in many cells b1-c1 and a2-c2 and a3-c3 lost.
The real effect.
How to fix my code to get the desired effect?
import uno
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
svcmgr = context.ServiceManager
desktop = svcmgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
oDoc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
oSheet = oDoc.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:C3")
tup = (('a1','a2','a3'),('b1','b2','b3'),('c1','c2','c3'),)
oRange.setDataArray(tup)
target =''
for item in tup:
tmp = ' '.join(item)
target = target + tmp + ' '
target = target.strip()
oRange.merge(True)
oCell = oSheet.getCellByPosition(0, 0)
oCell.String = target
oCell.HoriJustify = 2
oCell.VertJustify = 2
I'm not sure, but I think UNO has no way of knowing that you want to rearrange the data into the merged cell that way. What UNO does is "copy" the data from the "main" cell (the top left one) and "paste" its data into the merged cell. Therefore, what you could do is change the data of the main cell before merging. Check the example below.
# get range
oRange = oSheet.getCellRangeByName("A1:C3")
# build string
flat_list = [str(item) for sublist in oRange.getDataArray() for item in sublist]
string = ' '.join(flat_list)
# put string into main cell
main_cell = oRange.getCellByPosition(0, 0)
main_cell.setString(string)
# merge
oRange.merge()
Related
I am using Pandas to calculate percentage change(s) between values that occur more than once in the column of interest.
I want to compare the values of last weeks workout provided they're the same exercise type to get the percentage change of (weight used, reps accomplished )
I am able to get the percentages of all the rows which is halfway what I want but the conditional part is missing - so only get the percentages if the exercise_name is of the same value as we want to compare how we improve on a weekly, bi-weekly basis.
ids = self.user_data["exercise"].fillna(0)
dups = self.user_data[ids.isin(ids[ids.duplicated()])].sort_values("exercise")
dups['exercise'] = dups['exercise'].astype(str)
dups['set_one_weight'] = pd.to_numeric(dups['set_one_weight'])
dups['set_two_weight'] = pd.to_numeric(dups['set_two_weight'])
dups['set_three_weight'] = pd.to_numeric(dups['set_three_weight'])
dups['set_four_weight'] = pd.to_numeric(dups['set_four_weight'])
dups['set_one'] = pd.to_numeric(dups['set_one'])
dups['set_two'] = pd.to_numeric(dups['set_two'])
dups['set_three'] = pd.to_numeric(dups['set_three'])
dups['set_four'] = pd.to_numeric(dups['set_four'])
**percent_change = dups[['set_three_weight']].pct_change()**
the last line gets the percentage change for all the rows for column set_three_weight but is unable to do what I want above which is find rows with same name and obtain the percentage change.
UPDATE
Using Group By Solution
ids = self.user_data["exercise"].fillna(0)
dups = self.user_data[ids.isin(ids[ids.duplicated()])].sort_values("exercise")
dups['exercise'] = dups['exercise'].astype(str)
dups['set_one_weight'] = pd.to_numeric(dups['set_one_weight'])
dups['set_two_weight'] = pd.to_numeric(dups['set_two_weight'])
dups['set_three_weight'] = pd.to_numeric(dups['set_three_weight'])
dups['set_four_weight'] = pd.to_numeric(dups['set_four_weight'])
dups['set_one'] = pd.to_numeric(dups['set_one'])
dups['set_two'] = pd.to_numeric(dups['set_two'])
dups['set_three'] = pd.to_numeric(dups['set_three'])
dups['set_four'] = pd.to_numeric(dups['set_four'])
dups['routine_upload_date'] = pd.to_datetime(dups['routine_upload_date'])
# percent_change = dups[['set_three_weight']].pct_change()
# Group the exercises together and create a new cols that represent the percentage delta variation in percentages
dups.sort_values(['exercise', 'routine_upload_date'], inplace=True, ascending=[True, False])
dups['set_one_weight_delta'] = (dups.groupby('exercise')['set_one_weight'].apply(pd.Series.pct_change) + 1)
dups['set_two_weight_delta'] = (dups.groupby('exercise')['set_two_weight'].apply(pd.Series.pct_change) + 1)
dups['set_three_weight_delta'] = (dups.groupby('exercise')['set_three_weight'].apply(pd.Series.pct_change) + 1)
dups['set_four_weight_delta'] = (dups.groupby('exercise')['set_four_weight'].apply(pd.Series.pct_change) + 1)
dups['set_one_reps_delta'] = (dups.groupby('exercise')['set_one'].apply(pd.Series.pct_change) + 1)
dups['set_two_reps_delta'] = (dups.groupby('exercise')['set_two'].apply(pd.Series.pct_change) + 1)
dups['set_three_reps_delta'] = (dups.groupby('exercise')['set_three'].apply(pd.Series.pct_change) + 1)
dups['set_four_reps_delta'] = (dups.groupby('exercise')['set_four'].apply(pd.Series.pct_change) + 1)
print(dups.head())
I think this gets me the result(s) I want, would like someone to confirm
So I'm trying to write some program to convert html to pptx using Python.
I'm using some code to parse through the file and then format text at run level.
I am using 2 textframes on a blank slide to work, the first textframe is used for title and 2nd one is used for rendering the body of html.
But no matter what I do (Paragraph.font.name or run.font.name), I am always getting Arial font in my 2nd textframe.
I've tried to update the fontnames by looping over tf.paragraphs and also by looping over all runs (paragraph.runs) nothing seems to work.
Here is my function which I use for setting the font
def setFont(font,tags,fontStyle,size):
font.language_id = MSO_LANGUAGE_ID.HEBREW
font.size = Pt(size)
font.name = fontStyle
for tag in tags:
if tag == 'b':
font.bold = True
elif tag == 'i':
font.italic = True
elif tag == 'u':
font.underline = True
return font
and here is my main calling function (I've removed some other calls which are not directly related to python-pptx)
def makeSlide(prs,title,body,fontStyle,titleSize,bodySize):
#Add title Slide
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
width = height = Inches(8)
txBox = slide.shapes.add_textbox(Inches(1), Inches(0.5), Inches(8), Inches(1))
tf = txBox.text_frame
tf.text = title
tf.paragraphs[0].font.size=Pt(titleSize)
tf.paragraphs[0].font.bold = True
tf.paragraphs[0].font.color.rgb = RGBColor(255,0,0)
tf.paragraphs[0].font.name = fontStyle
tf.paragraphs[0].alignment = PP_ALIGN.CENTER
styles = MY_CUSTOM_HTML_BODY_PARSER() #Removed this part from here, its just a parser which gives output in a desired format
#Start 2nd textbox for body
txBox2 = slide.shapes.add_textbox(Inches(0.5), Inches(1.7), Inches(9), Inches(5.5))
tf = txBox2.text_frame
tf.clear()
tf.word_wrap = True
tf.paragraphs[0].text = ''
tf.paragraphs[0].font.name = fontStyle
paragraph = tf.add_paragraph()
paragraph.alignment = alignment
#Loop over styles (Tag info and render pptx accordingly)
new_line = True
level = 0
number = 0
for _ in styles:
#Can ignore this part, I'm just checking to see if I have to go on a new line or not
if _ == '\n':
paragraph = tf.add_paragraph()
paragraph.alignment = alignment
new_line = True
else:
tags = _[1]
#Can also ignore this, I'm checking to see if I have to be on next level in lists or not
#(I use custom bullet function, since python-pptx doesn't have a function for numbered bullets.
if _[1].count('ul') > 1 or _[1].count('ol') > 1 or _[1].count('ul') + _[1].count('ol') > 1:
level = 1
if new_line:
paragraph.level = level
level = 0
else:
paragraph = tf.add_paragraph()
paragraph.alignment = alignment
paragraph.level = level
level = 0
new_line = True
if new_line:
run = paragraph.add_run()
#Custom bullet function as u can see I send in fontStyle here and apply style inside function
run,number = addBullets(run,tags,bodySize-3,number,fontStyle)
new_line = False
run = paragraph.add_run()
run.text = parser.words_styles[_[0]][0]
font = run.font
#SetFont function Defined above
font = setFont(font,tags,fontStyle,bodySize)
new_line = False
for paragraph in tf.paragraphs:
paragraph.font.name = fontStyle
for run in paragraph.runs:
if run.font.name != fontStyle:
print(run.text)
#return slide
return slide
I'm not quite sure where I am doing wrong, would appreciate any help, I can clean up code more if that's needed.
I have tables in different sheets of excel and requirement is to copy second last row of table to last row. Can someone pls help me how can we dynamically find table size so that code wont be required to change evrytime when table size changes? There are many tables and we want to automate this task using vba code and macro button.
I have written a code but that is range specific and everytime I need to update the range and process become cumbersome.
Sub history_copy()
Set obj = ActiveWorkbook.Sheets("sheet A")
obj.Range("E12:N12").Value = obj.Range("E11:N11").Value
obj.Range("E34:N34").Value = obj.Range("E33:N33").Value
obj.Range("E46:N46").Value = obj.Range("E45:N45").Value
obj.Range("E57:N57").Value = obj.Range("E56:N56").Value
Set obj1 = ActiveWorkbook.Sheets("sheet b ")
obj1.Range("G21:O21").Value = obj1.Range("G20:O20").Value
Set obj2 = ActiveWorkbook.Sheets("sheet c")
obj2.Range("D4:M4").Value = obj2.Range("D3:M3").Value
obj2.Range("D14:M14").Value = obj2.Range("D13:M13").Value
obj2.Range("D23:M23").Value = obj2.Range("D22:M22").Value
obj2.Range("D33:M33").Value = obj2.Range("D32:M32").Value
obj2.Range("D43:M43").Value = obj2.Range("D42:M42").Value
obj2.Range("D52:M52").Value = obj2.Range("D51:M51").Value
obj2.Range("D61:M61").Value = obj2.Range("D60:M60").Value
obj2.Range("D70:M70").Value = obj2.Range("D69:M69").Value
obj2.Range("D79:M79").Value = obj2.Range("D78:M78").Value
obj2.Range("D88:M88").Value = obj2.Range("D87:M87").Value
obj2.Range("D97:M97").Value = obj2.Range("D96:M96").Value
obj2.Range("D106:M106").Value = obj2.Range("D105:M105").Value
obj2.Range("D114:M114").Value = obj2.Range("D113:M113").Value
Set obj3 = ActiveWorkbook.Sheets("sheet d")
obj3.Range("D4:L4").Value = obj3.Range("D3:L3").Value
Set obj5 = ActiveWorkbook.Sheets("sheet f")
obj5.Range("D4:L4").Value = obj5.Range("D3:L3").Value
Set obj6 = ActiveWorkbook.Sheets("sheet e")
obj6.Range("C4:C12").Value = obj6.Range("B4:B12").Value
obj6.Range("H4:H8").Value = obj6.Range("G4:G8").Value
obj6.Range("N4:N11").Value = obj6.Range("M4:M11").Value
obj6.Range("S4:S10").Value = obj6.Range("R4:R10").Value
obj6.Range("X4:X18").Value = obj6.Range("W4:W18").Value
obj6.Range("AD4:AD9").Value = obj6.Range("AC4:AC9").Value
obj6.Range("AI4:AI13").Value = obj6.Range("AH4:AH13").Value
obj6.Range("AO4:AO6").Value = obj6.Range("AN4:AN6").Value
obj6.Range("AT4:AT11").Value = obj6.Range("AS4:AS11").Value
obj6.Range("AY4:AY20").Value = obj6.Range("AX4:AX20").Value
obj6.Range("BD4:BD10").Value = obj6.Range("BC4:BC10").Value
obj6.Range("BI4:BI21").Value = obj6.Range("BH4:BH21").Value
Set obj7 = ActiveWorkbook.Sheets("sheet i")
obj7.Range("C4:C12").Value = obj7.Range("B4:B12").Value
obj7.Range("H4:H8").Value = obj7.Range("G4:G8").Value
obj7.Range("N4:N11").Value = obj7.Range("M4:M11").Value
obj7.Range("S4:S10").Value = obj7.Range("R4:R10").Value
obj7.Range("X4:X18").Value = obj7.Range("W4:W18").Value
obj7.Range("AD4:AD9").Value = obj7.Range("AC4:AC9").Value
obj7.Range("AI4:AI13").Value = obj7.Range("AH4:AH13").Value
obj7.Range("AO4:AO6").Value = obj7.Range("AN4:AN6").Value
obj7.Range("AT4:AT11").Value = obj7.Range("AS4:AS11").Value
obj7.Range("AY4:AY20").Value = obj7.Range("AX4:AX20").Value
obj7.Range("BD4:BD10").Value = obj7.Range("BC4:BC10").Value
obj7.Range("BI4:BI21").Value = obj7.Range("BH4:BH21").Value
End Sub
I am trying to copy multiple rows from an excel sheet with a Groovy Script, but somehow I am hitting the java.lang.NullPointerException error. The code I am using is the following:
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*
def numofapps = context.expand('${Data_AppNM#NumberOfApplicants}')
def apps2 = ["2","3","4","5","6"]
def myTestCase = context.testCase
def counter,next,previous,size
Workbook workbook1 = Workbook.getWorkbook(new File("C://Path//Multiple records.xls"))
Sheet sheet1 = workbook1.getSheet(0)
size= sheet1.getRows().toInteger()
propTestStep = myTestCase.getTestStepByName("Data")
propTestStep.setPropertyValue("Total", size.toString())
counter = propTestStep.getPropertyValue("Count").toString()
counter = counter.toInteger()
next = (counter > size-2? 0: counter+1)
Cell u1_1 = sheet1.getCell(0,counter)
Cell u2_1 = sheet1.getCell(1,counter)
Cell u3_1 = sheet1.getCell(2,counter)
workbook1.close()
1value1 = u1_1.getContents()
2value1 = u2_1.getContents()
3value1 = u3_1.getContents()
propTestStep.setPropertyValue("A1.1Value", 1value1 )
propTestStep.setPropertyValue("A1.2Value", 2value1 )
propTestStep.setPropertyValue("A1.3Value", 3value1 )
propTestStep.setPropertyValue("Count", next.toString())
next++ //increase next value
propTestStep.setPropertyValue("Next", next.toString())
if (apps2.contains(numofapps)){ //setting values for Applicant 2 if requested
counter = propTestStep.getPropertyValue("Count").toString()
counter = counter.toInteger()
next = (counter > size-2? 0: counter+1)
// Extracting the Data from the Excel sheet
Cell u1_2 = sheet1.getCell(0,counter)
Cell u2_2 = sheet1.getCell(1,counter)
Cell u3_2 = sheet1.getCell(2,counter)
workbook1.close()
1value2 = u1_2.getContents()
2value2 = u2_2.getContents()
3value2 = u3_2.getContents()
propTestStep.setPropertyValue("A2.1Value", 1value2 )
propTestStep.setPropertyValue("A2.2Value", 2value2 )
propTestStep.setPropertyValue("A2.3Value", 3value2 )
propTestStep.setPropertyValue("Count", next.toString())
next++ //increase next value
propTestStep.setPropertyValue("Next", next.toString())
}
I am hitting the NullPointerException error on the Cell u1_2 = sheet1.getCell(0,counter) step.
Can you please tell me why I am hitting these and is there any other way that I can use a shorter code?
Thank you :)
I want to save pitch,yaw and roll data in excel file for all frames. Eg: if i have 200 frames then i want to save 200 frames information in excel file. I have tried but my code only stores one frame data.exceldata
fitting_model='models/Chehra_f1.0.mat';
load(fitting_model);
mov=VideoReader('7_a.avi'); %Read video file and create an object
c=mov.NumberOfFrames;
for k=1:c
a = read(mov, k);
img=im2double(a);
disp(['Detecting Face in ']);
faceDetector = vision.CascadeObjectDetector(); % detect face in an image
bbox = step(faceDetector, img); %create boundary box around face
test_init_shape = InitShape(bbox,refShape); %initialize facial points in variable
test_init_shape = reshape(test_init_shape,49,2);
if size(img,3) == 3
test_input_image = im2double(rgb2gray(img));
else
test_input_image = im2double((img));
end
disp(['Fitting']);
MaxIter=6;
test_points = Fitting(test_input_image,test_init_shape,RegMat,MaxIter);
load('3D_Shape_Model.mat');
n=49;
test_image=img;
imshow(test_image);hold on;
% % Compute 3D Head Pose
if(n==49)
test_shape=test_points;
[pitch,yaw,roll] = ComputePose(PDM_49,test_shape(:));
filename='framesdata.xlsx';
header = {'Pitch', 'yaw ','roll'};
new_data = num2cell([pitch(:), yaw(:), roll(:)]);
output = [header; new_data];
xlswrite(filename,output);
end
plot(test_shape(:,1),test_shape(:,2),'b*');
title([num2str(i),' : Pitch = ',num2str(pitch),' ; Yaw = ',num2str(yaw),' ; Roll = ',num2str(roll)]);
set(gcf,'units','normalized','outerposition',[0 0 1 1]);
pause(0.5);
close all;
end
As #excaza stated, you will need to move the xlswrite command out of your loop or specify the cells you are writing. Please see the xlswrite Doc for more information. The correct syntax would be :
xlswrite(filename,A,xlRange)
The following is the example they provide:
filename = 'testdata.xlsx';
A = {'Time','Temperature'; 12,98; 13,99; 14,97};
sheet = 2;
xlRange = 'E1';
xlswrite(filename,A,sheet,xlRange)
You will just need to provide xlswrite the address to start writing data.