How to create a structure that already has default values?
Somehow like this:
struct First {
int data = 4;
int pos = 5;
}
void main () {
var a = First ();
assert(a.data == 4);
}
The response from AlThomas:
"Structs in Vala can have initializers (similar to a constructor for a class) and methods. So what I can extract from your second pastebin you could write that as:"
struct First {
int data;
int pos;
public First (int[] mass) {
data= 5;
pos = mass.length;
}
public int sas () {
return data + pos;
}
}
void main () {
int[] a = {1,3,0,1,2,3,2,1};
var b = First (a);
print (#"$(b.sas ())\n");
}
Related
I have the following sample code. A Map with (Foo) class items, and a Map with (Bar) struct items:
public class Maps {
Gee.Map<Foo?, int> map1 = new Gee.HashMap<Foo?, int> ();
Gee.Map<Bar?, int> map2 = new Gee.HashMap<Bar?, int> ();
public Maps () {
Foo a = new Foo ();
Foo b = new Foo ();
Foo c = new Foo ();
map1.set (a, 1);
map1.set (b, 2);
map1.set (c, 3);
stdout.printf ("Foo = %d %d %d %d\n", map1.get (a), map1.get (b), map1.get (c), map1.size);
Bar e = Bar ();
Bar d = Bar ();
Bar f = Bar ();
map2.set (d, 1);
map2.set (e, 2);
map2.set (f, 3);
stdout.printf ("Bar = %d %d %d %d\n", map2.get (d), map2.get (e), map2.get (f), map2.size);
}
}
public class Foo {
public string name;
public Foo () {
name = "foo";
}
}
public struct Bar {
public string name;
public Bar () {
name = "bar";
}
}
public static int main (string[] args) {
stdout.printf ("Start\n");
var a = new Maps ();
stdout.printf ("End\n");
return 0;
}
The output:
Start
Foo = 1 2 3 3
Bar = 0 0 0 3
End
What is it that I am doing wrong as to not being able to retrieve values from map2?
After trolling through the GNOME source, I found the following solution (from Geary):
i.e. Adding custom hash and equal functions.
Gee.Map<Bar?, int> map2 = new Gee.HashMap<Bar?, int> (bar_hash_func, bar_equal_func);
public static uint bar_hash_func (Bar? n) {
return hash_memory ((uint8 *) n, sizeof(Bar));
}
public static bool bar_equal_func (Bar? a, Bar? b) {
Bar *bia = (Bar *) a;
Bar *bib = (Bar *) b;
return (*bia) == (*bib);
}
/**
* A rotating-XOR hash that can be used to hash memory buffers of any size.
*/
public static uint hash_memory (void *ptr, size_t bytes) {
if (ptr == null || bytes == 0) {
return 0;
}
uint8 *u8 = (uint8 *) ptr;
// initialize hash to first byte value and then rotate-XOR from there
uint hash = *u8;
for (int ctr = 1; ctr < bytes; ctr++) {
hash = (hash << 4) ^ (hash >> 28) ^ (*u8++);
}
return hash;
}
How can I convert a haxe.Int64 to a Float?
I've got something like
var x = haxe.Int64.parseString("1000000000000");
and I'd like to convert that to a Float. I've looked in the Int64 api docs, have found fromFloat, ofInt, and toInt, but there's no toFloat method in there.
I cannot see that functionality in the Haxe standard library either, I checked Int64 and Int64Helper.
However the MIT-licensed thx.core library does include an implementation, see below: https://github.com/fponticelli/thx.core/blob/master/src/thx/Int64s.hx#L137
using haxe.Int64;
class Int64s {
static var zero = Int64.make(0, 0);
static var one = Int64.make(0, 1);
static var min = Int64.make(0x80000000, 0);
/**
Converts an `Int64` to `Float`;
Implementation by Elliott Stoneham.
*/
public static function toFloat(i : Int64) : Float {
var isNegative = false;
if(i < 0) {
if(i < min)
return -9223372036854775808.0; // most -ve value can't be made +ve
isNegative = true;
i = -i;
}
var multiplier = 1.0,
ret = 0.0;
for(_ in 0...64) {
if(i.and(one) != zero)
ret += multiplier;
multiplier *= 2.0;
i = i.shr(1);
}
return (isNegative ? -1 : 1) * ret;
}
}
Using the library method worked for me, tested on the JavaScript target like so:
import haxe.Int64;
import thx.Int64s;
class Main {
public static function main():Void {
var x:Int64 = haxe.Int64.parseString("1000000000000");
var f:Float = thx.Int64s.toFloat(x);
trace(f); // Prints 1000000000000 to console (on js target)
}
}
Alternatively, you can convert Int64 to Float yourself by combining high/low halves:
class Test {
static function main() {
var x = haxe.Int64.parseString("1000000000000");
var f = x.high * 4294967296. + (x.low >>> 0);
trace("" + x);
trace(f);
}
}
Here,
4294967296. is a float literal for unsigned 2^32;
>>> 0 is required because the lower half can be signed.
Or, for a naive conversion method, you can use:
var f = Std.parseFloat(haxe.Int64.toStr(x));
You may want to try to use FPHelper class. It contains a set of methods to convert Int types to Float / Double.
import haxe.io.FPHelper;
class Test {
static function main() {
var x = haxe.Int64.parseString("1000000000000");
var f = FPHelper.i64ToDouble(x.low, x.high);
trace(f);
}
}
See https://try.haxe.org/#CDa93
I made a test game in unity that makes it so when I click on a button, it spawns a cylinder created from a factory class. I'm trying to make it so when I create the cylinder, its height shrinks over the next 20 seconds. Some methods I found are difficult to translate into what I'm doing. If you could lead me to the right direction, I'd very much appreciate it.
Here's my code for the cylinder class
public class Cylinder : Shape
{
public Cylinder()
{
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder.transform.position = new Vector3(3, 0, 0);
cylinder.transform.localScale = new Vector3(1.0f, Random.Range(1, 2)-1*Time.deltaTime, 1.0f);
cylinder.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
Destroy(cylinder, 30.0f);
}
}
This can be done with the Time.deltaTime and Vector3.Lerp in a coroutine function. Similar to Rotate GameObject over time and Move GameObject over time questions. Modified it a little bit to do just this.
bool isScaling = false;
IEnumerator scaleOverTime(Transform objectToScale, Vector3 toScale, float duration)
{
//Make sure there is only one instance of this function running
if (isScaling)
{
yield break; ///exit if this is still running
}
isScaling = true;
float counter = 0;
//Get the current scale of the object to be moved
Vector3 startScaleSize = objectToScale.localScale;
while (counter < duration)
{
counter += Time.deltaTime;
objectToScale.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
yield return null;
}
isScaling = false;
}
USAGE:
Will scale GameObject within 20 seconds:
StartCoroutine(scaleOverTime(cylinder.transform, new Vector3(0, 0, 90), 20f));
Check out Lerp. A general example of how to use it would be something like this:
float t = 0;
Update()
{
t += Time.deltaTime;
cylinder.localScale = new Vector3(1, Mathf.Lerp(2f, 1f, t/3f), 1); // shrink from 2 to 1 over 3 seconds;
}
You will create a new monobehaviour script and add it to your primitive. Then you wil use "Update" method of monobehaviour (or use coroutine) for change object over time.
Monobehaviour must be look like this:
public class ShrinkBehaviour : MonoBehaviour
{
bool isNeedToShrink;
Config currentConfig;
float startTime;
float totalDistance;
public void StartShrink(Config config)
{
startTime = Time.time;
currentConfig = config;
totalDistance = Vector3.Distance(currentConfig.startSize, currentConfig.destinationSize);
isNeedToShrink = true;
transform.localScale = config.startSize;
}
private void Update()
{
if (isNeedToShrink)
{
var nextSize = GetNextSize(currentConfig);
if (Vector3.Distance(nextSize, currentConfig.destinationSize) <= 0.05f)
{
isNeedToShrink = false;
return;
}
transform.localScale = nextSize;
}
}
Vector3 GetNextSize(Config config)
{
float timeCovered = (Time.time - startTime) / config.duration;
var result = Vector3.Lerp(config.startSize, config.destinationSize, timeCovered);
return result;
}
public struct Config
{
public float duration;
public Vector3 startSize;
public Vector3 destinationSize;
}
}
For using this, you must do next:
public Cylinder()
{
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
var shrink = cylinder.AddComponent<ShrinkBehaviour>();
shrink.StartShrink(new ShrinkBehaviour.Config() { startSize = Vector3.one * 10, destinationSize = Vector3.one * 1, duration = 20f });
cylinder.transform.position = new Vector3(3, 0, 0);
cylinder.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
Destroy(cylinder, 30.0f);
}
You must remember, monobehaviour-script must be in separate file, and must have name similar to monobehaviour-class name. For example, ShrinkBehaviour.cs;
I have QList which contains inhereted from QThread objects. These objects in run() method do some work in cycle with different periodicity(I use QThread::sleep) and results save in private fields.
Question
How correct print result in QTableView or QTableWidget?
my idea - create thread that will print in QTableWidget result in infinity cycle, but I guess that this idea is terrible...
//httpgettask.h
//Task inherit from QThread
class HttpGetTask : public Task
{
public:
HttpGetTask(const QString &, const int &, const int &);
HttpGetTask(const QUrl &, const int &, const int &);
void run();
};
//httpgettask.cpp
HttpGetTask::HttpGetTask(const QUrl &url, const int &period, const int &errLimit) :
Task(url, period, errLimit, "HTTP GET")
{
}
HttpGetTask::HttpGetTask(const QString &url, const int &period, const int &errLimit) :
Task(url, period, errLimit, "HTTP GET")
{
}
void HttpGetTask::run()
{
TestConn conn(url);
Response res;
QString msg;
int errCount = 0;
while (!stopThread)
{
msg = "";
res = conn.get();
if (!res.isSuccess())
{
if (++errCount == errLimit) {
msg = QString("ERROR!! %1 ERROR").arg(errLimit);
++errors;
errCount = 0;
}
}
msg = QString("%1 %2 %3 %4").arg(QDateTime::currentDateTime().toString(datePattern),
msg,
"HTTP_GET",
res.getMessage());
writeResultFile(msg);
++checkCount;
QThread::sleep(period);
}
}
I solved the problem. Just create QTimer and update QTableWidget in timer slot
This following code gives me the error below . I think I need "InvokeRequired" . But I don't understand how can I use?
error:Cross-thread operation not valid: Control 'statusBar1' accessed from a thread other than the thread it was created on.
the code :
public void CalculateGeneration(int nPopulation, int nGeneration)
{
int _previousFitness = 0;
Population TestPopulation = new Population();
for (int i = 0; i < nGeneration; i++)
{
if (_threadFlag)
break;
TestPopulation.NextGeneration();
Genome g = TestPopulation.GetHighestScoreGenome();
if (i % 100 == 0)
{
Console.WriteLine("Generation #{0}", i);
if ( ToPercent(g.CurrentFitness) != _previousFitness)
{
Console.WriteLine(g.ToString());
_gene = g;
statusBar1.Text = String.Format("Current Fitness = {0}", g.CurrentFitness.ToString("0.00"));
this.Text = String.Format("Sudoko Grid - Generation {0}", i);
Invalidate();
_previousFitness = ToPercent(g.CurrentFitness);
}
if (g.CurrentFitness > .9999)
{
Console.WriteLine("Final Solution at Generation {0}", i);
statusBar1.Text = "Finished";
Console.WriteLine(g.ToString());
break;
}
}
}
}
Easiest for reusability is to add a helper function like:
void setstatus(string txt)
{
Action set = () => statusBar1.Text = txt;
statusBar1.Invoke(set);
}
Or with the invokerequired check first:
delegate void settextdelegate(string txt);
void setstatus(string txt)
{
if (statusBar1.InvokeRequired)
statusBar1.Invoke(new settextdelegate(setstatus), txt);
else
statusBar1.Text = txt;
}
Either way the status can then be set like
setstatus("Finished");
For completeness I should add that even better would be to keep your calculating logic separated from your form and raise a status from within your calculating functionality that can be hanled by the form, but that could be completely out of scope here.