XQuery expression with predicates - xquery

I'm trying to use an expression with a predicate to display the child nodes for each parent node (the exercise looks silly because this is test data: the final solution has to draw in data from other xml files).
A sample of the data is as follows:
<Schools>
<School>
<name>St John's</name>
<AcademicYear year = "2017"></AcademicYear>
<Subject>English</Subject>
<Subject>Geography</Subject>
<Subject>Maths</Subject>
<AcademicYear year = "2016"></AcademicYear>
<Subject>Maths</Subject>
<Subject>Textiles</Subject>
<Subject>English</Subject>
<AcademicYear year = "2015"></AcademicYear>
<Subject>History</Subject>
<Subject>French</Subject>
<Subject>Spanish</Subject>
</School>
<School>
<name>Marsh Academy</name>
<AcademicYear year = "2017"></AcademicYear>
<Subject>Science</Subject>
<Subject>Geography</Subject>
<Subject>Computer science</Subject>
<AcademicYear year = "2016"></AcademicYear>
<Subject>English</Subject>
<Subject>History</Subject>
<Subject>Maths</Subject>
<AcademicYear year = "2015"></AcademicYear>
<Subject>French</Subject>
<Subject>Geography</Subject>
<Subject>Art</Subject>
</School>
</Schools>
The query is below:
<Schools>
{for $School in doc("test.xml")/Schools/School
return
<School>
<Name>
{$School/name}
</Name>
{for $i in doc("test.xml")/Schools/[School = $School]/AcademicYear
return
<AcademicYear>
{$i/#year}
<subject><teacher></teacher><scale></scale></subject>
</AcademicYear>}
</School>}
</Schools>
The error appears says "node expected, array found" in relation to line 8. I've tried both a for loop, and simply placing an expression inside the academic year tags as follows
{doc("test.xml")/Schools/[School = $School]/AcademicYear/#year}
Sorry - I'm sure it is simple. I'm a beginner!

There is no child node preceding the predicate.
When selecting the School elements, move it outside of the predicate as the child node selected from the Schools element, and then inside the predicate filter, refer to the current School element with .:
for $i in doc("test.xml")/Schools/School[. = $School]/AcademicYear
But if you are iterating over the elements from the same document, why not just use the already selected $School:
for $i in $School/AcademicYear

Related

Finding children of IfcBuildingStorey using ifcopenshell

By using ifchopenshell I can easily traverse all storeys using this code
for ifc_storey in ifc_file.by_type("IfcBuildingStorey"):
print(str(ifc_storey.Name))
However, for each storey I would like to find all the Ifc elements of type IfcSpace, that belongs to it.
How can I query this? Thank you.
I finally solved it using this code:
def getChildrenOfType(ifcParentElement,ifcType):
items=[]
if type(ifcType) != list:
ifcType=[ifcType]
_getChildrenOfType(items,ifcParentElement,ifcType,0)
return items
def _getChildrenOfType(targetList,element,ifcTypes,level):
# follow Spatial relation
if (element.is_a('IfcSpatialStructureElement')):
for rel in element.ContainsElements:
relatedElements = rel.RelatedElements
for child in relatedElements:
_getChildrenOfType(targetList,child, ifcTypes, level + 1)
# follow Aggregation Relation
if (element.is_a('IfcObjectDefinition')):
for rel in element.IsDecomposedBy:
relatedObjects = rel.RelatedObjects
for child in relatedObjects:
_getChildrenOfType(targetList,child, ifcTypes, level + 1)
for typ in ifcTypes:
if (element.is_a(typ)):
targetList.append(element)

Update dictionary key inside list using map function -Python

I have a dictionary of phone numbers where number is Key and country is value. I want to update the key and add country code based on value country. I tried to use the map function for this:
print('**Exmaple: Update phone book to add Country code using map function** ')
user=[{'952-201-3787':'US'},{'952-201-5984':'US'},{'9871299':'BD'},{'01632 960513':'UK'}]
#A function that takes a dictionary as arg, not list. List is the outer part
def add_Country_Code(aDict):
for k,v in aDict.items():
if(v == 'US'):
aDict[( '1+'+k)]=aDict.pop(k)
if(v == 'UK'):
aDict[( '044+'+k)]=aDict.pop(k)
if (v == 'BD'):
aDict[('001+'+k)] =aDict.pop(k)
return aDict
new_user=list(map(add_Country_Code,user))
print(new_user)
This works partially when I run, output below :
[{'1+952-201-3787': 'US'}, {'1+1+1+952-201-5984': 'US'}, {'001+9871299': 'BD'}, {'044+01632 960513': 'UK'}]
Notice the 2nd US number has 2 additional 1s'. What is causing that?How to fix? Thanks a lot.
Issue
You are mutating a dict while iterating it. Don't do this. The Pythonic convention would be:
Make a new_dict = {}
While iterating the input a_dict, assign new items to new_dict.
Return the new_dict
IOW, create new things, rather than change old things - likely the source of your woes.
Some notes
Use lowercase with underscores when defining variable names (see PEP 8).
Lookup values rather than change the input dict, e.g. a_dict[k] vs. a_dict.pop(k)
Indent the correct number of spaces (see PEP 8)

XQuery "flattening" an element

I am extracting data from an XML file and I need to extract a delimited list of sub-elements. I have the following:
for $record in //record
let $person := $record/person/names
return concat($record/#uid/string()
,",", $record/#category/string()
,",", $person/first_name
,",", $person/last_name
,",", $record/details/citizenships
,"
")
The element "citizenships" contains sub-elements called "citizenship" and as the query stands it sticks them all together in one string, e.g. "UKFrance". I need to keep them in one string but separate them, e.g. "UK|France".
Thanks in advance for any help!
fn:string-join($arg1 as xs:string*, $arg2 as xs:string) is what you're looking for here.
In your currently desired usage, that would look something like the following:
fn:string-join($record/details/citizenships/citizenship, "|")
Testing outside your document, with:
fn:string-join(("UK", "France"), "|")
...returns:
UK|France
Notably, ("UK", "France") is a sequence of strings, just as a query returning multiple citizenships would likewise be a sequence (the entries in which will be evaluated for their string value when passed to fn:string-join(), which is typed as taking a sequence of strings for its first argument).
Consider the following (simplified) query:
declare context item := document { <root>
<record uid="1">
<person>
<citizenships>
<citizenship>France</citizenship>
<citizenship>UK</citizenship>
</citizenships>
</person>
</record>
</root> };
for $record in //record
return concat(fn:string-join($record//citizenship, "|"), "
")
...and its output:
France|UK

Getting the level x value of the currentmember in a parent-child hierarchy in MDX

I have an employee parent-child hierarchy in a dimension called Employees which shows the managerial structure of an organisation. This hierarchy is [Employees].[Managerial].
There is another hierarchy that lists all the employees for an organisation. This is a single level hierarchy and it is [Employess].[All Employees].
I have a query that looks something like this:
With
Member measures.[FullTimeSalary] as measures.[Salary] * measures.[FullTimeFactor]
Select {measures.[FullTimeSalary]} on 0,
Non empty
{
[Employess].[All Employees].[All].Children
}
On 1
From MyCube
Where ([Time].[Month].&[201501])
Now if I expand the parent-child hierarchy (the [Employees].[Managerial] hierarchy) I can see each of the different levels of this structure( [Level 02], [Level 03], [Level 04], ect) and what I need to do now is create a new calculated measure called measures.[SupervisingManager] that brings back the currentmembers value at [Level 03] of the hierarchy.
I've tried
member measures.[SupervisingManager] as [Employees].[Managerial].[Level 03].currentmember.member_name
but that just returns "#Error" and using
member measures.[SupervisingManager] as [Employees].[Managerial].currentmember.member_name
returns that currentmember. I also experimented with
measures.[SupervisingManager] as [Employees].[Managerial].currentmember.parent.member_name
but the issue with this is that the currentmember can be located at any within the hierarchy. The only way I can think of doing this is to do a massive case statement, get the ordinal value of the current member and use the appropriate .parent.parent logic. Is there a neater way to do this?
Maybe something along these lines will help:
WITH
MEMBER measures.[FullTimeSalary] AS
measures.[Salary] * measures.[FullTimeFactor]
MEMBER measures.[SupervisingManager] AS
IIF
(
[Employees].CurrentMember.Parent.Level.Name = 'Level 03'
,[Employees].CurrentMember.Parent.Member_Caption
,'n/a'
)
SELECT
{
measures.[FullTimeSalary]
,measures.[SupervisingManager]
} ON 0
,NON EMPTY
{[Employess].[All Employees].[All].Children} ON 1
FROM MyCube
WHERE
[Time].[Month].&[201501];

How can I model a scalable set of definition/term pairs?

Right now my flashcard game is using a prepvocab() method where I
define the terms and translations for a week's worth of terms as a dictionary
add a description of that week's terms
lump them into a list of dictionaries, where a user selects their "weeks" to study
Every time I add a new week's worth of terms and translations, I'm stuck adding another element to the list of available dictionaries. I can definitely see this as not being a Good Thing.
class Vocab(object):
def __init__(self):
vocab = {}
self.new_vocab = vocab
self.prepvocab()
def prepvocab(self):
week01 = {"term":"translation"} #and many more...
week01d = "Simple Latvian words"
week02 = {"term":"translation"}
week02d = "Simple Latvian colors"
week03 = {"I need to add this":"to self.selvocab below"}
week03d = "Body parts"
self.selvocab = [week01, week02] #, week03, weekn]
self.descs = [week01d, week02d] #, week03, weekn]
Vocab.selvocab(self)
def selvocab(self):
"""I like this because as long as I maintain self.selvocab,
the for loop cycles through the options just fine"""
for x in range(self.selvocab):
YN = input("Would you like to add week " \
+ repr(x + 1) + " vocab? (y or n) \n" \
"Description: " + self.descs[x] + " ").lower()
if YN in "yes":
self.new_vocab.update(self.selvocab[x])
self.makevocab()
I can definitely see that this is going to be a pain with 20+ yes no questions. I'm reading up on curses at the moment, and was thinking of printing all the descriptions at once, and letting the user pick all that they'd like to study for the round.
How do I keep this part of my code better maintained? Anybody got a radical overhaul that isn't so....procedural?
You should store your term:translation pairs and descriptions in a text file in some manner. Your program should then parse the text file and discover all available lessons. This will allow you to extend the set of lessons available without having to edit any code.
As for your selection of lessons, write a print_lesson_choices function that displays the available lessons and descriptions to the user, and then ask for their input in selecting them. Instead of asking a question of them for every lesson, why not make your prompt something like:
self.selected_weeks = []
def selvocab(self):
self.print_lesson_choices()
selection = input("Select a lesson number or leave blank if done selecting: ")
if selection == "": #Done selecting
self.makevocab()
elif selection in self.available_lessons:
if selection not in self.selected_weeks:
self.selected_weeks.append(selection)
print "Added lesson %s"%selection
self.selvocab() #Display the list of options so the user can select again
else:
print "Bad selection, try again."
self.selvocab()
Pickling objects into a database means it'll take some effort to create an interface to modify the weekly lessons from the front end, but is well worth the time.

Resources