Tuesday, April 24, 2012

mixed-type, variable length argument list (varargin, *args, ...) for C++

I am building a C++ clone of a project originally written in MATLAB. I'd like to "translate" the code keeping as close to the original as possible (given the unavoidable differences between a dynamically typed language like MATLAB and a statically typed language like C++).



My question is about variable length argument lists as function parameters which can contain arguments of mixed type.



MATLAB has varargin as a function parameter:



 varargin Variable length input argument list.
Allows any number of arguments to a function. The variable
varargin is a cell array containing the optional arguments to the
function. varargin must be declared as the last input argument
and collects all the inputs from that point onwards. In the
declaration, varargin must be lowercase (i.e., varargin).


In Python, *args and **kwargs handle this very comfortably.



How close can I get to this kind of flexibility in C++? Are there any standard argument list classes I should use?





How to change array index to start from 1?

How can I change my array's indices to start from 1 instead of 0. I am trying to fetch news from a site (JSON) and after parsing it:



@news = JSON.parse(Net::HTTP.get(URI.parse('http://api.site.com/news?format=json')))


But to see the individual news title, I have to do @news["items"][0] for the first link's title. Is it possible to change that behavior so when I do @news["items"][1] it shows me the first link's title?





Add an undo/redo method to core graphic draw app

I am trying to implement an undo/redo method using NSUndoManager. I have asked other questions on this, but am still stuck.



Where I am at the moment is as follows:



.h
NSUndoManager *undoManager;
@property(nonatomic,retain) NSUndoManager *undoManager;

.m
@synthesize undoManager;


[undoManager setLevelsOfUndo:99];
viewdidload:



NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];      
[dnc addObserver:self selector:@selector(undoButtonTapped) name:@"undo" object:nil];
[dnc addObserver:self selector:@selector(redoButtonTapped) name:@"redo" object:nil];

- (void)resetTheImage:(UIImage*)image
{
NSLog(@"%s", __FUNCTION__);

// image = savedImage.image;
if (image != drawImage.image)
{
[[undoManager prepareWithInvocationTarget:self] resetTheImage];
image = drawImage.image ;
} else {
NSLog(@"That didn't work");
}
}

- (void)undoButtonTapped {
NSLog(@"%s", __FUNCTION__);
[undoManager undo];
}


I get "That didn't work"...



I would appreciate help. I will post the answer to my original question when I figure out what I'm doing wrong.



---EDIT---



I have changed resetTheImage as follows:



- (void)resetTheImage:(UIImage*)image
{
NSLog(@"%s", __FUNCTION__);

image = savedImage.image;
if (image != drawImage.image)
{
drawImage.image = image;
savedImage.image = image;
NSLog(@"undo image");
[[self.undoManager prepareWithInvocationTarget:drawImage.image] image];

} else {
NSLog(@"same image");
savedImage.image = image;
}
}


However, confusion rains - it may help if someone (Brad?, Justin?) can provide a bullet point list of the steps I need to take to get this working. For example:



. Add notifications in ...
. Trigger notifications....
. Have undo /redo buttons point to...
. What methods/functions I really need to build..
....



I wish SO would allow me to give you more points than 1..



(It doesn't help that my "o" key is getting wonky)
It does help that I had a baby granddaughter yesterday :))))





ROC Curves Turorial

Guys I am looking for a third party software that applies classifiers (like SVM, multilayer perceptrons, I head libsvm is quite good) and also more important any tutorial about ROC Curves as I want to learn how to do them. The ones I found In google are not really helpful so if you know anything else that would be nice.





Android - assign and retrieve ID's dynamically

I know how to assing ID's dynamically by invoking setID(). For the ID's to be unique, I used to utilize ids.xml and pass to setID() ID's from the pre-generated pool of ID's.



Question 1: Is there any way to assign ID's without utilizing the ids.xml since I cannot participate how many ID's I will need in runtime?



I tried to by pass the first issue presented in Question 1 by dynamically assigning each of which an id based on its label's hash (each label is unique), but there is no way to gaurantee that ID's won't be colliding with ID's auto generated in R.java.



Question 1.1: How the ID naming collision can be resolved?



Question 2: Assume I have the ID value of which I assign and generate dynamically. Since the aformentioned ID does not appear in R.id, findViewById() won't be applicable for retrieving the view. Hence, how can the view be retrieved when the ID is known?





JQuery/Javascript and the use of && operators

I'm trying to get a simple conditional statement to work, and running into problems. The failing code:



    $(document).ready(function(){
var wwidth = $(window).width();

if (wwidth < 321) {
alert("I am 320 pixels wide, or less");
window.scrollTo(0,0);
} else if (wwidth > 321) && (wwidth < 481) {
alert("I am between 320 and 480 pixels wide")
}
});


