Sparql query using ASK WHERE based on COUNT result - count

I have the following basic query, which retrieves how many paintings were done by an artist
PREFIX dc: <http://purl.org/dc/terms/>
SELECT (COUNT(?numberOfPaintings) AS ?howMany)
WHERE { ?numberOfPaintings dc:creator "Artists_Name" . }
The variable ?howMany returns, let's say 20 (paintings) — so far, so good. I'd like to create another query that would use ASK WHERE to check whether the artist has painted more than 10 paintings, with an expected result of true or false.
I have tried using ?numberOfPaintings > 10 in the ASK portion of the query and I know I still need to do the COUNT, but so far I have only seen the > operator in the context of the FILTER function so I am not sure how to use it in other situations such as this one.

A alternative, with much the same effect: HAVING is the way to apply a filter after an aggregation operation:
PREFIX dc: <http://purl.org/dc/terms/>
SELECT (COUNT(?numberOfPaintings) AS ?howMany)
WHERE { ?numberOfPaintings dc:creator "Artists_Name" . }
HAVING ( ?howMany > 7 )
and then you can embed inside an ASK query.

Note: AndyS's answer is better for this specific scenario. While the nested select query and filter expressions that I've used here might be necessary for more complex query restrictions, this particular case can be solved more easily with having.
Let's say you've got data like this:
#prefix : <https://stackoverflow.com/questions/19826515/> .
:a1 :p :b1, :b2, :b3 .
:a2 :p :b1, :b2, :b3, :b4 .
:a3 :p :b1, :b2, :b3, :b4, :b5 .
Then a query like:
select ?a (count(?b) as ?num) where {
?a :p ?b
}
group by ?a
returns each ?a and the number of its ?bs:
-------------
| a | num |
=============
| :a3 | 5 |
| :a1 | 3 |
| :a2 | 4 |
-------------
Now you just need to wrap that query in another query and filter on ?num > .... E.g,. for 3:
prefix : <https://stackoverflow.com/questions/19826515/>
ask where {
{
select ?a (count(?b) as ?num) where {
?a :p ?b
}
group by ?a
}
filter( ?num > 3 )
}
Yes
For 7, we'll get no:
prefix : <https://stackoverflow.com/questions/19826515/>
ask where {
{
select ?a (count(?b) as ?num) where {
?a :p ?b
}
group by ?a
}
filter( ?num > 7 )
}
No

Related

Why does "reduce" not reduce in jq

tl;dr
In the language of jq, why is
$ jq --compact-output reduce (1,2,3,4) as $i ([]; . + [$i])
[1,2,3,4]
not the same as
$ jq --compact-output (1,2,3,4) | reduce . as $i ([]; . + [$i])
[1]
[2]
[3]
[4]
Full question and discussion
I have a somewhat theoretical question in that I have figured out a way to get the transformation I want, but still I do not understand completely why my first attempt failed and I would like an explanation.
Interactive example at jqPlay
I have input
{
"data": {
"k1": "v1"
},
"item": {
"data": {
"k2": "v2"
}
},
"list": {
"item": {
"data": {
"k3": "v3",
"k4": "v4"
}
}
}
}
and I want to collect into a single array all of the values of all of the keys that are immediate children of a "data" key. So the output I want is
["v1","v2","v3","v4"]
I eventually figured out that this works
jq --compact-output '[.. | .data? | select(.) | to_entries | .[].value]'
My question is, why could I not get it to work with reduce? I originally tried
.. | .data? | select(.) | to_entries | .[].value | reduce . as $v ([]; . + [$v])
but that gave me
["v1"]
["v2"]
["v3"]
["v4"]
instead. My question is why? reduce is supposed to iterate over multiple values, but what kind of multiple values does it iterate over and what kind are treated as separate inputs to separate reduce statements?
I guess my fundamental confusion is when is . (dot) an expression with 4 results and when is it 4 expressions? Or if . is always a an expression with 1 result, how do you collect 4 results back into 1, which is what reduce is all about? Is the array operator the only way?
An expression of the form:
reduce STREAM as ...
reduces the given stream, whereas the compound expression:
STREAM | reduce . as ...
invokes reduce once for each item in the stream, and for each invocation, . is that item.
If the concept of streams is unclear in this context, you might be interested to read a stream-oriented introduction to jq that I wrote:
https://github.com/pkoppstein/jq/wiki/A-Stream-oriented-Introduction-to-jq

