Swift array access triggers EXC_BREAKPOINT - random

Here is my code (largeAsteroids.count is never 0):
var largeAsteroids=[[SKTexture]]()
func randomLargeAsteroidTextures()->Array<SKTexture>{
let i=Int(arc4random())%largeAsteroids.count
return largeAsteroids[i]// this line triggers EXC_BREAKPOINT
}
When I execute my code, I receive no errors but I get a EXC_BREAKPOINT. I ensured there wasn't any breakpoint and at index i there was a valid object.
First I changed SKTexture to AnyObject, it didn't help.
Then I tried to use NSMutableArray instead of swift array, problem still exist:
var largeAsteroids=NSMutableArray()
func randomLargeAsteroidTextures()->AnyObject{
let i=Int(arc4random())%largeAsteroids.count
return largeAsteroids.objectAtIndex(i) // this line triggers EXC_BREAKPOINT
}
update:
Problem solved,
replace:
let i=Int(arc4random())%largeAsteroids.count
by:
let i=Int(arc4random_uniform(UInt32(largeAsteroids.count)))
Thanks for Matt's solution:
You should probably be using arc4random_uniform. You'll get modulo bias from your current implementation. – Matt Gibson

You were running on a 32-bit target, yes? On a 32-bit target (e.g. iPhone 4), Swift Ints are 32-bits, and signed. However, on any platform, arc4random() returns a 32-bit unsigned integer.
Because of this conflict, and your conversion to Int, Int(arc4random()), sometimes—in fact, half the time, all else being equal—your number was negative, giving you a negative array index, and causing your problem (though I get EXC_BAD_INSTRUCTION, as I'd expect, when I reproduce the problem; presumably you have a breakpoint set for exceptions?)
My suggestion, to use arc4random_uniform, should work fine as long as the count of your asteroids is never more than Int.max on a 32-bit platform, which is presumably quite unlikely, unless you're giving your gamer a really hard time. It will also avoid modulo bias in the random generation, so your resulting random numbers will be more uniformly distributed than in your original solution.

Related

Parameters for dlib::find_min_bobyqa

I'm working on the C++ version of Matt Zucker's Page dewarping. So far everything works fine, but I have a problem with optimization. In line 748 of Github repo Matt uses optimize function from Scipy. My C++ equivalent is find_min_bobyqa from dlib.net. The code is:
auto f = [&](const column_vector& ppts) { return objective( dstpoints, ppts, keypoint_index); };
dlib::find_min_bobyqa(f,
params,
2 * params.nr() + 1, // npt - number of interpolation points: x.size() + 2 <= npt && npt <= (x.size()+1)*(x.size()+2)/2
dlib::uniform_matrix<double>(params.nr(), 1, -2), // lower bound constraint
dlib::uniform_matrix<double>(params.nr(), 1, 2), // upper bound constraint
1, // initial trust region radius
1e-5, // stopping trust region radius
4000 // max number of objective function evaluations
);
In my concrete example params is a dlib::column_vector with double values and length = 189. Every element of params is less than 2.0 and greater than -2.0. Function objective() returns double value and "alone" it works properly because I get the same value as in the Python version. But after running fin_min_bobyqa function I usually get the message:
Terminate called after throwing an instance of 'dlib:bobyqa_failure', return from BOBYQA because the objective function has been called max_f_evals times.
I set max_f_evals to quite big value to see if it optimizes at all, but it doesn't. I did some tweaking with parameters but without good results. How should I set the parameters of find_min_bobyqa to get the right solution?
I am very interested in this issue as well. Zucker's work, with very minor tweaks, is ideal for straightening sheet music images, and I was looking for ways to implement it in a mobile platform when I came across your question.
My research so far suggests that BOBYQA is not the equivalent of Powell's method in scipy. BOBYQA is constrained, and the one in scipy is not.
See these links for more information, and a possible way to compile the right supporting library - I would try UOBYQA or NEWUOA.
https://github.com/jacobwilliams/PowellOpt
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#rdd2e1855725e-3
(See the Notes section)
EDIT: see C version here:
https://github.com/emmt/Algorithms/tree/master/newuoa
I wanted to post this as a comment, but I don't have enough points for that.
I am very interested in your progress. If you're willing, please keep me posted.
I finally solved this problem. I used PRAXIS library, because it doesn't need derivative information and is fast.
I modified the code a little to my needs and now it is faster around few seconds than original version written in Python.

Using termios in Swift

Now that we've reached Swift 2.0, I've decided to convert my, as yet unfinished, OS X app to Swift. Making progress but I've run into some issues with using termios and could use some clarification and advice.
The termios struct is treated as a struct in Swift, no surprise there, but what is surprising is that the array of control characters in the struct is now a tuple. I was expecting it to just be an array. As you might imagine it took me a while to figure this out. Working in a Playground if I do:
var settings:termios = termios()
print(settings)
then I get the correct details printed for the struct.
In Obj-C to set the control characters you would use, say,
cfmakeraw(&settings);
settings.c_cc[VMIN] = 1;
where VMIN is a #define equal to 16 in termios.h. In Swift I have to do
cfmakeraw(&settings)
settings.c_cc.16 = 1
which works, but is a bit more opaque. I would prefer to use something along the lines of
settings.c_cc.vim = 1
instead, but can't seem to find any documentation describing the Swift "version" of termios. Does anyone know if the tuple has pre-assigned names for it's elements, or if not, is there a way to assign names after the fact? Should I just create my own tuple with named elements and then assign it to settings.c_cc?
Interestingly, despite the fact that pre-processor directives are not supposed to work in Swift, if I do
print(VMIN)
print(VTIME)
then the correct values are printed and no compiler errors are produced. I'd be interested in any clarification or comments on that. Is it a bug?
The remaining issues have to do with further configuration of the termios.
The definition of cfsetspeed is given as
func cfsetspeed(_: UnsafeMutablePointer<termios>, _: speed_t) -> Int32
and speed_t is typedef'ed as an unsigned long. In Obj-C we'd do
cfsetspeed(&settings, B38400);
but since B38400 is a #define in termios.h we can no longer do that. Has Apple set up replacement global constants for things like this in Swift, and if so, can anyone tell me where they are documented. The alternative seems to be to just plug in the raw values and lose readability, or to create my own versions of the constants previously defined in termios.h. I'm happy to go that route if there isn't a better choice.
Let's start with your second problem, which is easier to solve.
B38400 is available in Swift, it just has the wrong type.
So you have to convert it explicitly:
var settings = termios()
cfsetspeed(&settings, speed_t(B38400))
Your first problem has no "nice" solution that I know of.
Fixed sized arrays are imported to Swift as tuples, and – as far as I know – you cannot address a tuple element with a variable.
However,Swift preserves the memory layout of structures imported from C, as
confirmed by Apple engineer Joe Groff:. Therefore you can take the address of the tuple and “rebind” it to a pointer to the element type:
var settings = termios()
withUnsafeMutablePointer(to: &settings.c_cc) { (tuplePtr) -> Void in
tuplePtr.withMemoryRebound(to: cc_t.self, capacity: MemoryLayout.size(ofValue: settings.c_cc)) {
$0[Int(VMIN)] = 1
}
}
(Code updated for Swift 4+.)

greenline Xcode EXC_BAD_INSTRUCTION on NSUserDefaults Optional

I've been writing an app that involves using NSUserDefaults to store a few Int variables and it's been working fine. I thought I was finished and was doing some final testing and one of the first lines of code that I wrote, and that has been working consistently before, has failed me.
Apparently the green line error is supposed to occur if I try to unwrap an optional that has a value of nil, but this variable is still very much an optional
var savedTotalSeconds: Int? = userDefaults.objectForKey("totalSecondsKey") as Int?
Why would this possibly return an error? It was working fine before and I only changed things I thought were unrelated to it. In the app I have a button to remove this stored value via:
userDefaults.removeObjectForKey("totalSecondsKey")
What could possibly have gone wrong?
Try using 'as? Int' instead of 'as Int?'
The difference is that the first one tries, and might fail, at casting to Int. That failure will be captured in the optionality of the resulting variable.
The second one tries to coerce the object to 'Int?'.

term does not evaluate to a function taking 1 arguments

Please have a look at the following OpenCV code
Mat *curent;
current = new Mat();
cv::Rect bRect = cv::boundingRect(Mat(*points).reshape(2));
Mat roi = *current(bRect);
Here, I am trying to get a ROI to the Mat called roi. But whenever I try to get execute the last line of the above code I get the error term does not evaluate to a function taking 1 arguments. I have followed the same technique of getting an ROI without pointers number of times before in C++ and they worked. I guess the issue is with pointer current ? current must be a pointer because local variable slowed the application in an unbelievable way.
So, how can I solve this issue and get the ROI ?
please, throw out those pointers!
you're going to wreck havoc on the internal Mat refcounts, produce undefined behaviour and memleaks
"local variable slowed the application in an unbelievable way."
really, you think, copying a 58 byte struct is the reason ? i just don't believe you.
well i'll give you a hint, anyway - the ( ) operator has a higher precedence than the * operator.

Constant expression violates subrange bounds

I have a project that I'm going to rewrite to another language, and in order to do that - I'd like to build it. But when I try to build it, I receive "E1012: Constant expression violates subrange bounds".
I have such code:
var ForTolkResult : array[0..2000] of char;
ForTolkResult[sizeof(ForTolkResult)-1] := chr(0); // Occurs here
From my point of view everything is correct here, sizeof(ForTolkResult) = 2000 * 1, so sizeof(ForTolkResult) - 1 = 1999, that is in bounds of an array. (But I'm new to Pascal) So what's wrong here?
I'm trying to build it via Embarcadero C++ Builder. If this error is a bug in compiler, how can I turn this check off?
Does char really ocuppy one byte of memory? I mean, check whether it is an "Ansi" single-byte char and not a WideChar.
Anyway, when you need to access the last index of an array, you'd better use
ForTolkResult[High(ForTolkResult)] := chr(0);

Resources