Problem with codepoints/integer in XQuery - xquery

So im trying to execute this simple function:
declare function local:decodeBase64() as element(){
<root-element>
{
let $codepointsString := "77 97 110"
let $codepoints := fn:replace( $codepointsString,' ',', ')
let $x := fn:codepoints-to-string(xs:integer($codepoints))
return
$x
}
</root-element>
};
but i'm getting a error that i think it's because of xs:integer
however i can execute this code with the integer hardcoded
let $x := codepoints-to-string((77, 97, 110))
I noticed that i can run the code if i declare $codepoints as xs:integer* but i dont't know get a codePoint inside an element and use as xs:integer* to call codepoints-to-string function.
error:
http://www.w3.org/2005/xqt-errors}FORG0001: "77 97 110": invalid value for cast/constructor: {http://www.w3.org/2001/XMLSchema}integer: error: decimal: Invalid decimal value: unexpected char '32'

The original string needs to be split to multiple codepoint strings. The resulting strings can then be converted to integers:
let $codepointsString := "77 97 110"
let $codepoints := (
for $string in fn:tokenize($codepointsString, " ")
return xs:integer($string)
)
return fn:codepoints-to-string($codepoints)

Related

Unable to understand this xquery statement

I am new to xquery and unable to understand what does it means :
$bottles=getallBottles()
$cups=getallCups()
<containers>
{
($bottles,$cups) //this line i am unable to get
}
<containers>
The comma forms a sequence. Presumably $bottles is a sequence of zero-to-many items and $cups is a sequence of zero-to-many items. The comma forms a sequence of all of the items in $bottles and all of the items in $cups.
For example:
let $x := (1, 2, 3)
let $y := ('a', 'b', 'c')
return ($x,$y)
yields:
1 2 3 a b c
In the above example, the parentheses are necessary so that forming the sequence of $x, $y takes precedence over return and the entire constructed sequence is returned.
In an example similar to the original question, parentheses are unnecessary because precedence is not ambiguous:
let $x := <a><x>5</x><x>6</x></a>
let $y := <b><y>1</y><y>2</y></b>
return <container>{$x, $y}</container>
yields:
<container><a><x>5</x><x>6</x></a><b><y>1</y><y>2</y></b></container>

How to count number of occurrences of a character in an array in Pascal

