does ios computed properties increment arc count of any object? - automatic-ref-counting

I have a code below and I want to know that does computed properties increment arc count of another object? (retained by arc) For example below
mycustomlabel count is 2 ?
var mycustomlabel = UILabel()
var myc : UILabel {
get {
return mycustomlabel
}
}

No you have a single strong reference at this point.

Related

How to get constraints from a body

Is there any way of knowing what constraints is a body attached to? I want to create a constraint each time two bodies collide, but not each time they collide after that first constraint is already created
UPDATE: Added proof of concept
In my code, i create an array of pairs with duplicate values, and because i have a maximum of 1000 elements, each value is duplicated in x+y1000 and y+x1000 indexes so they won't overlay
// global array
var alreadyPaired = [];
// on collision check, i save which pair of values must be paired
Matter.Events.on(engine, 'collisionStart', function(event) {
var idA = event.pairs[i].bodyA.id;
var idB = event.pairs[i].bodyB.id;
if ( !alreadyPaired[idA*1000+idB] && !alreadyPaired[idB*1000+idA] ) {
alreadyPaired[idA*1000+idB] = true;
alreadyPaired[idB*1000+idA] = true;
}
});

How to query exactly selected items in Paper.js?

According to my understanding, project.getItems({selected: true}) returns wrong results: I'm selecting a curve, it returns the parent Path: Sketch
Try clicking on a curve or a segment. Whole path will be moved. Then try changing the behavior by setting var workaround = false to var workaround = true to observe desired behavior.
How can I get exactly what is really selected?
Current workaround
I'm currently adding those objects into an array on selection and use those items instead of project.getItems({selected: true}).
The thing is that in Paper.js architecture, curves and segments are not items (they are part of a specific item which is the path). So you shouldn't expect project.getItems() to return anything else than items.
Another thing you have to know is that a path is assumed selected if any of its part is selected (curves, segments, points, handles, position, bounds, ...). And a curve is assumed selected if all of its parts are selected (points and handles).
With that in mind, you can create an algorithm to retrieve "what is really selected" based on project.getItems({selected: true}) as its first part. Then, you need to loop through curves and segments to check if they are selected.
Here is a sketch demonstrating a possible solution.
var vector = new Point(10, 10);
// Create path.
var path = new Path({
segments: [
[100, 100],
[200, 100],
[260, 170],
[360, 170],
[420, 250]
],
strokeColor: 'red',
strokeWidth: 10
});
// Translate given thing along global vector.
function translateThing(thing) {
switch (thing.getClassName()) {
case 'Path':
thing.position += vector;
break;
case 'Curve':
thing.segment1.point += vector;
thing.segment2.point += vector;
break;
case 'Segment':
thing.point += vector;
break;
}
}
// On mouse down...
function onMouseDown(event) {
// ...only select what was clicked.
path.selected = false;
hit = paper.project.hitTest(event.point);
if (hit && hit.location) {
hit.location.curve.selected = true;
}
else if (hit && hit.segment) {
hit.segment.selected = true;
}
// We check all items for demo purpose.
// Move all selected things.
// First get selected items in active layer...
project.activeLayer.getItems({ selected: true })
// ...then map them to what is really selected...
.map(getSelectedThing)
// ...then translate them.
.forEach(translateThing);
}
// This method returns what is really selected in a given item.
// Here we assume that only one thing can be selected at the same time.
// Returned thing can be either a Curve, a Segment or an Item.
function getSelectedThing(item) {
// Only check curves and segments if item is a path.
if (item.getClassName() === 'Path') {
// Check curves.
for (var i = 0, l = item.curves.length; i < l; i++) {
if (item.curves[i].selected) {
return item.curves[i];
}
}
// Check segments.
for (var i = 0, l = item.segments.length; i < l; i++) {
if (item.segments[i].selected) {
return item.segments[i];
}
}
}
// return item by default.
return item;
}
That said, depending on your real use case, your current workaround could be more appropriate than this approach.

kotlin adding pair to map when value is a list

I know this is basic but can I do this in a shorter way:
val ss = mutableMapOf<String, MutableList<String>>()
if(ss["new_key"] != null){
ss["new_key"]!!.add("NEW")
}
else{
ss["new_key"] = mutableListOf("OLD")
}
This basically checks if the key exists in the map
if it does an element is appended to the list(value) otherwise a new key-value pair is created
Can't I create a new key on the go? like this:
ss["new_key"].add("OLD")
ss["new_key"].add("NEW")
You have at least 2 options:
use computeIfAbsent:
ss.computeIfAbsent("new_key") { mutableListOf() } += "NEW"
use getOrPut:
ss.getOrPut("new_key", ::mutableListOf) += "NEW"

