Building dynamic lambda expressions - dynamic

I know how to build a simple lambda like x => x > 5:
int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> result1 = nbs.Where(x => x > 5);
ParameterExpression parameter = Expression.Parameter(typeof(int), "x");
ConstantExpression constant = Expression.Constant(5);
BinaryExpression expressionBody = Expression.GreaterThan(parameter, constant);
Expression<Func<int, bool>> expression = Expression.Lambda<Func<int, bool>>(expressionBody, parameter);
IEnumerable<int> result2 = nbs.Where(expression.Compile());
But how do I build a lambda like x => whiteNbs.Contains(x) in a similar way as above:
int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> whiteNbs = new List<int>() { 1, 5 };
IEnumerable<int> result = nbs.Where(x => whiteNbs.Contains(x));

Replace binary GreaterThan expression with a MethodCallExpression.
int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var elementType = typeof(int);
var x = Expression.Parameter(elementType, "x");
var whiteNbs = Expression.Constant(new List<int>() {1, 5});
var contains = Expression.Call(typeof(Enumerable),
"Contains",
new[] {elementType},
whiteNbs,
x
);
var lambda = Expression.Lambda<Func<int, bool>>(contains, x);
var result = nbs.Where(lambda.Compile());

Related

How do you keep the every kth element of a list in Ramda?