I have to script a pascal code that rations into calculation the frequency of a character's appearance in the code and displays it through the output mode
Input P2 changes:
Second Attempt at the coding phase
I tried revisioning the code.I added the output variable writeln('input array of characters'); & writeln('Number of Occurrences',k);, which should help me output how many times did the S character appear overall in the code, plus utilised the for & if commands to have the final values showcased based on the conditions, if the frequency is 1 then count in S, still getting errors, take a look at the Input P2 & Output P2
Input P1
function Count(t, s: String): Integer;
var
Offset, P: Integer;
begin
Result := 0;
Offset := 1;
P := PosEx(t, s, Offset);
while P > 0 do
begin
Inc(Result);
P := PosEx(t, s, P + 1);
end;
end;
Output P2
Target OS: Linux for x86-64
Compiling main.pas
main.pas(5,3) Error: Identifier not found "Result"
main.pas(7,8) Error: Identifier not found "PosEx"
main.pas(8,3) Error: Identifier not found "unsigned"
main.pas(8,12) Fatal: Syntax error, ";" expected but "identifier N" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
-------------------------------------------------------------------
Input P2
program p1
var S:string
i:integer
begin
writeln('input array of characters');
k:=O;
for i:=1 to length (S) do
if (S[i])='m') and (S[i+1]='a') then k:=k+1;
writeln('Number of Occurrences',k);
Readln;
end.
Output P2
Compiling main.pas
main.pas(2,1) Fatal: Syntax error, ";" expected but "VAR" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
The errors you see in the first block:
Identifier not found "Result"
Standard Pascal doesn't recognize the pseudovariable Result. In some Pascal implementations (like e.g. Delphi) it can be used to assign a value to the function result. The Pascal you are using needs to have the result of a function assigned to the name of the function. For example:
function Whatever(): integer;
begin
Whatever := 234;
end;
Identifier not found "PosEx"
Not all Pascal implementations include the PosEx() function. You need to use Pos() instead. But, the standard implementation of Pos() doesn't include the "search start position" that PosEx has. Therefore you need to ditch Pos() and do as you do in "Input P2", that is traverse the text character per character and count the occurances as you go.
Identifier not found "unsigned"
Seems you have removed that unknown identifier.
The error you see in the second block:
In Output P2 the error message should be clear. You are missing a semicolon where one is needed. Actually you are missing three of them.
You are also missing the line that reads user input: ReadLn(S);.
Finally, to calculate both upper and lower case characters you can use an extra string variable, say SU: string to which you assign SU := UpperCase(S) after reading user input, and then use that string to count the occurances.
I think this is more like what you want to do:
function Count(t, s: String): Integer;
var
Offset,Res, P: Integer;
begin
Res := 0
Offset := 1;
repeat
P := Pos(t, s, Offset);
if p>0 then
Inc(Res);
Offset := P+1
untl P = 0;
Count := Res;
end;
Now, if you don't have Pos, you can implement it:
Function Pos(const t,s:string; const Start:integer):Integer;
Var
LS, LT, {Length}
IxS, IxT, {Index)
R: Integer; {Result}
begin
R := 0;
{use only one of the two following lines of code}
{if your compiler has length}
LS := length(S); LT := Length(T);
{If it does not}
LS := Ord(s[0]); LT := Ord(T[0]);
if (LS <= LT) {if target is larger than search string, it's not there}
and (Start<=LT) and {same if starting position beyond size of S}
(Start+LT <-LS) then {same if search would go beyond size of S}
begin {Otherwise, start the search}
ixT := 1;
ixS := Start;
repeat
Inc(R); {or R:= R+1; if INC not available }
If (S[ixS] <> T[ixT]) then
R := 0 {they don't match, we're done}
else
begin {Move to next char}
Inc(ixS);
Inc(ixT);
end;
until (R=0) or (ixT>LT); {if search failed or end of target, done}
Pos := R;
end;

Writing raw bits to a file in Lazarus

Let's suppose I generate a string of randomly ordered 1's and 0's.
If I write said string to a file, it will be written as an ANSI string, which is not what I want to do. I want to instead write the 1's and 0's in the string as raw bits. How can I achieve this?
You could iterate through the input string, character by character, and replace every '0' by a #0, and every '1' by a #1.
const
txt = '0001010001011110101110101010000001011111';
var
s: String;
i: Integer;
begin
SetLength(s, Length(txt));
for i:=1 to Length(txt) do
if txt[i] = '0' then
s[i] := #0
else if txt[i] = '1' then
s[i] := #1
else
begin
WriteLn('Unsupported character in input string');
Halt;
end;
//... write to file here (you should know how to do it) ...
end;
Or you could subtract the ordinal value of the character '0' from each character and cast the result back to char. The result will be #0 for '0' or #1 for '1'.
SetLength(s, Length(txt));
for i := 1 to Length(txt) do
s[i] := char(ord(txt[i]) - ord('0'));

Python: Type Error unsupported operand type(s) for +: 'int' and 'str'

I'm really stuck, I am currently reading Python - How to automate the boring stuff and I am doing one of the practice projects.
Why is it flagging an error? I know it's to do with the item_total.
import sys
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1', }
def displayInventory(inventory):
print("Inventory:")
item_total = sum(stuff.values())
for k, v in inventory.items():
print(v + ' ' + k)
a = sum(stuff.values())
print("Total number of items: " + item_total)
displayInventory(stuff)
error i get:
Traceback (most recent call last):
File "C:/Users/Lewis/Dropbox/Python/Function displayInventory p120 v2.py", line 17, in
displayInventory(stuff)
File "C:/Users/Lewis/Dropbox/Python/Function displayInventory p120 v2.py", line 11, in displayInventory
item_total = int(sum(stuff.values()))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Your dictionary values are all strings:
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1', }
yet you try to sum these strings:
item_total = sum(stuff.values())
sum() uses a starting value, an integer, of 0, so it is trying to use 0 + '12', and that's not a valid operation in Python:
>>> 0 + '12'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
You'll have to convert all your values to integers; either to begin with, or when summing:
item_total = sum(map(int, stuff.values()))
You don't really need those values to be strings, so the better solution is to make the values integers:
stuff = {
'Arrows': 12,
'Gold Coins': 42,
'Rope': 1,
'Torches': 6,
'Dagger': 1,
}
and then adjust your inventory loop to convert those to strings when printing:
for k, v in inventory.items():
print(v + ' ' + str(k))
or better still:
for item, value in inventory.items():
print('{:12s} {:2d}'.format(item, value))
to produce aligned numbers with string formatting.
You are trying to sum a bunch of strings, which won't work. You need to convert the strings to numbers before you try to sum them:
item_total = sum(map(int, stuff.values()))
Alternatively, declare your values as integers to begin with instead of strings.
This error produce because you was trying sum('12', '42', ..), so you need to convert every elm to int
item_total = sum(stuff.values())
By
item_total = sum([int(k) for k in stuff.values()])
The error lies in line
a = sum(stuff.values())
and
item_total = sum(stuff.values())
The value type in your dictionary is str and not int, remember that + is concatenation between strings and addition operator between integers. Find the code below, should solve the error, converting it into int array from a str array is done by mapping
import sys
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1'}
def displayInventory(inventory):
print("Inventory:")
item_total = (stuff.values())
item_total = sum(map(int, item_total))
for k, v in inventory.items():
print(v + ' ' + k)
print("Total number of items: " + str(item_total))
displayInventory(stuff)

XQuery difference between same function different implementation

Return the number of cycles:
let $bd := doc("document")
return count ( for $c in $bd//cycle
where $c[#id]
return $c
)
Every cycle has an ID, not important here but it is a must to specify it.
What is the difference between the above use of count and the below use of count?
let $bd := doc("document")
let $c := $bd//cycle[#id]
return count($c)
I dont know the difference between these 2 XQueries return same result but following the same pattern the next 2 queries should work but the 2nd one doesnt... Here they are:
The total of hours of modules which is above 100.
*Working query*
let $bd:=doc("document")
return sum (
for $m in $bd//module[#id]
where $m/hours>100
return $m/hours
)
*Not working query*
let $bd := doc("document")
for $c in $bd//module[#id]
where $c/hours>100
return sum($c/hours)
Id like to know why following the same "pattern" the second query is not working.
The output of the not working query is this one:
160 160 256 224 192 160
Its not the result i need, I want the sum of all them.
The first two expressions are functionally equivalent. The difference is the use of FLWOR vs. XPath to select your sequence.
In the second example, you are calling sum() on each item of the sequence ($c/hours), instead of on the sequence itself:
let $bd := doc("document")
return sum(
for $c in $bd//module[#id]
where $c/hours>100
return $c/hours)
You could also use XPath:
let $bd := doc("document")
let $c := $bd//module[#id][hours>100]
return sum($c/hours)
Or similarly assign the result of the FLWOR to a variable and sum that:
let $bd := doc("document")
let $c :=
for $m in $bd//module[#id]
where $m/hours>100
return $m/hours
return sum($c)

Resources