Field Calculator Sum Across Other Layer - qgis

I'm hoping to reach into another layer and sum the relevant fields with Field Calculator, but am having some trouble.
I have the layers "Countries", and "Settlements". I want to create a new field in Countries called Population, which is the sum of all the matching Settlements. That is, the sum of all Settlements where Settlements->Owner_Name matches Countries->Name. Any advice on how to go about this? I haven't found a lot of detailed tutorials about reaching across layers.

Add a field to the Countries layer, named Population with this expression:
aggregate(
layer:='Settlements',
aggregate:='count',
expression:="id",
filter:="Owner_Name"=attribute(#parent, 'Name')
This should work.

Related

Assign weight to attribute based on there value is grater or lesser then some value: algolia

Hi I am trying to find a search solution where I can assign a weight (x point) to an attribute if its value is greater or smaller then some value ( Y value)
Like if the price is greater then 10 USD then assign 5 points to the item, and I am assigning points on multiple attribute, then get the list of item on the bases of total points in asc or desc order, how can i do this in algolia
Algolia doesn't work with weights, but with a tie-breaking strategy that decides how to rank results based on their attributes. This strategy is static, and set at indexing time.
In your case, you're willing to rank results by a multitude of criteria, including by price. The easiest way to do this is to use the customRanking attribute and set each attribute that should play a role in the ranking strategy. For example, if you want more expensive items to be ranked higher, you can do the following (JavaScript example, but you have a choice between 11 different languages):
index.setSettings({
customRanking: [
'desc(price)'
]
});
Notice the customRanking property takes an array. You can pass several criteria for your custom ranking, and they will be taken into account in the defined order, if the engine can't break the tie.
Since you're working with prices, you may end up in a case where two prices are so close that it makes no sense to break the tie on them; and you'll want to move on to the next criterion. In this case, you can add a new attribute with a rounded price and use this one as the custom ranking attribute. There's a guide in the documentation on that topic.

adding up specific mergefield values in word

I have a table in a word document that has three colums and all fields are mailmerge fields from an external IT system.
There are three columns displaying the fields:
Charge Description
Charge Value (£)
Eiligible? (yes/no)
I am trying to create a field that adds up all eligibale charges so that only charge values that show a "yes" in the eligigble field are included. Does anyone know if this is possible? I have tried creating a formula but can't get it to work. Also, I would assume at some point an if statment is required so that it only includes the eligible charge.
Has anyone done anything similar before and if so, would they mind sharing how it was achieved?
Many thanks
You can do some things with expression fields (created in Word with CTRL-F9). This will look like {} and you can insert the expression. eg {{MERGFIELD charge} + {MERGEFIELD charge2}}. Since however you want to check multiple values and then create an expression, its probably easier to use a macro. The macro would contain your logic, then set the fields in the document accordingly.
Here are two external links since I can't reproduce a useful amount the content here because it's a verbose answer to a potentially deep question:
Expression Fields
Merge fields
I hope that helps.

Sphinx: Show all results order by previous searches

I use SphinxQL for searching and filtering in product database and I store last x search phrases of each user. I wonder if is it possible to show all products (all rows) to every user but with relevance on previous search.
Let's say one user sought for mobile phones (iphone, galaxy s7...), ie. electronics category. I want to show him all products randomly, but products from category electronics more often and products with those searched keywords even more often.
Is it even possible with Sphinx?
Thanks and sorry for english.
An alternative, would be perhaps to create random numbers attached to each result. A high and a low number, with an overlapping range.
sql_query = SELECT id, RAND()*100 AS rand_low, (RAND()*100)+50 AS rand_high, ...
sql_attr_uint = rand_low
sql_attr_uint = rand_high
Can then arrange the ranking expression to pick either of these numbers depending on if matches or not, and sort by the result.
SELECT id FROM index WHERE MATCH('_all_ MAYBE electronics MAYBE (galaxy s7)')
OPTION ranker=expr('IF(doc_word_count>1,rand_high,rand_low)');
Will be mixed up. But results that match one of the words, have a greater chance of showing up first (because use the weighted random number) - its still only a chance, because a rand_high CAN still be smaller than rand_low.
... can change the size of the number 'overlap' to tweak the mix of matching/non matching results.
(added as a new answer as its a quite differnt idea, although uses the same 'all' keyword)
Sphinx doesn't have a 'mode' to just do that. But can get very close...
Can use MAYBE operator
MATCH('_all_ MAYBE electronics MAYBE (galaxy s7)')
The complication is need a way to match all products. Depending on your data you may already have a word can use (eg word like 'the' in every single product), or add the word to every document, during indexing.
... using MAYBE allows the matching results to have a higher weight.
But you dont want to sort strictly by weight. So need a different alogithm, something to shuffle the results a bit (as you not really wanting 'random'!)
SELECT id, IDIV(id/10000) AS int,WEIGHT() AS w
FROM index WHERE MATCH('_all_ MAYBE electronics MAYBE (galaxy s7)')
ORDER BY int DESC, w DESC;
This creates banding by ID, as in theory results can be spread over all the id-space will mix them up a bit. But the category results will still tend to be shown first within each band.
If you have one a different attribute other than ID might be better, something more spread out. Or can add a deliberate random attribute to results)
... there are all sort so variations, your imagination is the only limitation, this basic techqiue can be used to mix things up quote a bit.
(There are other possiblities, Sphinxes little known GROUP N BY function, can be used to produce a sampling search result. This is isnt random, but it might give the similar enough result - ie just mixing up results)

Getting Streets of a specific postcode using Open Street Maps

I want to write a code that has the Countrycode and Postcode as an input and the ouput are the streets that are in the given postcode using some apis that use GSM.
My tactic is as follows:
I need to get the relation Id of the district. For Example 1991416 is the relation id for the third district in Vienna - Austria. It's provided by the nominatim api: http://nominatim.openstreetmap.org/details.php?place_id=158947085
Put the id in this api url: http://polygons.openstreetmap.fr/get_wkt.py?id=1991416&params=0
After downloading the polygon I can put the gathered polygon in this query on the overpass api
(
way
(poly: "polygone data")
["highway"~"^(primary|secondary|tertiary|residential)$"]
["name"];
);
out geom;
And this gives me the streets of the searched district. My two problems with this solution are
1. that it takes quite a time, because asking three different APIs per request isn't that easy on ressources and
2. I don't know how to gather the relation Id from step one automatically. When I enter a Nominatim query like http:// nominatim.openstreetmap.org/search?format=json&country=austria&postalcode=1030 I just get various point in the district, but not the relation id of the searched district in order to get the desired polygone.
So my questions are if someone can tell my how I can get the relation_Id in order to do the mentioned workflow or if there is another, maybe better way to work this issue out.
Thank you for your help!
Best Regards
Daniel
You can simplify your approach quite a bit, down to a single Overpass API call, assuming you define some relevant tags to match the relation in question. In particular, you don't have to resort to using poly at all, i.e. there's no need to convert a relation to a list of lat/lon pairs. Nowadays the concept of an area can be used instead to query for certain objects in a polygon defined by a way or relation. Please check out the documentation for more details on areas.
To get the matching area for relation 1991416, I have used postal_code=1030 and boundary=administrative as filter criteria. Using that area you can then search for ways in this specific polygon:
//uncomment the following line, if you need csv output
//[out:csv(::id, ::type, name)];
//adjust area to your needs, filter critera are the same as for relations
area[postal_code=1030][boundary=administrative]->.a;
// Alternative: {{geocodeArea:name}} -> see
// http://wiki.openstreetmap.org/wiki/Overpass_turbo/Extended_Overpass_Queries
way(area.a)["highway"~"^(primary|secondary|tertiary|residential)$"]["name"];
(._;>;);out meta;
// just for checking if we're looking at the right area
rel(pivot.a);out geom;
Try it on overpass turbo link: http://overpass-turbo.eu/s/6uN
Note: not all ways/relations have a corresponding area, i.e. some area generation rules apply (see wiki page above). For your particular use case you should be ok, however.

How to order documents by a dynamic property in Mongoid

I am using Mongoid to store a series of geocoded listings. These listings need to be sorted by price and proximity. The price of every listing is a field in the database whereas distance is a dynamic property that is unique for every user.
class Listing
include Mongoid::Document
field :price
def distance
get_distance(current_user.location,coordinates)
end
end
How can I sort these documents by distance? I tried #listing.desc(:distance) and that didn't work.
The short (and unhelpful) answer is: you can't.
Mongoid does have the ability to query based on 2d co-ordinates though, then you could update your controller to do something like this:
#listings = Listing.near(current_user.location)
Which I believe will return your listings in order of distance.
On a side note, I noticed that your Listing model is referring to your current_user object, which kinda breaks the MVC architecture, since your models shouldn't know anything about the current session.