Where is the detailed parameter description of SharedTreeNode in h2o-genmodel? - h2o

I am using h2o-genmodel to parse Mojo model.
But I'm somewhat confused about some of the parameters in the generated shareTreeNode CLASS. I queried the API documentation(http://docs.h2o.ai/h2o/latest-stable/h2o-genmodel/javadoc/index.html) and source code, there is no text description of any parameters.
I really need the explain of all parameters, because I need to change it to my parameters defined in my project as another format.
Here is the parameters in SharedTreeNode, some parameters like colName I can understand by myself. But parameters like inclusiveNa I am really don't know.
public class SharedTreeNode {
final SharedTreeNode parent;
final int subgraphNumber;
int nodeNumber;
float weight;
final int depth;
int colId;
String colName;
boolean leftward;
boolean naVsRest;
float splitValue = 0.0F / 0.0;
String[] domainValues;
GenmodelBitSet bs;
float predValue = 0.0F / 0.0;
float squaredError = 0.0F / 0.0;
SharedTreeNode leftChild;
public SharedTreeNode rightChild;
private boolean inclusiveNa;
private BitSet inclusiveLevels;
}
Here is my code.

inclusiveNa and inclusiveLevels are for calculating the tree visualization. the arcs from parent to child node show where the NA value travels and where the different levels for a categorical split travel.

Related

What this parameter is responsible for? markerSpec in InteractiveInfoWindowAndroid by Appolica

in https://github.com/Appolica/InteractiveInfoWindowAndroid i read that
markerSpec - Provides the marker's offsetX and offsetY
but I can't understand what it is responsible for, I changed the values in every possible way, but the result was always the same. R.dimen.marker_offset_x =5dp R.dimen.marker_offset_y=39dp
public void onMapReady(GoogleMap googleMap) {
final Marker marker2 = googleMap.addMarker(new MarkerOptions().position(new LatLng(1, 1)).snippet(FORM_VIEW));
final int offsetX = (int) getResources().getDimension(R.dimen.marker_offset_x);
final int offsetY = (int) getResources().getDimension(R.dimen.marker_offset_y);
final InfoWindow.MarkerSpecification markerSpec =
new InfoWindow.MarkerSpecification(offsetX, offsetY);
formWindow = new InfoWindow(marker2, markerSpec, new FormFragment());
googleMap.setOnMarkerClickListener(MainActivity.this);
}
Maybe someone has worked with this and can explain it to me
Okay I was entering too large values

Sort a List<object> by two properties one in ascending and the other in descending order in dart

I saw examples where I can sort a list in dart using one property in flutter(dart).
But how can I do the functionality which an SQL query does like for example:
order by points desc, time asc
You can sort the list then sort it again..
Here is a sample I made from dartpad.dev
void main() {
Object x = Object(name: 'Helloabc', i: 1);
Object y = Object(name: 'Othello', i: 3);
Object z = Object(name: 'Avatar', i: 2);
List<Object> _objects = [
x, y, z
];
_objects.sort((a, b) => a.name.length.compareTo(b.name.length));
/// second sorting
// _objects.sort((a, b) => a.i.compareTo(b.i));
for (Object a in _objects) {
print(a.name);
}
}
class Object {
final String name;
final int i;
Object({this.name, this.i});
}
I was able to find an answer for this. Thanks to #pskink and the url
https://www.woolha.com/tutorials/dart-sorting-list-with-comparator-and-comparable.
I implemented the Comparable to sort by the two properties.
class Sample implements Comparable<Sample> {
final int points;
final int timeInSeconds;
Sample(
{
this.points,
this.timeInSeconds});
#override
int compareTo(Sample other) {
int pointDifference = points- other.points;
return pointDifference != 0
? pointDifference
: other.timeInSeconds.compareTo(this.timeInSeconds);
}
}
sampleList.sort();

How do I add or remove an object to an array from another object