Loading a set of recursively typed elements in F#

Suppose we had a table of vendors in a SQL database that we want to load into F#:
+----+--------+--------+
| ID | Name | Parent |
+----+--------+--------+
| 1 | Nest | 2 |
| 2 | Google | NULL |
| 3 | Apple | NULL |
+----+--------+--------+
Using type providers it is easy enough to get the table into F#, but suppose we wanted to then convert the data into a sequence of Vendors, where Vendor is a type like this:
Vendor = {ID: int; Name: String; Parent: Vendor option}
How would one go about doing that? The issue is that when creating the sequence of Vendors we can't map to each row a particular Vendor, since we don't have the sequence of Vendors yet. It would be good to also assume that the application allows for cycles (A could have B as a parent and B could have A as a parent), although in the case of vendors that doesn't really make sense.
You could instead define the Vendor type as:
Vendor = {ID: int; Name: String; ParentID: int option}
But this seems much less elegant, since every time you would want to reference the parent vendor you'd have to do some sort of lookup. Is there a known solution to this? It seems like a situation that could occur often (especially when dealing with graphs or trees).
It also seems like a solution could involve some sort of lazy evaluation, but it's not clear to me how the Lazy<'T> type in F# could be applied here.
It's not a particularly elegant solution, but the one that uses lazy evaluation for the parent would look something like this: you would have two types, one that matches the schema of your table and one recursive:
type Flat = { ID: int; Name: string; ParentID : int option}
type Recursive = { ID: int; Name: string; Parent: Lazy<Recursive> option}
Then let's set up something that looks like your table:
let records =
[
{ ID = 1; Name = "Nest"; ParentID = Some 2 }
{ ID = 2; Name = "Google"; ParentID = None }
{ ID = 3; Name = "Apple"; ParentID = None }
{ ID = 4; Name = "Yin"; ParentID = Some 5 }
{ ID = 5; Name = "Yang"; ParentID = Some 4 }
]
|> List.map (fun x -> x.ID, x)
|> Map.ofList
let getRecord recID = records |> Map.find recID
And you can put it together like this:
let rec getRecordRecursive recID =
let record = getRecord recID
{
ID = record.ID
Name = record.Name
Parent =
record.ParentID
|> Option.map (fun pid ->
Lazy.Create <| fun () ->
getRecordRecursive pid)
}
So in a sense you're using the lazy type to delay the next step of recursion until you need it. Otherwise getRecordRecursive 4 would give you a stack overflow.
But there are tradeoffs - you no longer get nice behaved equality on such records, for instance. I'm not convinced you're not better off with Flat records in the long run.

How to solve this grammar recursion?

