I have a model in angularJS which is bound to firebase $scope.items=$firebase(blah) and I use ng-repeat to iterate through the items.
Every item in firebase has a corresponding geofire location by the key of the item.
How can I update my controller to only include items by a custom radius around the user? I don't want to filter by distance in angular, just ask firebase to only retrieve closer items (say 0.3km around a location). I looked around geoqueries but they have a different purpose and I don't know how to bind them to the model anyway. The user may change the radius and the items list should be updated accordingly, so they need to be bound somehow.
Any suggestion is welcome, but an example would be greatly appreciated as I don't have fluency in this trio of angular/firebase/geofire yet :P
It's difficult to figure out what you need to do without seeing your code. But in general you'll need to query a Firebase ref that contains the Geohash as either the name of the child or the priority.
A good example of such a data structure can be found here: https://publicdata-transit.firebaseio.com/_geofire/i
i
9mgzcy8ewt:lametro:8637: true
9mgzgvu3hf:lametro:11027: true
9mgzuq55cc:lametro:11003: true
9mue7smpb9:nctd:51117: true
...
l
...
lametro:11027
0: 33.737797
1: -118.294708
actransit:1006
actransit:1011
actransit:1012
...
The actual transit verhicles are under the l node. Each of them has an array contains the location of that vehicle as a longitutude and latitude pair.
The i node is an index that maps each vehicle to a Geohash. You can see that the name of each node is built up as <geohash>:<metroarea>:<vehicleid>.
Since the Geohash is at the start of the name, we can filter on Geohash with a Query:
var ref = new Firebase("https://publicdata-transit.firebaseio.com/_geofire");
var query = ref.child('i').startAt(null, '9mgzgvu3ha').endAt(null, '9mgzgvu3hz');
query.once('child_added', function(snapshot) { console.log(snapshot.name()); });
With this query Firebase will give us all nodes whose name falls within the range. If all is well, this will output the name of one node:
9mgzgvu3hf:lametro:11027
Once you have that node, you can parse the name to extract the vehicleid and then lookup the actual location of the vehicle under l.
Calculating Geohashes based on a location and a range
In the snippet above, I hardcoded the geohash values to use. Normally you'll want to to get all nodes in a certain range around a center. Instead of calculating these yourself, I recommend using the geohashQueries function from GeoFire for that:
var whitehouse = [38.8977, -77.0366];
var rangeInKm = 0.3;
var hashes = geohashQueries(center, radiusInKm*1000);
console.log(JSON.stringify(hashes));
This outputs a number of Geohash ranges:
[["dqcjqch","dqcjqc~"],["dqcjr10","dqcjr1h"],["dqcjqbh","dqcjqb~"],["dqcjr00","dqcjr0h"]]
You can pass each of these Geohash ranges into a Firebase query:
hashes.forEach(function(hash) {
var query = geoFireRef.child('i').startAt(null, hash[0]).endAt(null, hash[1]);
query.once('child_added', function(snapshot) { log(snapshot.name()); });
});
I hope this helps you settings things up.
Here is a Fiddle that I created a while ago to experiment with this stuff: http://jsfiddle.net/aF9mN/.
Related
I need to work with the torch geometric Reddit dataset
I can load Reddit dataset as follows:
from torch_geometric.datasets import Reddit
path = os.path.join(os.getcwd(), 'data', 'Reddit')
dataset = Reddit(path)
data = dataset[0]
print(data.y)
The node label is the community, or “subreddit”, that a post belongs to.
But label exists as integers from 0 to 40.
I want to know the community(=subreddit) name corresponding to the label number.
I searched but couldn't find it. Please help.
I have an NSManagedObject class that's persisted in a SQLite database in Core Data. This object has persistent Latitude and Longitude properties. I'm trying to create an NSFetchedRequestController that fetches all of the instances of that class that are within a certain distance from the user. Having done some research, it seems impossible to do this with Core Data, because Core Data only supports bounding-box style queries, not predicates with blocks.
For example, I have a class of Groups with latitude and longitude properties. Given the latitude and longitude (of, say, a user), fetch all groups that are within a 6 mile radius of the given latitude and longitude.
class Group{
var latitude: Float
var longitude: Float
}
I'd like to take advantage of Core Data's R-Tree Indexing to do a fast bounding-box query on the latitudes and longitudes of instances of my class near my user. Then I'd like to filter the results with a more precise predicate, using my own block of code to see which of the instances are within my users current location. Here's the "Bounding box" query.
let request: NSFetchRequest<Group> = Group.fetchRequest()
let (topLeft,bottomRight) = boundingBox(center: center, radius: searchRadius)
let maxLat = topLeft.latitude
let minLon = topLeft.longitude
let minLat = bottomRight.latitude
let maxLon = bottomRight.longitude
let predicate = NSPredicate(format: "(%f < longitude AND longitude < %f) AND (%f < latitude AND latitude < %f)", minLon, maxLon, minLat, maxLat)
request.predicate = predicate
The problem is that I'd like a fetch that looked like this:
let location: CLLocation = /* Initialize a CLLocation */
let predicate = NSPredicate { (obj, _) -> Bool in
let object = obj as! Group
let objLocation = CLLocation(latitude: Double(object.latitude), longitude: Double(object.longitude))
return location.distance(from: objLocation) < 9656 //6 miles in meters
}
NSFetched results controller doesn't allow predicate with block. There's a significant difference between these two fetches. The first gets all groups in a Bounding Box, (the minLat, minLon, maxLat, and maxLat), the latter gets all groups in a Circle of a given radius.
I want to then use an NSFetchedRequestController to display the results in a table, and take advantage of the nice auto-update features. But of course, Core Data only supports bounding-box style queries, not the two-step filter method I need. Is there a proper solution?
I'm open to using other databases, if Core Data simply won't work with this type of use. I took a look at YapDatabase, and it seems more flexible, and includes R-Tree indexing, but I'm concerned that it's not well supported. Realm doesn't support R-Tree Indexing.
Its quite a big task but ill try to explain.
I have an array with a list of 200 strings and I want to be able to randomly select one and add it to the stage using code. I have movieclips exported for actionscript with the same class name as the strings in the array. Also, if it is possible, would I be able to select the strings with predictability such as the first has a 0.7 chance the second a 0.1 etc. Here is what i have currently
var nameList:Array=["Jimmy","Bob","Fred"]
var instance:DisplayObject = createRandom(nameList);
addChild(instance);
function createRandom(typeArray:Array):*
{
// Select random String from typeArray.
var selection:String = typeArray[ int(Math.random() * typeArray.length) ];
// Create instance of relevant class.
var Type:Class = getDefinitionByName(selection) as Class;
// Return created instance.
return new Type();
}
All this throws me this error
ReferenceError: Error #1065: Variable [class Jimmy] is not defined.
Ive searched for other threads similar but none combine the three specific tasks of randomisation, predictability and addChild().
I think that you've got two problems: a language problem and a logic problem. In the .fla connected to your code above, in the Library find each symbol representing a name and write into the 'AS linkage' column for that symbol the associated name -- e.g., 'Bob,' 'Fred' -- just the name, no punctuation.
Now getDefinitionByName() will find your 'Class'
If you put a different graphic into each MovieClip -- say, a piece of fruit or a picture of Bob,Jim, Fred -- and run your program you'll get a random something on stage each time.
That should solve your language problem. But the logic problem is a little harder, no?
That's why I pointed you to Mr. Kelly's solution (the first one, which for me is easier to grasp).
I've been searching for hours but I couldn't find an answer to my question: I've set up a ListGrid similar to the one shown here (Link). Right now I am using a XML-File as data source (default rows) just like in the example. It is also possible to add and delete rows to/from the grid.
Therefore I would like to store every user's data from the grid in a data store (Google Datastore). So I need to read all the rows of the current user as Strings. What would be a good way to do that? I already tried the following, but without success:
ListGrid componentsGrid = new ListGrid();
componentsGrid.setWidth(500);
componentsGrid.setHeight(224);
componentsGrid.setCellHeight(22);
componentsGrid.setDataSource(ComponentsXmlDS.getInstance());
componentsGrid.setAutoFetchData(true);
componentsGrid.setCanEdit(true);
componentsGrid.setModalEditing(true);
componentsGrid.setEditEvent(ListGridEditEvent.CLICK);
componentsGrid.setListEndEditAction(RowEndEditAction.NEXT);
componentsGrid.setAutoSaveEdits(false);
layout.addMember(componentsGrid);
//First try
componentsGrid.fetchData();
logger.log(Level.INFO, "Components: "+ componentsGrid.getResultSet().get(0).getAttribute("componentType"));
//Second try
logger.log(Level.INFO, "Components: "+ componentsGrid.getAllFields());
// Third try
logger.log(Level.INFO, "Components: "+ componentsGrid.getRecords());
Anyone having a hint? Help is greatly appreciated.
If I understand well your requirement you want to read all the rows of the grid and store their data in a db.
I think you can use:
getRecordList() which *Return the underlying data of this DataBoundComponent as a RecordList.
You will be able to iterate inside this list, extract the attribute value you want for every record and store these data in your db.
Or use the getRecords() method as you said and iterate in the array of ListGridRecord obtained.
To iterate through your RecordList you have to transform it to an array, for example with a lot of dummy objects and methods:
RecordList data = MyGrid.getRecordList();
for(Record record : data.toArray()){
MyDataObject obj = new MyDataObject()
obj.setId(record.getAttribute("thId"));
obj.setOne(record.getAttribute("anAttribute"));
obj.setTwo(record.getAttribute("anotherAttribute"));
obj.StoreToDb();
}
I'm using objectify-appengine in my app. In the DB I store latitude & longitude of places.
at some point I'd like to find the closest place (from the DB) to a specific point.
As far as i understood i can't perform regular SQL-like queries.
So my question is how can it be done in the best way?
You should take a look at GeoModel, which enables Geospatial Queries with Google App Engine.
Update:
Let's assume that you have in your Objectify annotated model class, a GeoPt property called coordinates.
You need to have in your project two libraries:
GeoLocation.java
Java GeoModel
In the code that you want to perform a geo query, you have the following:
import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.BoundingBox;
import you.package.path.GeoLocation;
// other imports
// in your method
GeoLocation specificPointLocation = GeoLocation.fromDegrees(specificPoint.latitude, specificPoint.longitude);
GeoLocation[] bc = specificPointLocation.boundingCoordinates(radius);
// Transform this to a bounding box
BoundingBox bb = new BoundingBox((float) bc[0].getLatitudeInDegrees(),
(float) bc[1].getLongitudeInDegrees(),
(float) bc[1].getLatitudeInDegrees(),
(float) bc[0].getLongitudeInDegrees());
// Calculate the geocells list to be used in the queries (optimize
// list of cells that complete the given bounding box)
List<String> cells = GeocellManager.bestBboxSearchCells(bb, null);
// calculate geocells of your model class instance
List <String> modelCells = GeocellManager.generateGeoCell(myInstance.getCoordinate);
// matching
for (String c : cells) {
if (modelCells.contains(c)) {
// success, do sth with it
break;
}
}