So in my program I have an object called Creatures and I have loaded it in via an array, all fine and dandy. But I want to add a way for the creature to repoduce and thus adding a copy of him to the array, but the problem is that the array is saved in another object. This is my code so far: (I have cut out some unrelated code)
The main part where my code is ran:
// Setting creature
Creature[] Creatures = new Creature[20];
void setup() {
size(1280,720,P2D);
// Initializing Creatures
for(int i = 0; i < Creatures.length; i++) {
Creatures[i] = new Creature(true, "");
}
}
void draw()
{
update();
//TODO: Add more
}
void update() {
//Updating the creatures
for(int i = 0; i < Creatures.length; i++) {
Creatures[i].update();
}
}
And the part with the Creature class:
class Creature {
String race;
float x;
float y;
float r;
float g;
float b;
ExtraUtils EU = new ExtraUtils();
Creature(boolean genned, String pRace) {
x = (float)Math.random() * width;
y = (float)Math.random() * height;
r = (float)Math.random() * 255;
g = (float)Math.random() * 255;
b = (float)Math.random() * 255;
if(genned)
{
race = EU.RandomString(round((float)Math.random()*5+3));
} else {
race = pRace;
}
}
void update() {
strokeWeight(0);
fill(r,g,b);
x+=(float)Math.random()*3 - 1.5;
y+=(float)Math.random()*3 - 1.5;
rect(x,y,8,8);
text(race,x,y);
}
}
If anyone would like to help me with this (with this i mean add a new creature to the Creatures array from the Creature class) I would be very very happy!
Don't use an Array, use an ArrayList. It is more dynamic.
So, inside creatures we will have:
class Creature {
ArrayList<Creature> creatures = new ArrayList<Creature>();
//You can access the above ArrayList and add to it at any point in this class with creature.add().
//The rest of your class below.
}
Since you defined the ArrayList in the Creature class, to add to it, just reference that object of the class.
Creature creature = new Creature(); //Whatever constructor paramaters you want to use.
creature.creatures.add(); //This is where you will add your object.
Update
I wanted to take the time to explain fully the final implementation.
You have created the ArrayList in the Creature class, so that means you do not need the Creature[] array in your sketch. So, remove that, and the for loop you have in Setup().
When you want to update the Creature objects in the creatures ArrayList, inside your sketch (not the Creature class), you will just do this:
for(int i = 0; i < creature.creatures.size; i++) {
creature.creatures.get(i).update();
}
In conclusion, here are the final code snippets that should work for your implementation:
1.) No change needed in class Creature. The Creature class has no changes other than adding the ArrayList I mentioned earlier.
2.) Your sketch:
// Setting Creature Object
Creature creature = new Creature(); //Whatever paramaters you want to add for the constructor.
void setup() {
size(1280,720,P2D);
// Initalizing Creature objects inside list.
for(int i = 0; i < QUANTITY_TO_ADD; i++) {
creatures.creature.add(new Creature(true, ""));
}
}
void draw()
{
update();
//TODO: Add more
}
void update() {
//Updating the creatures
for(int i = 0; i < creature.creatures.size(); i++) {
creature.creatures.get(i).update();
}
}
Note: QUANTITY_TO_ADD is merely a place holder.
Conclusion:
Now, your implementation is dynamic, and you only have one copy of the ArrayList stored, so you don't have to worry about saving updates between classes. The ArrayList is initialized in Creature and you can use the add() and get() methods to modify or get any elements in wherever, so long as you use the object of the Creature class to access it.
Passing creature array pointer to a member function of Creature should help, right?

how to get multi properties's mean values using java8 stream?