How do you filter out every kth element of a list with Ramda?
input = [1, 2, 3, 4, 5, 6, 7, 8, 9]
output = keepKth(input, 3)
output = [1, 4, 7]
This seemed to work:
let k = 3;
let Kth = (value, index) => (index % k == 0)
let filterKth = R.addIndex(R.filter)(Kth);
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let output = filterKth(input);
A variation based on Scott's comment:
const keepEvery = k => compose(pluck(0), splitEvery(k));
keepEvery(3)([1, 2, 3, 4, 5, 6, 7, 8, 9]);
//=> [1, 4, 7]
https://ramdajs.com/docs/#pluck
https://ramdajs.com/docs/#splitEvery
Probably not the cleanest, but point free.
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const whitelist = R.addIndex(R.reject)(R.flip(R.modulo(R.__, 3)));
console.log(
whitelist(data),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.2/ramda.js" integrity="sha512-MEPRnhl9ArIiZuk6ikVrLzYxQm8ov1Ngkn4kIUO82hwpD7d+cwXQ7+isupqVgZ6HHtAEBDMff8eUhzixwEBSbA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
And here is another method based on R.unfold. The seed is the index (initial 0), and it's incremented by k on every iteration.
const { curry, unfold } = R
const fn = curry((k, arr) => unfold(n => n < arr.length && [arr[n], n + k], 0))
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const result = fn(3, data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.2/ramda.js" integrity="sha512-MEPRnhl9ArIiZuk6ikVrLzYxQm8ov1Ngkn4kIUO82hwpD7d+cwXQ7+isupqVgZ6HHtAEBDMff8eUhzixwEBSbA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Filtering an array from another array in vue

This might be something really simple, but I just can't figure it out. What I'm trying to do is take 2 arrays and filter out what I don't need and only
return the one array.
So what I have right now is this
let array1 = [1, 2, 3];
let array2 = [1, 2, 3, 4, 5, 6];
and what I would like is to return array 2 with only the items that doesn't show up in array1 so that would be 4, 5,6.
This is what I have so far
return array1.forEach(a => {
array2.filter(aa => aa !== a)
});
and that doesn't return anything
let array1 = [1, 2, 3];
let array2 = [1, 2, 3, 4, 5, 6];
let array3 = array2.filter(i => !array1.includes(i));
console.log(array3)
This might help to solve your problem.
let array1 = [1, 2, 3]
let array2 = [1, 2, 3, 4, 5, 6]
function returnList(arOne,arTwo){
return arTwo.filter(a => !arOne.includes(a))
}
let response = returnList(array1 ,array2 );

How can I generate a random Verhoeff number in Apache Jmeter?

Need to pass a new Verhoeff Number every time I execute my script. The already used Verhoeff number is rejected by my application, as a business validation. Can someone help with the script for this?
The Java algorithm implementation is available at the Wikipedia page
In JMeter it's recommended to use Groovy for scripting so you will need to amend it to look like:
/**
* #see <ahref="http://en.wikipedia.org/wiki/Verhoeff_algorithm" > More Info</a>
* #see <ahref="http://en.wikipedia.org/wiki/Dihedral_group" > Dihedral Group</a>
* #see <ahref="http://mathworld.wolfram.com/DihedralGroupD5.html" > Dihedral Group Order 10</a>
* #author Colm Rice
*/
public class Verhoeff {
// The multiplication table
static int[][] d = new int[][]
{
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
[2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
[3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
[4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
[5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
[6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
[7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
[8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
};
// The permutation table
static int[][] p = new int[][]
{
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
[5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
[8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
[9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
[4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
[7, 0, 4, 6, 9, 1, 3, 2, 5, 8]
};
// The inverse table
static int[] inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];
/*
* For a given number generates a Verhoeff digit
*
*/
public static String generateVerhoeff(String num) {
int c = 0;
int[] myArray = stringToReversedIntArray(num);
for (int i = 0; i < myArray.length; i++) {
c = d[c][p[((i + 1) % 8)][myArray[i]]];
}
return Integer.toString(inv[c]);
}
/*
* Validates that an entered number is Verhoeff compliant.
* NB: Make sure the check digit is the last one.
*/
public static boolean validateVerhoeff(String num) {
int c = 0;
int[] myArray = stringToReversedIntArray(num);
for (int i = 0; i < myArray.length; i++) {
c = d[c][p[(i % 8)][myArray[i]]];
}
return (c == 0);
}
/*
* Converts a string to a reversed integer array.
*/
private static int[] stringToReversedIntArray(String num) {
int[] myArray = new int[num.length()];
for (int i = 0; i < num.length(); i++) {
myArray[i] = Integer.parseInt(num.substring(i, i + 1));
}
myArray = reverse(myArray);
return myArray;
}
/*
* Reverses an int array
*/
private static int[] reverse(int[] myArray) {
int[] reversed = new int[myArray.length];
for (int i = 0; i < myArray.length; i++) {
reversed[i] = myArray[myArray.length - (i + 1)];
}
return reversed;
}
}
and in order to call this and to store the result into a JMeter Variable you need to use vars shorthand to JMeterVariables class instance, something like:
vars.put('myVar', Verhoeff.generateVerhoeff("your-source-number-here"))
and then you will be able to refer the generated value as ${myVar} where required.

Find gap in datetime range with Linq to sql in vb.net

I would like use linq to sql to query (prefer vb.net but c# example will do a table for records that are grouped by a field in the table and have holes in the datetime field that are greater than 30 minutes. My table has records added at regular intervals during the lifetime of a job generally every two minutes occasionally there is a period of missing records. The table holds records for multiple jobs in the same date range although I have only added one with a different job number to highlight this. The table looks like the table below.
Edit:
VB .NET, untested:
Dim jobs = New List(Of Job)() From {
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 0, 0, 0),
.JobGroup = 1,
.Value = 100
},
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 2, 0, 0),
.JobGroup = 1,
.Value = 200
},
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 4, 0, 0),
.JobGroup = 1,
.Value = 300
},
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 7, 0, 0),
.JobGroup = 2,
.Value = 600
},
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 40, 0, 0),
.JobGroup = 1,
.Value = 400
},
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 42, 0, 0),
.JobGroup = 1,
.Value = 500
},
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 9, 0, 0),
.JobGroup = 2,
.Value = 700
},
New Job() With {
.Date = New DateTime(2020, 10, 1, 1, 49, 0, 0),
.JobGroup = 2,
.Value = 800
}
}
Dim gaps = jobs.OrderBy(Function(x) x.JobGroup).Skip(1).Zip(jobs, Function(c, p) New With {Key
.Current = c, Key
.Previous = p, Key
.Gap = (c.Date - p.Date).TotalMinutes
}).Where(Function(x) x.Gap >= 30 AndAlso (x.Current.JobGroup = x.Previous.JobGroup))
For Each gap In gaps
Console.WriteLine($"Job Group: {gap.Current.JobGroup}, Gap (minutes): {gap.Gap}, Value: {gap.Current.Value} ")
Next
End Sub
Class Job
Public Property JobGroup As Integer
Public Property Date As DateTime
Public Property Value As Integer
End Class
I´m a bit rusty at VB so I´ll give you an C# answer like you said.
//Sample Data //Year, Month, Day, Hour, Minute, Second, Millisecond
var jobs = new List<Job>() { new Job() { Date = new DateTime(2020, 10, 1, 1, 0, 0, 0), JobGroup = 1 ,Value = 100},
new Job() { Date = new DateTime(2020, 10, 1, 1, 2, 0, 0),JobGroup = 1 ,Value = 200} ,
new Job() { Date = new DateTime(2020, 10, 1, 1, 4, 0, 0),JobGroup = 1 ,Value = 300},
new Job() { Date = new DateTime(2020, 10, 1, 1, 7, 0, 0), JobGroup = 2 ,Value = 600},
new Job() { Date = new DateTime(2020, 10, 1, 1, 40, 0, 0),JobGroup = 1 ,Value = 400},
new Job() { Date = new DateTime(2020, 10, 1, 1, 42, 0, 0), JobGroup = 1 ,Value = 500},
new Job() { Date = new DateTime(2020, 10, 1, 1, 9, 0, 0), JobGroup = 2 ,Value = 700},
new Job() { Date = new DateTime(2020, 10, 1, 1, 49, 0, 0), JobGroup = 2 ,Value = 800}
};
//Determine gaps
var gaps = jobs.OrderBy(x => x.JobGroup) //don´t mix job group IDs
.Skip(1) //To compare current and previous job record
.Zip(jobs, (c, p) => new { Current = c, Previous = p, Gap = (c.Date - p.Date).TotalMinutes }) //Determine gap between current and previous record
.Where(x => x.Gap >= 30 && (x.Current.JobGroup == x.Previous.JobGroup)); //Only take those gaps which are GT 30 minutes
foreach(var gap in gaps)
{
Console.WriteLine($"Job Group: {gap.Current.JobGroup}, Gap (minutes): {gap.Gap}, Value: {gap.Current.Value} ");
}
//Result:
//Job Group: 1, Gap(minutes): 36, Value: 400
//Job Group: 2, Gap(minutes): 40, Value: 800
My sample data is just a simple DTO
class Job
{
public int JobGroup { get; set; }
public DateTime Date { get; set; }
public int Value { get; set; }
}
Be aware that #Alex B's solution requires the table be pulled into memory before executing because .Zip isn't translatable to SQL. in this case, you may want to look into doing this via a view leveraging SQL's Lag...Over syntax and just consume the results of that via a Linq to SQL Entity. Something like:
CREATE VIEW vwJobGaps AS
SELECT Job, DateAdded, PrevDateAdded, Value,
DATEDIFF(m, PrevDateAdded, DateAdded) As MinutesFromLastJob
FROM
(SELECT Job, DateAdded, Value,
LAG(DateAdded, 1, null) over (Partition by Job order by DateAdded ASC) As PrevDateAdded
FROM MYTable))
And then for your entity:
<Table("vwJobGaps")>
Public Class JobGap
Public Property Job As Integer
Public Property DateAdded As DateTime
Public Property PrevDateAdded As DateTime
Public Property Value As Decimal
Public Property MinutesFromLastJob As Integer
End Class
Since you're using a view here, you can add additional filters, joins, etc using standard LINQ to SQL just as you would other tables:
var query = from gap in dc.JobGaps
where gap.MinutesFromLastJob > 30
'' select clause not needed in vb

Can help make array with only odd numbers from array in Kotlin

I need help. I trying make array only with odd numbers but I don't want use arraylist because I only want array.
Input array like this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I am trying to get odd only array like : [1, 3, 5, 7, 9]
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val arraylist = arrayListOf<Int>()
for(i in 0..array.size - 1) {
if(array[i] % 2 != 0)
arraylist.add(array[i])
}
val oddarray = arraylist.toArray()
Why not just use filter:
import java.util.Arrays;
fun main(args: Array<String>) {
val numbersArray = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val oddArray = numbersArray.filter{ it % 2 != 0 }.toTypedArray()
print(Arrays.toString(oddArray)) // [1, 3, 5, 7, 9]
}