I'm trying to write a Graph into a binary file by using flatbuffers. A graph consists of nodes and edges. Every node has at least one edge and every edge consists of two nodes.
Excerpt from MyGraph.fbs:
namespace MyGraph;
table Node {
edges:[Edge];
}
table Edge {
startNode:Node;
endNode:Node;
}
table Graph {
allNodes:[Node];
}
root_type Graph;
Now I want to create a simple graph and write it into a bytefile:
FlatBufferBuilder fbb;
// create first node
auto node1mloc = DG::CreateNode(fbb, 0, 0);
// create second node
auto node2mloc = DG::CreateNode(fbb, 0, 0);
// create edge between first and second node
auto edgeloc = DG::CreateEdge(fbb, node1mloc, node2mloc);
// ???
// store the edge in the edges-vector of node1 and node2
// ???
// store nodes in graph
flatbuffers::Offset<Node> nodes[] = {node1mloc, node2mloc};
auto allNodes = fbb.CreateVector(nodes, 2);
auto graphloc = DG::CreateGraph(fbb, allNodes);
DG::FinishGraphBuffer(fbb, graphloc);
// write graph into file
auto buffer_pointer = fbb.GetBufferPointer();
SaveFile("myfile2.bin", reinterpret_cast<const char *>(buffer_pointer), fbb.GetSize(), true);
// load graph from file
string binData;
LoadFile("myfile2.bin", true, &binData);
auto graph = DG::GetGraph(binData.data());
cout << graph->allNodes()->size() << endl;
assert(graph->allNodes()->size() == 2);
The Problem is, that after creating the nodes, I can't add the edge to the edges-vector of node1 and node2. Is there a solution for that kind of cyclic dependencies between two types.
You cannot store cyclic structures in a FlatBuffer (it enforces that children always come before parents, using unsigned offsets).
You can store DAGs, however.
To encode a cyclic structure, you'll have to use indices for either Nodes or Edge references, e.g.
table Edge {
startNode:uint;
endNode:uint;
}
This means these node references are an index into allNodes.
Note that there's very few serialization formats that allow graphs, e.g. Protocol Buffers and JSON both only allow trees.
This works in FlatBuffersSwift but is not supported in the official FlatBuffers implementation.
//: Playground - noun: a place where people can play
import Foundation
var str = "Hello, playground"
let (f1, f2, f3, f4) = (Friend(), Friend(), Friend(), Friend())
f1.name = "Maxim"
f2.name = "Leo"
f3.name = "Boris"
f4.name = "Marc"
let f5 = Friend()
f5.name = "Daria"
f1.friends = [f1, f2, f3, f4]
f2.friends = [f1, f4]
f3.friends = [f2, f4]
f1.lover = Female(ref: f5)
f5.lover = Male(ref: f1)
f1.father = Friend()
f1.father?.name = "Issai"
f1.mother = Friend()
f1.mother?.name = "Margo"
let data = f1.toByteArray()
let f = Friend.fromByteArray(UnsafeBufferPointer(start:UnsafePointer<UInt8>(data), count: data.count))
print(f.friends[2]?.friends[0]?.friends[0]?.name)
print(((f.lover as? Female)?.ref?.lover as? Male)?.ref?.name)
let lazyF = Friend.Fast(data)
let girlFriend = (lazyF.lover as! Female.Fast).ref
let boyFriend = (girlFriend?.lover as! Male.Fast).ref
lazyF == boyFriend
I asked in the google groups chat if it would be of interest for main project.
Seems like it will not happen any time soon.
https://groups.google.com/forum/#!topic/flatbuffers/Y9K9wRKSHxg
Related
I'm trying to match two lists to another. In one list are items of crypto trades, the other contains so called candlesticks, which represents a price of crypto asset for one minute. A candlestick is limited by open time and close time. One trade item belongs exactly to one candlestick set. So I step through the trades list an for each item I apply a filter of two conditions. Unfortunately the filter returns no matching data. When I compare the trades data with candlestick items manually, I get a match. Here is the code of the data filter.
TradesDbHandler(dbConnector).use { dbHandler ->
val rowsInTime = dbHandler.readTimeframe(startTime, buffer)
rowsInTime.distinctBy { it.symbol }.forEach {
val symbolFilter = rowsInTime.filter { row -> row.symbol == it.symbol }
val symbolMinTime = symbolFilter.minByOrNull { it.time }
val symbolMaxTime = symbolFilter.maxByOrNull { it.time }
val tempKlines = binanceClient.getCandleSticks( symbolMaxTime!!.symbol,
symbolMinTime!!.time,
symbolMaxTime!!.time ) {
log(">>> $it")
}
val klines = mutableListOf<KlineRow>()
klines.plusElement(tempKlines.filter { row ->
(row.opentime <= it.time) &&
(row.closetime >= it.time) })
}
}
The code was not the problem but the data. Therefore no matches could be found. Thread can be closed.
Suppose I have two class:
class Key {
private Integer id;
private String key;
}
class Value {
private Integer id;
private Integer key_id;
private String value;
}
Now I fill the first list as follows:
List<Key> keys = new ArrayLisy<>();
keys.add(new Key(1, "Name"));
keys.add(new Key(2, "Surname"));
keys.add(new Key(3, "Address"));
And the second one:
List<Value> values = new ArrayLisy<>();
values.add(new Value(1, 1, "Mark"));
values.add(new Value(2, 3, "Fifth Avenue"));
values.add(new Value(3, 2, "Fischer"));
Can you please tell me how can I rewrite the follow code:
for (Key k : keys) {
for (Value v : values) {
if (k.getId().equals(v.getKey_Id())) {
map.put(k.getKey(), v.getValue());
break;
}
}
}
Using Lambdas?
Thank you!
‐------UPDATE-------
Yes sure it works, I forget "using Lambdas" on the first post (now I added). I would like to rewrite the two nested for cicle with Lamdas.
Here is how you would do it using streams.
stream the keylist
stream an index for indexing the value list
filter matching ids
package the key instance key and the value instance value into a SimpleEntry.
then add that to a map.
Map<String, String> results = keys.stream()
.flatMap(k -> IntStream.range(0, values.size())
.filter(i -> k.getId() == values.get(i).getKey_id())
.mapToObj(i -> new AbstractMap.SimpleEntry<>(
k.getKey(), values.get(i).getValue())))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
results.entrySet().forEach(System.out::println);
prints
Address=Fifth Avenue
Surname=Fischer
Name=Mark
Imo, your way is much clearer and easier to understand. Streams/w lambdas or method references are not always the best approach.
A hybrid approach might also be considered.
allocate a map.
iterate over the keys.
stream the values trying to find a match on key_id's and return first one found.
The value was found (isPresent) add to map.
Map<String,String> map = new HashMap<>();
for (Key k : keys) {
Optional<Value> opt = values.stream()
.filter(v -> k.getId() == v.getKey_id())
.findFirst();
if (opt.isPresent()) {
map.put(k.getKey(), opt.get().getValue());
}
}
[RESOLVED]
I'm building a game engine that uses LuaBridge in order to read components for entities. In my engine, an entity file looks like this, where "Components" is a list of the components that my entity has and the rest of parameters are used to setup the values for each individual component:
-- myEntity.lua
Components = {"MeshRenderer", "Transform", "Rigidbody"}
MeshRenderer = {
Type = "Sphere",
Position = {0,300,0}
}
Transform = {
Position = {0,150,0},
Scale = {1,1,1},
Rotation = {0,0,0}
}
Rigidbody = {
Type = "Sphere",
Mass = 1
}
I'm currently using this function (in C++) in order to read the value from a parameter (given its name) inside a LuaRef.
template<class T>
T readParameter(LuaRef& table, const std::string& parameterName)
{
try {
return table.rawget(parameterName).cast<T>();
}
catch (std::exception e) {
// std::cout ...
return NULL;
}
}
For example, when calling readVariable<std::string>(myRigidbodyTable, "Type"), with myRigidbodyTable being a LuaRef with the values of Rigidbody, this function should return an std::string with the value "Sphere".
My problem is that when I finish reading and storing the values of my Transform component, when I want to read the values for "Ridigbody" and my engine reads the value "Type", an unhandled exception is thrown at Stack::push(lua_State* L, const std::string& str, std::error_code&).
I am pretty sure that this has to do with the fact that my component Transform stores a list of values for parameters like "Position", because I've had no problems while reading components that only had a single value for each parameter. What's the right way to do this, in case I am doing something wrong?
I'd also like to point out that I am new to LuaBridge, so this might be a beginner problem with a solution that I've been unable to find. Any help is appreciated :)
Found the problem, I wasn't reading the table properly. Instead of
LuaRef myTable = getGlobal(state, tableName.c_str());
I was using the following
LuaRef myTable = getGlobal(state, tableName.c_str()).getMetatable();
Writing a WP8 Silverlight app. Is there a standard .NET technique available in this environment I can use to serialize an object like this
private static List<MemoryStream> MemoryStreamList = new List<MemoryStream>();
to save it to a file and restore it later?
I tried to use DataContractJsonSerializer for this which is good to serialize a List of simple custom objects, but it fails for List (I get System.Reflection.TargetInvocationException).
I would suggest converting your list to a list of byte arrays before persisting and then you should be able to serialize. Of course this comes with some overhead at deserialization as well.
Serialization part:
byte[] bytes = null;
var newList = MemoryStreamList.Select(x => x.ToArray()).ToList();
XmlSerializer ser = new XmlSerializer(newList.GetType());
using (var ms = new MemoryStream())
{
ser.Serialize(ms, newList);
//if you want your result as a string, then uncomment to lines below
//ms.Seek(0, SeekOrigin.Begin);
//using (var sr = new StreamReader(ms))
//{
//string serializedStuff = sr.ReadToEnd();
//}
//else you can call ms.ToArray() here and persist the byte[]
bytes = ms.ToArray();
}
Deserialization part:
using (var ms = new MemoryStream(bytes))
{
var result = ser.Deserialize(ms) as List<byte[]>;
}
I have a shape file (Sample.shp) along with two other files (Sample.shx and Sample.dbf), which has geometry (polygons) defined for 15 pincodes of Bombay.
I am able to view the .shp file using the Quickstart tutorial.
File file = JFileDataStoreChooser.showOpenFile("shp", null);
if (file == null) {
return;
}
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
// Create a map content and add our shapefile to it
MapContent map = new MapContent();
map.setTitle("Quickstart");
Style style = SLD.createSimpleStyle(featureSource.getSchema());
Layer layer = new FeatureLayer(featureSource, style);
map.addLayer(layer);
// Now display the map
JMapFrame.showMap(map);
Now I want to convert the geometry of these 15 pincodes to 15 Geometry/Polygon objects so that I can use Geometry.contains() to find if a point falls in a particular Geometry/Polygon.
I tried:
ShapefileReader r = new ShapefileReader(new ShpFiles(file),true,false,geometryFactory);
System.out.println(r.getCount(0)); >> returns 51
System.out.println(r.hasNext()); >> returns false
Any help is really appreciated
In fact you don't need to extract the geometries your self - just create a filter and iterate through the filtered collection. In your case there will probably be only one feature returned.
Filter pointInPolygon = CQL.toFilter("CONTAINS(the_geom, POINT(1 2))");
SimpleFeatureCollection features = source.getFeatures(filter);
SimpleFeatureIterator iterator = features.features();
try {
while (iterator.hasNext()) {
SimpleFeature feature = iterator.next();
Geometry geom = (Geometry) feature.getDefaultGeometry();
/*... do something here */
}
} finally {
iterator.close(); // IMPORTANT
}
For a full discussion of querying datastores see the Query Lab.
I used the above solution and tried a few combinations. Just changed "THE_GEOM" to lower case and POINT is in order (Lon Lat)
Filter filter = CQL.toFilter("CONTAINS(the_geom, POINT(72.82916 18.942883))");
SimpleFeatureCollection collection=featureSource.getFeatures(filter);
SimpleFeatureIterator iterator = collection.features();
try {
while (iterator.hasNext()) {
SimpleFeature feature = iterator.next();
.....
}
} finally {
iterator.close(); // IMPORTANT
}