there's one Object
#Data
class ScoreInfo{
String id;
float cove_score;
float theam_score;
float content_score;
float teach_score;
Date create_date;
ScoreInfoP scoreInfoP;
}
and ScoreInfoP is :
#Data
class ScoreInfoP{
String stream_sn;
String anchor_id;
String create_by;
}
sourceList is a list of ScoreInfo,I want to get cove_score,theam_score,content_score,teach_score's mean values,group by scoreInfoP property and return four mean values for each of these properties.
I can get only one mean value using such code:
Map<ScoreInfoP, Double> meanForCoveScore = sourceList.stream().collect(Collectors.groupingBy(ScoreInfo::getScoreInfoP,
Collectors.averagingDouble(ScoreInfo::getCove_score)));
I want to learn how to get four mean values using java8 or any easier way you suggest achieving this.
Waiting here for your generous help.
There isn't anything build-in for this, but it's not that complicated to build a custom Collector for that...
Map<String, List<Float>> result = Arrays.asList(first, second)
.stream()
.collect(Collectors.groupingBy(
x -> x.getScoreInfoP().getAnchorId(),
Collector.of(
() -> new float[5],
(a, x) -> {
a[0] += x.getCoveScore();
a[1] += x.getTheamScore();
a[2] += x.getTeachScore();
a[3] += x.getContentScore();
a[4]++;
},
(left, right) -> {
for (int i = 0; i < 4; ++i) {
left[i] += right[i];
}
return left;
}, x -> Arrays.asList(x[0] / x[4], x[1] / x[4], x[2] / x[4], x[3] / x[4]))
));
System.out.println(result);
I actually groupBy here on ScoreInfoP#anchorId; but you can do it on ScoreInfoP - for that you need to change x -> x.getScoreInfoP().getAnchorId() to x -> x.getScoreInfoP(). But obviously ScoreInfoP needs to override hashCode and equals.
As I said in the comment you should use a proper result class.
class ScoreInfoAverage {
private float cove_score;
private float theam_score;
private float content_score;
private float teach_score;
// ctor, getter, setter
}
Then you can use a custom Collector:
public static Collector<ScoreInfo, ?, ScoreInfoAverage> scoreInfoToAverage() {
class ScoreInfoAccumulator {
private DoubleSummaryStatistics cove_score = new DoubleSummaryStatistics();
private DoubleSummaryStatistics theam_score = new DoubleSummaryStatistics();
private DoubleSummaryStatistics content_score = new DoubleSummaryStatistics();
private DoubleSummaryStatistics teach_score = new DoubleSummaryStatistics();
public void add(ScoreInfo si) {
cove_score.accept(si.cove_score);
theam_score.accept(si.theam_score);
content_score.accept(si.content_score);
teach_score.accept(si.teach_score);
}
public ScoreInfoAccumulator combine(ScoreInfoAccumulator sia) {
cove_score.combine(sia.cove_score);
theam_score.combine(sia.theam_score);
content_score.combine(sia.content_score);
teach_score.combine(sia.teach_score);
return this;
}
public ScoreInfoAverage average() {
return new ScoreInfoAverage((float) cove_score.getAverage(),
(float) theam_score.getAverage(), (float) content_score.getAverage(),
(float) teach_score.getAverage());
}
}
return Collector.of(ScoreInfoAccumulator::new, ScoreInfoAccumulator::add,
ScoreInfoAccumulator::combine, ScoreInfoAccumulator::average);
}
Last but not least you add your Collector to the downstream:
Map<ScoreInfoP, ScoreInfoAverage> collect = scoreInfos.stream()
.collect(Collectors.groupingBy(ScoreInfo::getScoreInfoP, scoreInfoToAverage()));

How to scroll to a specific element in ScrollRect with Unity UI?