If I remove the else if part of the code, I get the alert. If I try to use && or || operators it will fail. I've Googled, I can't find a reason why it's not working. I've also tried:



((wwidth > 321 && wwidth < 481))


along with other ways, just in case it's some odd syntax thing.



Any help would be greatly appreciated. Thanks :)





send simple data from wp7 to winforms application

I want to send simple data (geolocation data to be precise) from Windos Phone 7 application to a windows forms application and use it, as I'm a total beginner in this field I don't know which tools to use.
I searched about wcf services and tested this method but there's some issues: the data is sent from the phone application but isn't sent to the winforms application (guess something is missing)



If your know how to do this in a quick way, or have good tutorials I'll be thankful.





HTML5 getCurrentPosition with Meteor

I'm trying to use the html5 geolocation api with Meteor.
I'm using:
navigator.geolocation.getCurrentPosition(handle_geolocation_query); in my js but it doesn't seem to work - I think it may be related to the timer ( http://docs.meteor.com/#timers ) restrictions Meteor has. Any thoughts?





How to specialize a template member funcion depending on the class' template arguments?

I would like to write this:



template<typename T1, typename T2>
class OK
{
T1 t1;
T2 t2;

public:
template<typename TX> const TX & GetRef() const;
};

template<typename T1,typename T2>
template<>
const T1 & OK<T1,T2>::GetRef<T1>() const { return t1; }


Which VS10 fails to compile.



To check my understanding of template specialization, I tried and compiled this all right:



typedef int  T1;
typedef char T2;
class OK
{
T1 t1;
T2 t2;

public:
template<typename TX> const TX & GetRef() const;
};

template<>
const T1 & OK::GetRef<T1>() const { return t1; }


What am I missing ? Is what I want to do even possible ?





Liquibase Auto Rollback

I'm working on a branch and for instance need to delete a column in table X, I add a change and its good for that specific branch, then I switch to another branch that still requires that column and that change needs to be rolled back. There are a lot of changes to the db such as this from branch to branch.



I add a new changelog xml for every branch and include it in the master changelog xml. Obviously when I switch to another branch the changlog xml for the previous branch is no longer in the workspace and liquibase does not save the actual changeset in the database only its name and when it was applied, thus it won't be able to rollback changes automatically.



I'm using the Liquibase Servlet to apply changes on start up of my application.



Liquibase experts, is there an easy solution to this problem already implemented? Thank you!





Android SOAP NTLM example?

I've tried to google around for a working example. I've tried KSOAP2 and JCIFS examples but no success. The web service i'm trying to connect is 3rd parties (Microsoft Dynamics NAV) and can't be modified. It uses SOAP and either SPNEGO or NTLM authentication. And I guess it's already NTLMv2 but I'm not sure on that.
Can anybody please suggest me a full code for the following SOAP request?



$<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:item="urn:microsoft-dynamics-schemas/page/items">
$ <soapenv:Header/>
$ <soapenv:Body>
$ <item:ReadMultiple>
$ <!--1 or more repetitions:-->
$ <item:filter>
$ <item:Field>No</item:Field>
$ <item:Criteria>1000</item:Criteria>
$ </item:filter>
$ <item:setSize>500</item:setSize>
$ </item:ReadMultiple>
$ </soapenv:Body>
$</soapenv:Envelope>


I've validated this request with soapUI and it works fine. But when I tried to run it with KSOAP2 and JCIFS I get an error message "Connection refused".
Important to note I am a beginner in Java and Android.





Jquery how to animate a div ONLY if at a certain position?

hope your all well... Is there a way to animate a div (slide down) for example if its ONLY at a certain position on the page?
For example, there are four Divs that all have the same class .ALLCONTENT but when a button is clicked (.BUTTONS) only the Div thats at 30px from the top will animate downwards, the rest will remain in the same place.



