Is there any way (elegant way) to transform from a BDD select:
SELECT CONSOLIDATION_DATE d, SUM(CONSOLIDATED_VALUE) v
FROM MON_CONSOLIDATION_FIRST
GROUP BY CONSOLIDATION_DATE
into a JSON data structure like the following:
[[1369265180000, 2], [1369265141000, 3], [1369265141000, 2]]
Right now, I got this:
[{"D":1369265180000,"V":2},{"D":1369265141000,"V":3},{"D":1369296900000,"V":2}]
My "tools": MyBatis, Spring3, com.fasterxml.jackson.core to http://api.highcharts.com/highstock#series.data
I know I can do it by hand with something like this, but I'm searching a better way -- considering performance.
Finally I got a (good) solution implementing a ResultHandler with mybatis.
I did this:
List<Collection> answer = new ArrayList<Collection>();
#Override
public void handleResult(ResultContext context) {
final Map<?, ?> consolidations = (Map<?, ?>) context.getResultObject();
Collection<?> llista = consolidations.values();
answer.add(lista);
}
This is also a good solution for export to csv.
Related
Since I'm unable to use SQLite in a node-webkit app, I'm looking at LokiJS but I cannot seem to find an easy way of making joins or some kind of relations between 2 datasets.
One dataset is artists and the other is media.
Since it could possibly hold 5000 artists and a million medias, I think it would be better to avoid repetition by making the artist a subdocument of a media. Also if I modify the artist of 1000 media entries, it would require a lot of writing instead of just updating one single entry in the artist dataset.
The only join I found create the returned json as followed:
Object {
left: {
// artists
},
right: {
// media
}
}
What I would prefer is something more traditionnal like:
{
artist_id:
artist_name:
media_id:
media_title:
}
I looked at NeDB which offer joins more easily but wasn't updated for over 2 years now. and I cannot get SQLite3 to compile for nodewebkit 0.28.0 and got no answers from SO. Anyway, LokiJS looks way more fun to play with anyway since it's in memory and on disk.
So how can I join artists and media?
Thanks!
joinResult.map(data => {
let a = {}
a.artist_id = data.left.artist_id
a.artist_name = data.left.artist_name
a.media_id = data.right.media_id
a.media_title = data.right.media_title
return a
})
Use lodash to do final data manipulation.
I don't think left, right object should be a problem here. The code I am using is
const q = db.card.eqJoin(db.deck, "deckId", "$loki", (l, r) => {
const {front, back, note, srsLevel, nextReview, tags} = l;
return {
front, back, note, srsLevel, nextReview, tags,
deck: r.name
};
}).find(query);
const count = q.copy().count();
const data = q.offset(offset).limit(limit).data();
I have a nested JSON file, consisting of keys and values which are string only. But the structure of the JSON file is not fixed, so sometimes it could be nested 3 levels, sometimes only 2 levels.
I wonder how i could serialize this in strict mode?
"live" : {
"host" : "localhost",
"somevalue" : "nothing",
"anobject" : {
"one" : "two",
"three" : "four",
"five" : {
"six" : "seven"
}
}
}
If i would know the structure of the JSON, i simply would write my own class for it, but since the keys are not fixed, and also the nesting could be into several levels, i really wonder how i cut put such an object into a specific type.
Any help or hints appreciated
I think invariants will serve you well here. First off, it might be helpful to know that you can type a keyed tree strictly in Hack:
<?hh // strict
class KeyedTree<+Tk as arraykey, +T> {
public function __construct(
private Map<Tk, KeyedTree<Tk, T>> $descendants = Map{},
private ?T $v = null
) {}
}
(It must be a class because cyclic shape definitions are sadly not allowed)
I haven't tried it yet, but type_structures and Fred Emmott's TypeAssert look to also be of interest. If some part of your JSON blob is known to be fixed, then you could isolate the nested, uncertain part and build a tree out of it with invariants. In the limiting case where the whole blob is unknown, then you could excise the TypeAssert since there's no interesting fixed structure to assert:
use FredEmmott\TypeAssert\TypeAssert;
class JSONParser {
const type Blob = shape(
'live' => shape(
'host' => string, // fixed
'somevalue' => string, // fixed
'anobject' => KeyedTree<arraykey, mixed> // nested and uncertain
)
);
public static function parse_json(string $json_str): this::Blob {
$json = json_decode($json_str, true);
invariant(!array_key_exists('anobject', $json), 'JSON is not properly formatted.');
$json['anobject'] = self::DFS($json['anobject']);
// replace the uncertain array with a `KeyedTree`
return TypeAssert::matchesTypeStructure(
type_structure(self::class, 'Blob'),
$json
);
return $json;
}
public static function DFS(array<arraykey, mixed> $tree): KeyedTree<arraykey, mixed> {
$descendants = Map{};
foreach($tree as $k => $v) {
if(is_array($v))
$descendants[$k] = self::DFS($v);
else
$descendants[$k] = new KeyedTree(Map{}, $v); // leaf node
}
return new KeyedTree($descendants);
}
}
Down the road, you'll still have to supplement containsKey invariants on the KeyedTree, but that's the reality with unstructured data in Hack.
Im using an unwind query in neo4j, with a nodejs driver (https://github.com/philippkueng/node-neo4j)
What I am trying to do is include an array of objects in the unwind query.
It currently works if I hard code the string as shown below, but i'm trying to have the array inserted dynamically.
UNWIND [{Label:'User',Lang:'English'},{Label:'Usuario',Lang:'Español'},{Label:'用户',Lang:'中文_简体'}] as ll
Regardless of the query I use, after testing, the above works, but if I do something like the following it doesn't:
var MyList = [{Label:'User',Lang:'English'},{Label:'Usuario',Lang:'Español'},{Label:'用户',Lang:'中文_简体'}];
"UNWIND "+ MyList " + as ll"
The problem is that when you do "UNWIND " + MyList you convert MyList to string, and it will be something like [object Object],[object Object],.... My first idea was to use JSON.stringify but that produces a JSON, which is not ok in cypher syntax (it is { "Label": ... } instead of { Label: ... }). The solution is to use parameters:
var queryString = 'UNWIND {list} as ll // continue query';
var queryParams = { list: MyList };
db.cypherQuery(queryString, queryParams, function(err, res) {
// handle response
});
Ideally you would use the ll identifier in your query.
However by seeing you have a property named Label, I remind you that currently it is not possible to add labels dynamically.
A possible query you might do is :
UNWIND MyList AS ll
CREATE (user:User) SET user.lang = {ll}.Lang
Chris
I have a Groovy class which looks a lot like this:
class A {
B[] requests = []
}
In code, I have an array of A and I'd like to know how many B are contained within it. What's the most groovyish way to make that calculation? I know how to do it in Java, but it looks far uglier than I suspect Groovy would like it to be. Here's what I've worked out so far:
list.each{ a -> count += a.requests.size() }
Is there a better way?
When coding this, I'd invoke the KISS principle regarding maintenance and clarity. Not everything should use shiny features.
Your version is reasonably 'Groovy', though you may want to consider using the implicit variable it (see doc):
def count = 0
list.each{ count += it.requests.size() }
Use spread operator (*)
class A {
B[] requests = []
}
class B{
String name
}
assert [
new A(requests : [new B(name: 'John'), new B(name: 'Jim'),
new B(name: 'Alex')]),
new A(requests : [new B(name: 'Test'), new B(name: 'Alex')]),
new A(requests : [new B(name: 'John')])
]*.requests*.size() == [3, 2, 1]
I've a scenario to pass a List of char values to the query in Grails.
When I pass the List this is what happening
def accounts = ['A', 'B']
AND acct.account_status_cd in '${accounts}
the query looks like "AND acct.account_status_cd in '[A,B]'"
but it should be "AND acct.account_status_cd in ('A','B')"
how to achieve this?
Resolved it by Passing as a String...
String s = keys.collect { "'$it'" }.join( ',' )
It gives me S = 'A','B','C'
A solution could be a NamedQuery inside your domain class, something like this:
class Account {
// code omitted
static namedQueries = {
accountsInList { accountList ->
'in'("account_status_cd", accountList)
}
}
Then you can use this namedQuery like:
Account.accountsInList(['A', 'B']).list()
Ofcourse you can also use a withCriteria.
See the docs for more info:
http://grails.org/doc/2.2.x/ref/Domain%20Classes/createCriteria.html