I am trying to write the following
double sum_res = 0.0;
double yhat = 0;
double res = 0;
int n = 0;
for(int i=0;i<x.Count;i++)
{
yhat = inter + (slp*x[i]);
res = yhat - y[i];
n++;
}
using lambda but somehow not able to get it work(compile time error)
Enumerable.Range(0, x.Count).Select(i =>
{
yhat = inter + (slp * x[i]);
res = yhat - y[i];
sum_res += res * res;
n++;
});
Error: The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Help needed.
Thanks
Use Aggregate instead of Select since it more closely models what you're really trying to do.
double sum_res = Enumerable.Range(0, x.Count).Aggregate(0.0, (sum, i) =>
{
yhat = inter + (slp * x[i]);
res = yhat - y[i];
n++;
return sum + res * res;
});
the error you are getting is pretty good--LINQ has no idea what you are going to return from your lambda. . . Sam shows how the compiler can figure out what you are returning by explicitly returning something of a known type.
In the future, think about how the compiler would be able to discern what it is you are attempting to return from your expression. That can give you a clue about how to form your expression in a way that the compiler can work out.
If your expression is unambiguous, you don't need to explicitly state a return, otherwise you need to help the compiler as Sam illustrates.
I don't know why you are incrementing n but that really doesn't belong. I would go for something like this.
double sum_res = Enumerable.Range(0, x.Count).Aggregate(0.0, (sum, i) =>
sum + Math.Pow((inter + (slp * x[i])) - y[i]), 2.0))
);
The lambda body has no return statement, hence the error. Select method takes Func<TSource, TResult> lambda as a parameter, which is a function taking something of the same type as the collection and returning something else. You must have a return statement in order for this to work.
Related
I'd like to generate logging messages from within a C function embedded in a DML method. Take the example code below where the fib() function is called from the write() method of the regs bank. The log methods available to C all require a pointer to the current device.
Is there a way to get the device that calls the embedded function? Do I need to pass the device pointer into fib()?
dml 1.2;
device simple_embedded;
parameter documentation = "Embedding C code example for"
+ " Model Builder User's Guide";
parameter desc = "example of C code";
extern int fib(int x);
bank regs {
register r0 size 4 #0x0000 {
parameter allocate = false;
parameter configuration = "none";
method write(val) {
log "info": "Fibonacci(%d) = %d.", val, fib(val);
}
method read() -> (value) {
// Must be implemented to compile
}
}
}
header %{
int fib(int x);
%}
footer %{
int fib(int x) {
SIM_LOG_INFO(1, mydev, 0, "Generating Fibonacci for %d", x);
if (x < 2) return 1;
else return fib(x-1) + fib(x-2);
}
%}
I want to log from an embedded C function.
I solved this by passing the Simics conf_object_t pointer along to C. Just like implied in the question.
So you would use:
int fib(conf_object_t *mydev, int x) {
SIM_LOG_INFO(1, mydev, 0, "Generating Fibonacci for %d", x);
}
And
method write(val) {
log "info": "Fibonacci(%d) = %d.", val, fib(dev.obj,val);
}
Jakob's answer is the right one if your purpose is to offload some computations to C code (which makes sense in many situations, like when functionality is implemented by a lib).
However, if you just want a way to pass a callback to an API that asks for a function pointer, then it is easier to keep the implementation within DML and use a method reference, like:
method init() {
SIM_add_notifier(obj, trigger_fib_notifier_type, obj, &trigger_fib,
&dev.regs.r0.val);
}
method trigger_fib(conf_object_t *_, lang_void *aux) {
value = *cast(aux, uint64 *);
local int result = fib(value);
log info: "result: %d", result;
}
method fib(int x) -> (int) {
log info: "Generating Fibonacci for %d", x;
if (x < 2) return 1;
else return fib(x-1) + fib(x-2);
}
using if block in scala for distributed computing is least recommended. I have code and i want to replace if with Scala higher order method. How can i do that.
Detail code is given Here
Some part of code that contains if block is.
var bat = DenseVector.fill(N)(new BAT12(d , MinVal , MaxVal ))
bat.foreach{x => x.BestPosition = x.position;x.fitness = Sphere(x.position) ; x.BestFitness = x.fitness}
bat.foreach(x =>
if(x.BestFitness < GlobalBest_Fitness)
{
GlobalBest_Fitness =x.BestFitness ;GlobalBest_Position = x.BestPosition
})
Try
bat.filter(_.BestFitness < GlobalBest_Fitness).foreach { x =>
GlobalBest_Fitness = x.BestFitness
GlobalBest_Position = x.BestPosition
}
Do a filter before the foreach, with the if condition as the filter condition. Then do the foreach without any condition.
I have no idea why this code does not work. The whole idea about it is to make the value bigger until it's bigger than score.
if(score > height && rocketlaunch == false)
{
#try
{
height = [self makebigger:height];
}
#catch (NSException *exception)
{
height = height + 4000;
}
upgradeRocket.center = CGPointMake((rand()%200), -50);
rocketlaunch = true;
}
-(int)makebigger:(int)heightnr {
heightnr = heightnr + (1000 * rand() %5);
if(score > heightnr) {
[self makebigger:heightnr];
return heightnr;
} else {
return heightnr;
}
}
Does anyone know how to fix this? Or have a alternative way?
P.S.
The error displayed was:
Implicit conversion of int to id is disallowed with ARC
and
Incompatible integer to pointer conversion returning int from a function with result type id
Thank you in advance.
EDIT:
It works this way thank you very much :)
EDIT:
I got a new problem hard to solve:
this gives the error > tread 1 exc bad acces code = 2
change -makebigger:(int)heightnr to - (int)makebigger:(int)heightnr.
You have to specify the return type.
And you have to return something if the condition is true, too.
Until now I didn't even know it was possible to use no return type. But apparently it is.
Assuming score is an instance variable of type int then you have two errors in your code: first you must specify the return type of the method otherwise id is assumed; and second every path must return a value and your recursive call does not do this. Correcting those gives:
- (int)makebigger:(int)heightnr
{
heightnr = heightnr + (1000 * rand() %5);
if(score > heightnr)
return [self makebigger:heightnr];
else
return heightnr;
}
While this should work for simple value-based algorithms like this it is more usual to use iteration rather than recursion, as in:
- (int)makebigger:(int)heightnr
{
while (score > heightnr)
heightnr = heightnr + (1000 * rand() %5);
return heightnr;
}
I am going to take a guess that your "score" variable is an NSNumber. The compiler is complaining because you are trying to compare an NSNumber (object) to an int.
Try this:
if([score intValue] > heightnr)
I have the folowwing statement and I would like to have a LINQ equivalent:
SELECT *
FROM People
where Name like '%something%'
ORDER BY CASE
WHEN Name LIKE 'something%' then 1
WHEN Name LIKE '%something%' then 2
ELSE 3 END
Basically, I'm retrieving all the rows which contains a value (in this case 'something') and I'm ordering them: first the ones starting with that value, and then the remaining.
Any idea on how to do that in LinQ?
I've came out with the following solution.
var dc = new EntityContext();
var result = dc
// Condition part
.People.Where(x => x.Name.IndexOf("Foo") > -1) // This part is translated to like
// projection part
.Select(x => new { Person = x, Weight = x.Name.IndexOf("Bar") > -1 ? 1 : (x.Name.IndexOf("Baz") ? 2 : 0)})
// Order
.OrderBy(x => x.Weight)
// Final projection
.Select(x => x.Person);
I guess everything is self explanatory. First you select under your condition, then create a new object with weights necessary, then order it and finally take the necessary people.
I am not able to verify this, but something like this might work. The code can definitely be optimized/cleaned up, but in theory this just might work :)
The only question is whether the contains in the comparable delegate will translate the way it does in the Where. So, you might need to use an IndexOf or similar (as Oybek implemented)
var queryResult =
people
.Where(person=>person.name.Contains(#"/something/"))
.OrderBy(person=>person.Name,
delegate(string name1, string name2)
{
int result1, result2;
if(name1.Contains(#"something/")) result1 = 1;
else if(name1.Contains(#"/something/")) result1 = 2;
else result1 = 3;
if(name2.Contains(#"something/")) result2 = 1;
else if(name2.Contains(#"/something/")) result2 = 2;
else result2 = 3;
return result1.CompareTo(result2);
})
List<double> y = new List<double> { 0.4807, -3.7070, -4.5582,
-11.2126, -0.7733, 3.7269,
2.7672, 8.3333, 4.7023 };
List<double> d1 = y.ForEach(i => i * 2);
Error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
What is wrong?
Thanks
List<T>.ForEach doesn't perform a conversion: it executes the given delegate for each item, but that's all. That's why it has a void return type - and why the parameter type is Action<T> rather than something like Func<T, TResult>. This last part is why you've got a compilation error. You're basically trying to do:
Action<double> = i => i * 2;
That will give you the same compilation error.
If you want to stick within the List<T> methods (e.g. because you're using .NET 2.0) you can use List<T>.ConvertAll:
List<double> d1 = y.ConvertAll(i => i * 2);
Try instead:
List<double> d1 = y.Select(i => i * 2).ToList();
List.Foreach takes an Action<> delegate which does not return anything, so you cannot use it to create a new list that way. As others have pointed out, using ForEach is not the best option here. A sample on how to perform the operation using ForEach might help to understand why:
List<double> y = new List<double> { 0.4807, -3.7070, -4.5582,
-11.2126, -0.7733, 3.7269,
2.7672, 8.3333, 4.7023 };
List<double> d1 = new List<double>();
Action<double> a = i => d1.Add(i*2);
y.ForEach(a);
List<double> d1 = y.ForEach(i => i = i * 2);