Basically, slide down a div to a certain position, if that divs in that position already it wont slide further down (the problem im having now with



$(".BUTTONS").click(function(){
$(".ALLCONTENT").animate({"top":"+=558px"}, 250, 'linear');
});


Thanks, Tom





use of undeclared identifier 'isinf' error

My iOS project includes both C and C++ code (because I have integrated openCV).

Everything works fine as long as I don't include Mapkit.h. As soon as I include Mapkit.h I get the the following compile error:



Use of undeclared identifier 'isinf'


This error occurs in MKGeometry.h. I Google'ed around and the only thing I gathered is that the error has something to do with the fact that C++ has undefined isinf as a macro and declared it as a function in cmath.h.



I can't change MKGeometry.h (which is not a good idea, anyway) and I don't really want to change the standard headers (math.h or cmath.h) either. Is there a fix for this?



Many thanks for the help,





Retrieving javascript output from a form via php

I have a hidden field in a form where I'm trying to grab the users screen resolution. Then on the processing end retrieve the screen resolution via php. Unfortunately, my understanding of javascript is pretty limited. Here is what I have. I would really appreciate any help.



<head>
<script type="text/javascript">
function xy(){
document.write(screen.width + "x" + screen.height);
document.getElementById('xy').value;
}
</script>
</head>




<form action="" method=post >

//other fields here

<input type="hidden" name="xy" id="xy" value=""/>
<input type=submit name="button" value="button" />
</form>


When I view the page's source code, shouldn't I see the value set to for example "1366x768"? Now on the processing side, I would like to pull out information with php like this.



if(isset($_POST['xy']) && (!empty($_POST['xy'])){
$blah = $_POST['xy'];
//sanatize $blah;
}




Why can't I use a try block around my super() call?

So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that?



My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException.



So, what I want to do is effectively this:



public class MyClassMock extends MyClass {
public MyClassMock() {
try {
super(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

// Mocked methods
}


But Java complains that super isn't the first statement.



My workaround:



public class MyClassMock extends MyClass {
public static MyClassMock construct() {
try {
return new MyClassMock();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public MyClassMock() throws Exception {
super(0);
}

// Mocked methods
}


Is this the best workaround? Why doesn't Java let me do the former?






My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways.



I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.





Values Disappearing in Form

Well, the below snippet contains the text fields that I am filling in, whose values are used later in the JavaScript function.These are contained in a form.



   <br/>
<br/>
<label for="rchange">Change in Rate : </label>
<input type="text" id="rchange" name="ratechange" />


//same as above for Change in Capacity, but with name=capachange

<br/>
<br/>
<label for="rev">Annual Revenue : </label>
<input type="text" id="rev" readonly />

<input type="submit" name="sub" value="Submit Form" onClick="calculateRevenue(this.form)" />


JavaScript function that calculates some value and places it in the text field called rev.



     function calculateRevenue(form) 
{
if (form.capachange.value == '')
{
alert('Please enter a value for the Change in Capacity field.');


}
if (form.ratechange.value == '')
{
alert('Please enter a value for the Change in Rate field. ');


}

else

{

form.rev.value=parseInt(form.capachange.value)+parseInt(form.ratechange.value);
}

}

</script>


The problem is when I submit the form, I get the correct value and then the contents of the fields filled in vanish after around 2 seconds. The same thing happen if I don't fill in the change in rate or change in capacity field, it gives the alert and then the value disappears. Any idea whats happening here? Im not even using 'refresh' anywhere. Thank you for your time.





Unit Testing the IoC container itself

I don't think this was asked before, although it's really hard to search for a term like unit test ioc container and not find a question about how to implement IoC in order to perform unit tests.



I would like to have unit tests against the IoC container itself basically because sometimes I have issues with the container (like you could with any other part of an application), and it's pretty troublesome to test the resolution of dependencies merely debugging.



If I could introduce unit tests for these cases, I think it would save me a lot of trouble.



Update



Is something like this, not an Unit Test? Is it an integration test?



[TestClass]
public class IoC
{
private IWindsorContainer _container;

[TestInitialize]
public void TestInit()
{
_container = new WindsorContainer();
_container.Install(new WindsorInstaller());
}

[TestMethod]
public void ContainerShouldResolve_MembershipProvider()
{
ContainerShouldResolve<IMembershipProvider>();
}

public void ContainerShouldResolve<T>()
{
T result = _container.Resolve<T>();
Assert.IsInstanceOfType(result, typeof(T));
}
}


The only real "not self-contained" reference is a connection string I had to wire into app.config. Also: when trying to resolve PerWebRequest lifestyle components I had to add the related httpModule, too.



By the way: by doing this I found out the source of my issue in little time compared to what it was taking me to debug it through using the web application.





How do different apps written in different languages interact?

Off late I'd been hearing that applications written in different languages can call each other's functions/subroutines. Now, till recently I felt that was very natural - since all, yes all - that's what I thought then, silly me! - languages are compiled into machine code and that should be same for all the languages. Only some time back did I realise that even languages compiled in 'higher machine code' - IL, byte code etc. can interact with each other, the applications actually. I tried to find the answer a lot of times, but failed - no answer satisfied me - either they assumed I knew a lot about compilers, or something that I totally didn't agree with, and other stuff...Please explain in an easy to understand way how this works out. Especially how languages compiled into 'pure' machine code have different something called 'calling conventions' is what is making me clutch my hair.
Thanks!





How to define x++ (where x: int ref) in F#?

I currently use this function



let inc (i : int ref) =
let res = !i
i := res + 1
res


to write things like



let str = input.[inc index]


How define increment operator ++, so that I could write



let str = input.[index++]




Implementing search into mediaplayer

ok i have a mediaplayer app tht works perfect. ive been trying to implement a search feature into it. like take user input words query them and match and find songs on the sd card. anyone wanna help as im completely lost