Geotrellis, get the points that fall in a polygon grid Rdd

I need to calculate the average of the values of points that fall in a polygon grid.
Is like a join one to many based in condition Polyogon.contains(point)
//In:
val pointValueRdd : RDD[Feature[Point,Double]]
val squareGridRdd : RDD[Feature[Polygon]]
//Needed Out:
val squareGridRdd : RDD[Feature[Polygon,(accum:Double,count:Int)]]
//or
val squareGridRdd : RDD[Feature[Polygon,average:Double]]
is possible to use some quadtree index ?
I read:clip to grid but i don not if it is the right tool.
http://geotrellis.readthedocs.io/en/latest/guide/vectors.html#cliptogrid
The next image show the grid in blue, and the points
Some advice we welcome
There is a straightforward way to accomplish this if your polygon grid can be expressed as a LayoutDefinition in GeoTrellis. A LayoutDefinition defines the grid of tiles that are used by GeoTrellis layers to represent large collection of raster tiles. It can also be used to perform transformations between a grid key (SpatialKey) in the grid space and bounding boxes (Extents) of in the map space.
I won't assume that you can represent the grid by a LayoutDefinition and instead will show an example that solve the more general case. If you can represent your polygon grid by a LayoutDefinition, that approach will be more straightforward. However here is a code snippet of the more general approach. This was compiled but not tested, so if you find problems with it let me know. This is being included in our examples in the doc-examples project with this PR: https://github.com/locationtech/geotrellis/pull/2489
import geotrellis.raster._
import geotrellis.spark._
import geotrellis.spark.tiling._
import geotrellis.vector._
import org.apache.spark.HashPartitioner
import org.apache.spark.rdd.RDD
import java.util.UUID
// see https://stackoverflow.com/questions/47359243/geotrellis-get-the-points-that-fall-in-a-polygon-grid-rdd
val pointValueRdd : RDD[Feature[Point,Double]] = ???
val squareGridRdd : RDD[Polygon] = ???
// Since we'll be grouping by key and then joining, it's work defining a partitioner
// up front.
val partitioner = new HashPartitioner(100)
// First, we'll determine the bounds of the Polygon grid
// and the average height and width, to create a GridExtent
val (extent, totalHeight, totalWidth, totalCount) =
squareGridRdd
.map { poly =>
val e = poly.envelope
(e, e.height, e.width, 1)
}
.reduce { case ((extent1, height1, width1, count1), (extent2, height2, width2, count2)) =>
(extent1.combine(extent2), height1 + height2, width1 + width2, count1 + count2)
}
val gridExtent = GridExtent(extent, totalHeight / totalCount, totalWidth / totalCount)
// We then use this for to construct a LayoutDefinition, that represents "tiles"
// that are 1x1.
val layoutDefinition = LayoutDefinition(gridExtent, tileCols = 1, tileRows = 1)
// Now that we have a layout, we can cut the polygons up per SpatialKey, as well as
// assign points to a SpatialKey, using ClipToGrid
// In order to keep track of which polygons go where, we'll assign a UUID to each
// polygon, so that they can be reconstructed. If we were dealing with PolygonFeatures,
// we could store the feature data as well. If those features already had IDs, we could
// also just use those IDs instead of UUIDs.
// We'll also store the original polygon, as they are not too big and it makes
// the reconstruction process (which might be prone to floating point errors) a little
// easier. For more complex polygons this might not be the most performant strategy.
// We then group by key to produce a set of polygons that intersect each key.
val cutPolygons: RDD[(SpatialKey, Iterable[Feature[Geometry, (Polygon, UUID)]])] =
squareGridRdd
.map { poly => Feature(poly, (poly, UUID.randomUUID)) }
.clipToGrid(layoutDefinition)
.groupByKey(partitioner)
// While we could also use clipToGrid for the points, we can
// simply use the mapTransform on the layout to determien what SpatialKey each
// point should be assigned to.
// We also group this by key to produce the set of points that intersect the key.
val pointsToKeys: RDD[(SpatialKey, Iterable[PointFeature[Double]])] =
pointValueRdd
.map { pointFeature =>
(layoutDefinition.mapTransform.pointToKey(pointFeature.geom), pointFeature)
}
.groupByKey(partitioner)
// Now we can join those two RDDs and perform our point in polygon tests.
// Use a left outer join so that polygons with no points can be recorded.
// Once we have the point information, we key the RDD by the UUID and
// reduce the results.
val result: RDD[Feature[Polygon, Double]] =
cutPolygons
.leftOuterJoin(pointsToKeys)
.flatMap { case (_, (polyFeatures, pointsOption)) =>
pointsOption match {
case Some(points) =>
for(
Feature(geom, (poly, uuid)) <- polyFeatures;
Feature(point, value) <- points if geom.intersects(point)
) yield {
(uuid, Feature(poly, (value, 1)))
}
case None =>
for(Feature(geom, (poly, uuid)) <- polyFeatures) yield {
(uuid, Feature(poly, (0.0, 0)))
}
}
}
.reduceByKey { case (Feature(poly1, (accum1, count1)), Feature(poly2, (accum2, count2))) =>
Feature(poly1, (accum1 + accum2, count1 + count2))
}
.map { case (_, feature) =>
// We no longer need the UUID; also compute the mean
feature.mapData { case (acc, c) => acc / c }
}