I built a registration form for a mobile game using Unity 5.1.
To do that, I use Unity UI components: ScrollRect + Autolayout (Vertical layout) + Text (labels) + Input Field.
This part works fine.
But, when keyboard is opened, the selected field is under keyboard. Is there a way to programmatically scroll the form to bring the selected field into view?
I have tried using ScrollRect.verticalNormalizedPosition and it works fine to scroll some, however I am not able to make selected field appear where I want.
Thanks for your help !
I am going to give you a code snippet of mine because I feel like being helpful. Hope this helps!
protected ScrollRect scrollRect;
protected RectTransform contentPanel;
public void SnapTo(RectTransform target)
{
Canvas.ForceUpdateCanvases();
contentPanel.anchoredPosition =
(Vector2)scrollRect.transform.InverseTransformPoint(contentPanel.position)
- (Vector2)scrollRect.transform.InverseTransformPoint(target.position);
}
None of the suggestions worked for me, the following code did
Here is the extension
using UnityEngine;
using UnityEngine.UI;
namespace BlinkTalk
{
public static class ScrollRectExtensions
{
public static Vector2 GetSnapToPositionToBringChildIntoView(this ScrollRect instance, RectTransform child)
{
Canvas.ForceUpdateCanvases();
Vector2 viewportLocalPosition = instance.viewport.localPosition;
Vector2 childLocalPosition = child.localPosition;
Vector2 result = new Vector2(
0 - (viewportLocalPosition.x + childLocalPosition.x),
0 - (viewportLocalPosition.y + childLocalPosition.y)
);
return result;
}
}
}
And here is how I used it to scroll a direct child of the content into view
private void Update()
{
MyScrollRect.content.localPosition = MyScrollRect.GetSnapToPositionToBringChildIntoView(someChild);
}
Although #maksymiuk's answer is the most correct one, as it properly takes into account anchors, pivot and all the rest thanks to InverseTransformPoint() function, it still didn't work out-of-box for me - for vertical scroller, it was changing its X position too. So I just made change to check if vertical or horizontal scroll is enabled, and not change their axis if they aren't.
public static void SnapTo( this ScrollRect scroller, RectTransform child )
{
Canvas.ForceUpdateCanvases();
var contentPos = (Vector2)scroller.transform.InverseTransformPoint( scroller.content.position );
var childPos = (Vector2)scroller.transform.InverseTransformPoint( child.position );
var endPos = contentPos - childPos;
// If no horizontal scroll, then don't change contentPos.x
if( !scroller.horizontal ) endPos.x = contentPos.x;
// If no vertical scroll, then don't change contentPos.y
if( !scroller.vertical ) endPos.y = contentPos.y;
scroller.content.anchoredPosition = endPos;
}
here's the way I clamped selected object into ScrollRect
private ScrollRect scrollRect;
private RectTransform contentPanel;
public void ScrollReposition(RectTransform obj)
{
var objPosition = (Vector2)scrollRect.transform.InverseTransformPoint(obj.position);
var scrollHeight = scrollRect.GetComponent<RectTransform>().rect.height;
var objHeight = obj.rect.height;
if (objPosition.y > scrollHeight / 2)
{
contentPanel.localPosition = new Vector2(contentPanel.localPosition.x,
contentPanel.localPosition.y - objHeight - Padding.top);
}
if (objPosition.y < -scrollHeight / 2)
{
contentPanel.localPosition = new Vector2(contentPanel.localPosition.x,
contentPanel.localPosition.y + objHeight + Padding.bottom);
}
}
The preconditions for my version of this problem:
The element I want to scroll to should be fully visible (with minimal clearance)
The element is a direct child of the scrollRect's content
Keep scoll position if element is already fully visible
I only care about the vertical dimension
This is what worked best for me (thanks for the other inspirations):
// ScrollRect scrollRect;
// RectTransform element;
// Fully show `element` inside `scrollRect` with at least 25px clearance
scrollArea.EnsureVisibility(element, 25);
Using this extension method:
public static void EnsureVisibility(this ScrollRect scrollRect, RectTransform child, float padding=0)
{
Debug.Assert(child.parent == scrollRect.content,
"EnsureVisibility assumes that 'child' is directly nested in the content of 'scrollRect'");
float viewportHeight = scrollRect.viewport.rect.height;
Vector2 scrollPosition = scrollRect.content.anchoredPosition;
float elementTop = child.anchoredPosition.y;
float elementBottom = elementTop - child.rect.height;
float visibleContentTop = -scrollPosition.y - padding;
float visibleContentBottom = -scrollPosition.y - viewportHeight + padding;
float scrollDelta =
elementTop > visibleContentTop ? visibleContentTop - elementTop :
elementBottom < visibleContentBottom ? visibleContentBottom - elementBottom :
0f;
scrollPosition.y += scrollDelta;
scrollRect.content.anchoredPosition = scrollPosition;
}
A variant of Peter Morris answer for ScrollRects which have movement type "elastic". It bothered me that the scroll rect kept animating for edge cases (first or last few elements). Hope it's useful:
/// <summary>
/// Thanks to https://stackoverflow.com/a/50191835
/// </summary>
/// <param name="instance"></param>
/// <param name="child"></param>
/// <returns></returns>
public static IEnumerator BringChildIntoView(this UnityEngine.UI.ScrollRect instance, RectTransform child)
{
Canvas.ForceUpdateCanvases();
Vector2 viewportLocalPosition = instance.viewport.localPosition;
Vector2 childLocalPosition = child.localPosition;
Vector2 result = new Vector2(
0 - (viewportLocalPosition.x + childLocalPosition.x),
0 - (viewportLocalPosition.y + childLocalPosition.y)
);
instance.content.localPosition = result;
yield return new WaitForUpdate();
instance.horizontalNormalizedPosition = Mathf.Clamp(instance.horizontalNormalizedPosition, 0f, 1f);
instance.verticalNormalizedPosition = Mathf.Clamp(instance.verticalNormalizedPosition, 0f, 1f);
}
It introduces a one frame delay though.
UPDATE: Here is a version which does not introduce a frame delay and it also takes scaling of the content into account:
/// <summary>
/// Based on https://stackoverflow.com/a/50191835
/// </summary>
/// <param name="instance"></param>
/// <param name="child"></param>
/// <returns></returns>
public static void BringChildIntoView(this UnityEngine.UI.ScrollRect instance, RectTransform child)
{
instance.content.ForceUpdateRectTransforms();
instance.viewport.ForceUpdateRectTransforms();
// now takes scaling into account
Vector2 viewportLocalPosition = instance.viewport.localPosition;
Vector2 childLocalPosition = child.localPosition;
Vector2 newContentPosition = new Vector2(
0 - ((viewportLocalPosition.x * instance.viewport.localScale.x) + (childLocalPosition.x * instance.content.localScale.x)),
0 - ((viewportLocalPosition.y * instance.viewport.localScale.y) + (childLocalPosition.y * instance.content.localScale.y))
);
// clamp positions
instance.content.localPosition = newContentPosition;
Rect contentRectInViewport = TransformRectFromTo(instance.content.transform, instance.viewport);
float deltaXMin = contentRectInViewport.xMin - instance.viewport.rect.xMin;
if(deltaXMin > 0) // clamp to <= 0
{
newContentPosition.x -= deltaXMin;
}
float deltaXMax = contentRectInViewport.xMax - instance.viewport.rect.xMax;
if (deltaXMax < 0) // clamp to >= 0
{
newContentPosition.x -= deltaXMax;
}
float deltaYMin = contentRectInViewport.yMin - instance.viewport.rect.yMin;
if (deltaYMin > 0) // clamp to <= 0
{
newContentPosition.y -= deltaYMin;
}
float deltaYMax = contentRectInViewport.yMax - instance.viewport.rect.yMax;
if (deltaYMax < 0) // clamp to >= 0
{
newContentPosition.y -= deltaYMax;
}
// apply final position
instance.content.localPosition = newContentPosition;
instance.content.ForceUpdateRectTransforms();
}
/// <summary>
/// Converts a Rect from one RectTransfrom to another RectTransfrom.
/// Hint: use the root Canvas Transform as "to" to get the reference pixel positions.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public static Rect TransformRectFromTo(Transform from, Transform to)
{
RectTransform fromRectTrans = from.GetComponent<RectTransform>();
RectTransform toRectTrans = to.GetComponent<RectTransform>();
if (fromRectTrans != null && toRectTrans != null)
{
Vector3[] fromWorldCorners = new Vector3[4];
Vector3[] toLocalCorners = new Vector3[4];
Matrix4x4 toLocal = to.worldToLocalMatrix;
fromRectTrans.GetWorldCorners(fromWorldCorners);
for (int i = 0; i < 4; i++)
{
toLocalCorners[i] = toLocal.MultiplyPoint3x4(fromWorldCorners[i]);
}
return new Rect(toLocalCorners[0].x, toLocalCorners[0].y, toLocalCorners[2].x - toLocalCorners[1].x, toLocalCorners[1].y - toLocalCorners[0].y);
}
return default(Rect);
}
In case anyone looking for a smooth scroll (using lerp).
[SerializeField]
private ScrollRect _scrollRectComponent; //your scroll rect component
[SerializeField]
RectTransform _container; //content transform of the scrollrect
private IEnumerator LerpToChild(RectTransform target)
{
Vector2 _lerpTo = (Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - (Vector2)_scrollRectComponent.transform.InverseTransformPoint(target.position);
bool _lerp = true;
Canvas.ForceUpdateCanvases();
while(_lerp)
{
float decelerate = Mathf.Min(10f * Time.deltaTime, 1f);
_container.anchoredPosition = Vector2.Lerp(_scrollRectComponent.transform.InverseTransformPoint(_container.position), _lerpTo, decelerate);
if (Vector2.SqrMagnitude((Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - _lerpTo) < 0.25f)
{
_container.anchoredPosition = _lerpTo;
_lerp = false;
}
yield return null;
}
}
simple and works perfectly
var pos = 1 - ((content.rect.height / 2 - target.localPosition.y) / content.rect.height);
scrollRect.normalizedPosition = new Vector2(0, pos);
Yes,this is possible using coding to scroll vertically, please try this code :
//Set Scrollbar Value - For Displaying last message of content
Canvas.ForceUpdateCanvases ();
verticleScrollbar.value = 0f;
Canvas.ForceUpdateCanvases ();
This code working fine for me ,when i developed chat functionality.
width signifiy the width of childern in scroll rect (assuming that all childerns width is same), spacing signifies the space between childerns, index signifies the target element you want to reach
public float getSpecificItem (float pWidth, float pSpacing,int pIndex) {
return (pIndex * pWidth) - pWidth + ((pIndex - 1) * pSpacing);
}
Vertical adjustment:
[SerializeField]
private ScrollRect _scrollRect;
private void ScrollToCurrentElement()
{
var siblingIndex = _currentListItem.transform.GetSiblingIndex();
float pos = 1f - (float)siblingIndex / _scrollRect.content.transform.childCount;
if (pos < 0.4)
{
float correction = 1f / _scrollRect.content.transform.childCount;
pos -= correction;
}
_scrollRect.verticalNormalizedPosition = pos;
}
Here's what I created to solve this problem. Place this behavior on each button that can be selected via controller UI navigation.
It supports fully nested children objects.
It only supports vertical scrollrects, but can be easily adapted to do horizontal.
using UnityEngine;
using System;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Legend
{
public class ScrollToOnSelect: MonoBehaviour, ISelectHandler
{
ScrollRect scrollRect;
RectTransform target;
void Start()
{
scrollRect = GetComponentInParent<ScrollRect>();
target = (RectTransform)this.transform;
}
Vector3 LocalPositionWithinAncestor(Transform ancestor, Transform target)
{
var result = Vector3.zero;
while (ancestor != target && target != null)
{
result += target.localPosition;
target = target.parent;
}
return result;
}
public void EnsureScrollVisible()
{
Canvas.ForceUpdateCanvases();
var targetPosition = LocalPositionWithinAncestor(scrollRect.content, target);
var top = (-targetPosition.y) - target.rect.height / 2;
var bottom = (-targetPosition.y) + target.rect.height / 2;
var topMargin = 100; // this is here because there are headers over the buttons sometimes
var result = scrollRect.content.anchoredPosition;
if (result.y > top - topMargin)
result.y = top - topMargin;
if (result.y + scrollRect.viewport.rect.height < bottom)
result.y = bottom - scrollRect.viewport.rect.height;
//Debug.Log($"{targetPosition} {target.rect.size} {top} {bottom} {scrollRect.content.anchoredPosition}->{result}");
scrollRect.content.anchoredPosition = result;
}
public void OnSelect(BaseEventData eventData)
{
if (scrollRect != null)
EnsureScrollVisible();
}
}
}

Resources