I found this grammar for a calculator:
<Expression> ::= <ExpressionGroup> | <BinaryExpression> | <UnaryExpression> | <LiteralExpression>
<ExpressionGroup> ::= '(' <Expression> ')'
<BinaryExpression> ::= <Expression> <BinaryOperator> <Expression>
<UnaryExpression> ::= <UnaryOperator> <Expression>
<LiteralExpression> ::= <RealLiteral> | <IntegerLiteral>
<BinaryOperator> ::= '+' | '-' | '/' | '*'
<UnaryOperator> ::= '+' | '-'
<RealLiteral> ::= <IntegerLiteral> '.' | <IntegerLiteral> '.' <IntegerLiteral>
<IntegerLiteral> ::= <Digit> <IntegerLiteral> | <Digit>
<Digit> ::= '0' | '1' |'2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
Source: here
It looks great. So I wrote the lexer and started the parser. Now there is an infinite recursion that I can't solve between Expression and BinaryExpression.
My code for expression:
boolean isExpression() {
if (isExpressionGroup() || isBinaryExpression() || isUnaryExpression() || isLiteralExpression()) {
println("Expression!");
return true;
}
println("Not expression.");
return false;
}
And for binary expression:
boolean isBinaryExpression() {
if (isExpression()) {
peek(1);
if (currentLex.token == Token.BINARY_OPERATOR) {
peek(2);
if (isExpression()) {
peek(3);
println("Binary expression!");
return true;
} else peek(0);
} else peek(0);
} else peek(0);
return false;
}
So peek(int) is just a function for looking forward without consuming any lexemes. So my problem: My input is '2*3' . isExpression() gets called. isExpressionGroup() fails, because there is no '('. Then the isBinaryExpression() gets called, which calls isExpression(). isExpressionGroup() fails again, and isBinaryExpression() gets called again. And so on, until a stack overflow.
I know, there is ANTLR and JavaCC (and other tools), but I would like to do it without them.
Could anyone give a hand?
Dealing with left recursion in a hand-crafted top-descent parser is not easy. Parser generators that solve the problem have years of work in them. There are theoretical reasons for that.
The best solution if you don't want to use a tool is to eliminate the left recursion. The problem if you do it "by the book" is that you'll get an ugly grammar and an ugly parser that will be difficult to use.
But there's another solution. You can add enough rules to represent the precedence hierarchy of the operators, which is something you'd have to do anyway, unless you want to risk a a+b*c be parsed as (a+b)*c.
There are plenty of examples of non left-recursive grammars for expressions on the Web, and here in SO in particular. I suggest you take one of them, and start from there.

Find ultimate parent of an entity using recursion in c#

I have an Entity which in turn refers to same table which is its parent. Below is the table which describes it more better.
| ID | Source_ID |
+----+----------+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 4 |
Now, when I am at ID = 5, I need to fetch its ultimate parent, which is ID = 1.
I tried writing a function which is as below:
<entity> ultimateparententity;
internal <entity> FetchParentComponentRecursive(<entity> entity)
{
if (component.ParentEntity!= null)
{
FetchParentComponentRecursive(entity.ParentEntity);
}
else
{
ultimateparententity = entity;
return component;
}
return entity;
}
I am using variable declared at class level to know the ultimate parent. I am returning variable "Entity" which is never used later, but ultimateparententity is what is used. This approach works, but I am not too happy with this. Any directions will be helpful.
I'm not too familiar with C#, but the general structure of your recursive function looks off.
Try something along the lines of:
internal <entity> FetchParentComponentRecursive(<entity> entity)
{
if (component.ParentEntity == null)
{
return component;
}
else
{
return FetchParentComponentRecursive(entity.ParentEntity);
}
}
By the way, this very much depends on there being no circular references in your data set.

How to sort a Dictionary by values in Smalltalk?

I've got a Dictionary like this:
a PluggableDictionary(
Rankable1->8.5
Rankable2->9.0
)
I need just an OrderedCollection with the Rankable objects in descending order:
a OrderedCollection(
Rankable2
Rankable1
)
I noticed it is easy to sort by keys, but I found it a bit more difficult to sort by values. What is the smalltalk way of doing this?
If you need one shot sorted collection in noncritical loop you might use something like this (uses pharo syntax to initialize example dictionary):
pd := PluggableDictionary newFromPairs: { 'a' . 2 . 'b' . 1 . 'c' . 3} .
(pd associations asSortedCollection: [:x :y | x value < y value])
collect: [:assoc | assoc key].
If you would need it more often, than you might consider introducing your own class that will keep this collection calculated.
If you're using VisualWorks, you can take advantage of SortFunction and Symbol>>value behavior to reduce all of that down to
(aDictionary associations sort: #value ascending) collect: #key
If you can use Grease (eg, when using Seaside), you can
probably use its GROrderedMultiMap. It is intended for small dictionaries with probably multiple values per key.
On a second note, probably you can swap key and value, and just send #asSortedCollection, like this:
(Dictionary newFrom: { 2 -> 'b' . 1-> 'a' })
asSortedCollection "--> a SortedCollection('a' 'b')"
(Tested in Squeak and Pharo)
Got it:
^ ((SortedCollection sortBlock:
[:association :otherAssociation | association value > otherAssociation value])
addAll: theDictionary associations;
yourself) collect: [:association | association key]

Resources