How do I get a bounding box for the current selection?

I'd like to do fancy things the selection indicator. How do I get the bounding box for the currently selected characters?
This was non-trivial. First, a selection may require more than one rectangle. Next, there's no convenient way to do it.
Here's what I had to do:
var start:int = op.activePosition < op.anchorPosition ? op.activePosition : op.anchorPosition;
var end:int = op.activePosition > op.anchorPosition ? op.activePosition : op.anchorPosition;
var textFlow:TextFlow = this.textFlow;
var rectangles:Dictionary = new Dictionary();
// For each selected character, make a box
for( var i:int=start; i < end; i++) {
var flowLine:TextFlowLine = textFlow.flowComposer.findLineAtPosition( i, true );
if( rectangles[ flowLine.absoluteStart ] == null ) {
rectangles[ flowLine.absoluteStart ] = new Rectangle();
(rectangles[ flowLine.absoluteStart ] as Rectangle).x = 0xffffff;
(rectangles[ flowLine.absoluteStart ] as Rectangle).right = 0;
}
var currentRect:Rectangle = rectangles[ flowLine.absoluteStart ];
var textLine:TextLine = flowLine.getTextLine(true);
var atomIndex:int = textLine.getAtomIndexAtCharIndex( i );
if( atomIndex >= 0) {
var atomBounds:Rectangle = textLine.getAtomBounds( atomIndex );
var pt:Point = this.globalToLocal( textLine.localToGlobal( new Point( atomBounds.left, atomBounds.top ) ) );
if( pt.x <= currentRect.left ) {
currentRect.left = pt.x;
currentRect.top = pt.y;
}
pt = this.globalToLocal( textLine.localToGlobal( new Point( atomBounds.right, atomBounds.bottom) ) );
if( pt.x >= currentRect.right ) {
currentRect.right = pt.x;
currentRect.bottom = pt.y;
}
}
}
return rectangles;
I don't believe there's a trivial way to get total control over this, from looking around at the docs a bit I saw this:
http://opensource.adobe.com/wiki/display/flexsdk/Spark+Text+Primitives#SparkTextPrimitives-FTE
[Style(name="focusedTextSelectionColor", type="uint", format="Color", inherit="yes")]
[Style(name="inactiveTextSelectionColor", type="uint", format="Color", inherit="yes")]
[Style(name="unfocusedTextSelectionColor", type="uint", format="Color", inherit="yes")]
also to note:
anchor position - A character index specifying the end of the selection that stays fixed when you extend the selection with the arrow keys.
active position - A character index specifying the end of the selection that moves when you extend the selection with the arrow keys.
Since these are all only colors (or indices) I don't know if they'll get at all the fanciness you'd like to do. I'd worked on something in Flex 3 to deal with custom text selection controls and ended up using an "off screen buffer" of sorts where I put a TextField offscreen with the same properties as the one on screen then dump the characters 1 by 1 until I got to the desired width then I could figure out where in the characters the control was dropped(kind of like android selection).
I would suggest searching for the above styles in the SDK you have (particularly in RichEditableText and its super classes, I would do this but there's quite a few versions out there now and don't know which one your using, TLF and FTE are both a bit in flux it seems). Once you find where these styles are used you'll probably be in the vicinity of the selection indicator drawing code and will likely need to extend from whatever class that is in order to override the appropriate methods.
Sorry I can't give you a straight answer but hopefully this helps or someone else is able to chime in if there's an easier way.
Shaun

Resources