Need guidance and tips on oxmlelement - python-docx

I am currently manipulating a word document using Python-docx and I would like to standardize every table/figure caption to either match with their corresponding heading or just increment them based on user choice.
I am currently stuck with the field code as I need to also update the field automatically. Below is a sample field code which I have from the document and would like to achieve
Table { STYLEREF 1 \s }-{ SEQ Table \* ARABIC \s 1} Random Heading Name
I have referenced from this github link
paragraph = document.add_paragraph('Table ', style='Caption')
run = run = paragraph.add_run()
r = run._r
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'begin')
r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.text = ' STYLEREF 1 \s '
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'begin')
r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.text = ' SEQ Table \* ARABIC \s 1'
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
I have tried using preserver and separate but they can't seem to get "-" which I need sitting in between the 2 field code.
So right now, my end product is:
Table { STYLEREF 1 \s }{ SEQ Table \* ARABIC \s 1} Random Heading Name

Related

How to get a drop-down filter in Spotfire Information Link?

Generally people use the default option that Spotfire gives. Connect to the DB and pull the set of columns that you need and create an Information Link and load the data to Spotfire.
However, I am using SQL Query to fetch data to Spotfire. I am creating a table similar to Views, and writing a simple stored procedure to pull the data:
Create procedure ProcA(In Start_Date date, IN End_Date date, In Site_Name text)
Begin
SELECT * FROM TableA where day between Start_Date and End_Date and
site_name = Site_Name;
This works fine if I am not using site name filtering.
The Information Links helps in filtering the date properly. But when it comes to Site Name, nothing works.
There are 2 requirements:
Is it possible to give a drop-down just like how filter comes for Date
How to pass multiple site names to pull only those sites into the Spotfire file
TL;DR: There are better ways to do this; if it's just for the column names, I don't think it's worth it to do part 2, since it's easy enough to change the sql in the information link, but it's possible.
Okay, I will try (read: fail) not to be too long-winded.
1) Is it possible to do a drop-down for dates? Yes. The easiest way to do this would be to pull a data table with all of your date choices available for the end user. Here's an example finding a list of better way to generate months/year table Remember when creating your dropdownlist that your Document Property has to have the Data type "Date", and then you should be able to set property values through Unique Values in column against your date column from the new data, the same as you would do for a string drop-down list.
If you have a small subset of specific dates to choose from, this probably isn't too bad. If the drop down list gets longer, your end-users can type in the date they're looking for to speed up their search (though in my experience, a lot of them will scroll through until they find the date they're looking for).
While this is perfectly acceptable, if you're at all comfortable adding javascript, I'd personally recommend using a Popup Calendar These are fairly straightforward for end-users, and can allow them to use the calendar or type it themselves. (And if they type something that isn't a date in, it's even kind enough to inform them with red letters and an exclamation mark that they haven't typed an actual date)
2) How to pass multiple site names to pull only those sites into the Spotfire file
Hoo boi, where to start.
Step one: How do you want to select your list of Site Names? I'm going to go ahead and assume you have a data table with a list of distinct Site Names.
Your next choice is how to let your user select which Site Names they want. General options are using a List Box Filter, displaying a table and using marked rows, or providing a text area where the user can type their selections themselves.
When I needed to do this, I did a combo of a data table and a text area, so that's what I'm going to describe here.
I start off by providing the user with a text area, formatted to "specific size" with a larger than usual height to prompt that, yes, they are allowed to type multiple rows. If they know the values they're looking for, they can type them in manually, or copy paste from an excel file, etc.
If they don't know what they're looking for, the list of Site Names would be in a Table displayed for the user, where they can then mark the rows they want on the visualization and push a button which will do a cursor through the list of marked Site Names, concatenate them together, and put them in the text box previously mentioned (Note: if you don't want to let them enter their list manually, you can leave off the text area, combine these next two pieces of code, and throw it straight into the SpecialFilterProperty).
Please note that cursors are slow; if you have more than a few thousand rows to cycle through, this may stall out for a few seconds.
Code for the button:
from Spotfire.Dxp.Application.Visuals import CrossTablePlot
from Spotfire.Dxp.Data import IndexSet
from Spotfire.Dxp.Data import RowSelection
from Spotfire.Dxp.Data import DataValueCursor
from Spotfire.Dxp.Data import DataSelection
TextFltr = ""
crossSource = Document.Data.Tables["Distinct_SiteNames"]
##Get a Row Count
rowCount = Document.Data.Tables["Distinct_SiteNames"].RowCount
##Index Set of all our rows
rowIndexSet=Document.ActiveMarkingSelectionReference.GetSelection(Document.Data.Tables["Distinct_SiteNames"]).AsIndexSet()
allRows = IndexSet(rowCount,True)
if rowIndexSet.IsEmpty != True:
allRows = rowIndexSet
colCurs = DataValueCursor.CreateFormatted(crossSource.Columns["Site_Name"])
##Optional: Loop through to determine average value
colTotal = ''
for row in crossSource.GetRows(allRows, colCurs):
colTotal += ', ' + colCurs.CurrentValue
if TextFltr == "":
TextFltr += colTotal[2:]
else:
TextFltr += colTotal
Document.Properties["SelectedSiteNames"] = TextFltr
from System.Collections.Generic import Dictionary
from Spotfire.Dxp.Application.Scripting import ScriptDefinition
import clr
scriptDef = clr.Reference[ScriptDefinition]()
Document.ScriptManager.TryGetScript("Change Special Filter Value", scriptDef)
params = Dictionary[str, object]()
Document.ScriptManager.ExecuteScript(scriptDef.ScriptCode, params)
At the bottom it references a second script; this is the script attached to the button that parses through the text area when the user wants to submit their selections and refresh the data table.
The General Code I've used is here, script titled "Change Special Filter Value", which allows delimiting by newline, tabs, commas, quotes, and a few others. Feel free to add or subtract here, depending on your user-base's needs.
strVals = Document.Properties["SelectedSiteNames"]
lst = ""
cnt = 0
x = 0
y = 0
z = 0
for letter in strVals:
if y == 1:
if letter == " ":
lst = lst + "'" + strVals[x:z] + "', "
y = 0
elif letter == ",":
lst = lst + "'" + strVals[x:z] + "', "
y = 0
elif letter == "\n":
lst = lst + "'" + strVals[x:z] + "', "
y = 0
elif letter == "\r":
lst = lst + "'" + strVals[x:z] + "', "
y = 0
elif letter == "'":
lst = lst + "'" + strVals[x:z] + "', "
y = 0
elif letter == '"':
lst = lst + "'" + strVals[x:z] + "', "
y = 0
elif letter == '\t':
lst = lst + "'" + strVals[x:z] + "', "
y = 0
else:
if letter <> " " and letter <> "," and letter <> "\n" and letter <> "\r" and letter <> "'" and letter <> '"' and letter <> "\t":
if y == 0:
cnt += 1
print letter
x = z
y = 1
z += 1
if y == 1:
lst = lst + "'" + strVals[x:z] + "', "
print lst
lst = lst.upper()
if len(lst) > 0:
lst = lst[1:len(lst) - 3]
Document.Properties["SpecialFilterValue"] = lst
Step one is now complete! You have a list of all your selected site names in a property that you can now pass to your stored procedure.
Note: I believe there's a limit to the number of characters Spotfire can pass through a string value. In my previous testing, I think it's been over 500,000 characters (it's been a while, so I don't remember exactly), so you have a lot of leeway, but it does exist, and depending on which data source you're using, it may be lower.
Step Two: Alter the stored Procedure
Your stored procedure will basically be something along the lines of this:
Create procedure ProcA(In Start_Date date, IN End_Date date, In Site_Name text)
Begin
DECLARE #Script nvarchar(max) =
N'
Select * from TableA where day between Start_Date and End_Date and Site_Name in (' + #Site_Name + ') '
EXECUTE (#Script)
Downright easy in comparison!
(No loop after all! The bizarre use case I was remembering doesn't apply here, unless you're also using a data base that doesn't allow you to pass parameters directly...)

SSRS Insert Space Between Numeric and Alpha Characters

I am having an issue where a field is stored in our database as '##ABC' with no space between the number and letters. The number can be anything from 1-100 and the letters can be any combination, so no consistency of beginning letter or numeric length.
I am trying to find a way to insert a space between the number and letters.
For example, '1DRM' would transform to '1 DRM'
'35PLT' would transform to '35 PLT'
Does anyone know of a way to accomplish this?
You can use regular expressions like the one below (assuming your pattern is digits-characters)
= System.Text.RegularExpressions.Regex.Replace( Fields!txt.Value, "(\d)(\D)", "$1 $2")
Unfortunately, there's no built in function to do this.
Fortunately, Visual Studio lets you create functions to help with things like this.
You can add Visual BASIC custom code by going to the Report Properties and going to the Custom Code tab.
You would just need to write some code to go through some text input character by character. If it finds a number and a letter in the next character, add a space.
Here's what I wrote in a few minutes that seems to work:
Function SpaceNumberLetter(ByVal Text1 AS String) AS String
DIM F AS INTEGER
IF LEN(Text1) < 2 THEN GOTO EndFunction
F = 1
CheckCharacter:
IF ASC(MID(Text1, F, 1)) >= 48 AND ASC(MID(Text1, F, 1)) <=57 AND ASC(MID(Text1, F + 1, 1)) >= 65 AND ASC(MID(Text1, F + 1, 1)) <=90 THEN Text1 = LEFT(Text1, F) + " " + MID(Text1, F+1, LEN(Text1))
F = F + 1
IF F < LEN(Text1) THEN GOTO CheckCharacter
EndFunction:
SpaceNumberLetter = Text1
End Function
Then you call the function from your text box expression:
=CODE.SpaceNumberLetter("56EF78GH12AB34CD")
Result:
I used text to test but you'd use your field.

Adding Html tag into the title of the Tree query in Oracle APEX

I have a requirement to make few text in the title of my tree query in Oracle APEX to bold by adding b tag. But when i do that, the tag is displayed at the front end. My query is as mentioned below. I do not want to see the b tag, rather i want the text enclosed by b tag to be bold. Please help.
SELECT
CASE
WHEN CONNECT_BY_ISLEAF = 1 THEN 0
WHEN level = 1 THEN 1
ELSE -1
END
AS status,
level,
CASE
WHEN level = 1 THEN questions
ELSE '<b>' -- Comes in the front end which i do not want
|| flow_condition
|| '</b>'
|| ' - '
|| questions
END
AS title,
NULL AS icon,
question_id AS value,
NULL AS tooltip,
--null as link
apex_page.get_url(
p_page => 401,
p_items => 'P401_QUESTION_ID',
p_values => question_id,
p_clear_cache => 401
) AS link
FROM
(
SELECT
mmq.*,
mmm.flow_condition
FROM
msd_mc_questions mmq
LEFT OUTER JOIN msd_mc_par_chld_mapping mmm ON (
mmq.parent_id = mmm.parent_question_id
AND
mmq.question_id = mmm.child_question_id
)
)
START WITH
parent_id IS NULL
CONNECT BY
PRIOR question_id = parent_id
ORDER SIBLINGS BY questions
Struggled with this for hours but then found a solution via jQuery. Create a dynamic action that on page load and executes javascript. Find all items with class .a-TreeView-label (assuming that's the class name at runtime that you get as well - check to be sure) and loop over them and for each one, replace its text with itself. This forces it to re-render as HTML. My code in the javascript task:
$(".a-TreeView-label").each(function(index){
$(this).replaceWith($(this).text());
});
On the item attribute "Escape special characters" change to "No"

substring in python 3 given line number and offset

I'm trying parsing an html page with the HTMLParser library in python 3.
The function HTMLParser.getpos() return the line number and the offset of the last tag parsed.
For example I know that the "string" I want starts in line number 10 offset 5 and ends in line number 30 offset 10 how can I get the substring from line 10 offset 5 to line 30 offset 10 ?
Thanks.
html = 'this holds the entire html code'
MyParser.feed(html) #now the parser works its magic
start = (10,5) #this is returned from HTMLParser.getpos(), 10 is the line number and 5 is the offset of that line
end = (30,10) #same here
#I want to do something like this (I know this is invalid python code)
substring = html.substring(start,end) #return the html code as a string from line 10 offset 5 to line 30 offset 10
Better Explanation:
I'm trying to get a substring from a string.
I understand in python 3 it's called slice: string[a:b]
so if I wanted the substring 'jonny' form the string 'Hello jonny smith'
I would do this: substring = 'Hello jonny smith'[6:11]
The problem is that HTMLParser.getpos() returns a tuple (line number, offset of that line) so I can't do: substring = multy_line_string[line number:offset]
Assuming you are interested in HTML parsing try lxml --> http://docs.python-guide.org/en/latest/scenarios/scrape/
Indeed HTMLParser records the line and position in the line.
Here is the way to record the position in the stream:
def updatepos(self, i, j):
self.rawpos = i
return super().updatepos(i, j)
Now, assuming the string you are looking for stands inside mytag:
def handle_starttag(self, tag, attrs):
if tag == 'mytag':
self.mytag_pos = self.rawdata.index('>', self.rawpos) + 1
def handle_endtag(self, tag):
if tag == 'mytag':
self.mytag_data = self.rawdata[self.mytag_pos:self.rawpos]

Remove STRING before / character MySQL

I have a column which contains data like
thumb/RANDOM_STRING.JPG
thumb/cat/RANDOM_STRING.JPG
thumb/test/again/RANDOM_STRING.JPG
I want to contain only the Image name. And want to DELETE every word before / character.
Here is what I have tried but it does not work
UPDATE wsr_jshopping_products
SET product_full_image =
REPLACE(product_full_image,'thumb//', '');
if you just want the filename to remain use:
UPDATE wsr_jshopping_products
SET product_full_image = REVERSE(
SUBSTRING(
REVERSE(product_full_image),1,
LOCATE('/',REVERSE(product_full_image))-1))