IFF function in KQL azure analytics? - kql

I am trying to create an ifelse statement in KQL but I cannot find documentation about if its possible to do what I am trying.
Basically what I am trying to do to summarize ONLY if the conditions(EventResults=="Success") are met and do another summarize if they arent.
summarize SuccessCount=count(), SuccessUsers=makeset(User) by SrcDvcIpAddr, bin(TimeGenerated, timeframe)
ELSE
summarize FailCount=count(), SuccessUsers=makeset(User) by SrcDvcIpAddr, bin(TimeGenerated, timeframe)
I didnt really find any information about where and how I could use iff other than with the extend operator on the offical microsoft documentation page.
Is what I am trying to do possible?

// Sample data generation. Not Part of the solution.
let imAuthentication = materialize(range i from 1 to 500 step 1 | extend User = strcat("user_", tostring(toint(rand(10))+1)), SrcDvcIpAddr = tostring(dynamic(["1.1.1.1", "2.2.2.2", "3.3.3.3"])[toint(rand(2))]), EventResult = tostring(dynamic(["Success", "Failure"])[toint(rand(2))]), EventType ="Logon", EventProduct = "AAD", TimeGenerated = ago(12h * rand()));
// Solution starts here.
let sigin_threshold = 5;
let endtime = 12h;
let timeframe = 15m;
imAuthentication
|where TimeGenerated >= ago(endtime)
and EventProduct == "AAD"
and EventType =="Logon"
and EventResult in ("Success", "Failure")
and SrcDvcIpAddr != "-"
and isnotempty(User)
|summarize SuccessCount = countif(EventResult == "Success")
,FailCount = countif(EventResult == "Failure")
,SuccessUsers = make_set_if(User, EventResult == "Success")
,FailUsers = make_set_if(User, EventResult == "Failure")
by SrcDvcIpAddr
,bin(TimeGenerated, timeframe)
|where FailCount > sigin_threshold
SrcDvcIpAddr
TimeGenerated
SuccessCount
FailCount
SuccessUsers
FailUsers
2.2.2.2
2023-01-20T10:15:00Z
3
7
["user_3","user_2"]
["user_8","user_2","user_10","user_6","user_3","user_5"]
2.2.2.2
2023-01-20T11:00:00Z
4
6
["user_9","user_3","user_6"]
["user_8","user_7","user_2","user_4","user_9"]
1.1.1.1
2023-01-20T11:15:00Z
4
6
["user_10","user_7","user_4"]
["user_9","user_4","user_3"]
1.1.1.1
2023-01-20T11:45:00Z
3
6
["user_2","user_1","user_7"]
["user_2","user_1","user_9","user_4"]
2.2.2.2
2023-01-20T12:15:00Z
3
8
["user_4","user_5"]
["user_6","user_8","user_7","user_2","user_3","user_1","user_5"]
Fiddle

Related

Azure AlertRule queries sometimes changes query

I have an Azure AlertRule what validates a query, where to tables are joining on a timestamp.
Is seems like Azure is changing the query, replacing the statement bin(..) with bin_at(..).
The Original query:
The query, opened after the alert triggered.
In my case this change is enough to alter the result of the query, becuase the extra added parameter (yellow arrow).
Is there any way around the issue?
EDIT:
as David pointed out in the comments -
This behaviour can be reproduced by running this kql as the query of an alart rule:
print bin(now(), 1h)
Original:
For completness, i've added the entier query here. I was not able to shorten it more that this. (sorry)
let frame_size = 1h;
let messages = datatable (timestamp: datetime )
[
datetime(2022-11-09T23:01:00Z),datetime(2022-11-09T23:02:00Z),datetime(2022-11-09T23:03:00Z),datetime(2022-11-09T23:04:00Z),
datetime(2022-11-09T22:01:00Z),datetime(2022-11-09T22:02:00Z),datetime(2022-11-09T22:03:00Z),datetime(2022-11-09T22:04:00Z),
datetime(2022-11-09T21:01:00Z),datetime(2022-11-09T21:02:00Z),datetime(2022-11-09T21:03:00Z),datetime(2022-11-09T21:04:00Z),
datetime(2022-11-09T20:01:00Z),datetime(2022-11-09T20:02:00Z),datetime(2022-11-09T20:03:00Z),datetime(2022-11-09T20:04:00Z),
datetime(2022-11-09T19:01:00Z),datetime(2022-11-09T19:02:00Z),datetime(2022-11-09T19:03:00Z),datetime(2022-11-09T19:04:00Z),
datetime(2022-11-09T18:01:00Z),datetime(2022-11-09T18:02:00Z),datetime(2022-11-09T18:03:00Z),datetime(2022-11-09T18:04:00Z),
datetime(2022-11-09T17:01:00Z),datetime(2022-11-09T17:02:00Z),datetime(2022-11-09T17:03:00Z),datetime(2022-11-09T17:04:00Z),
datetime(2022-11-09T16:01:00Z),datetime(2022-11-09T16:02:00Z),datetime(2022-11-09T16:03:00Z),datetime(2022-11-09T16:04:00Z),
datetime(2022-11-09T15:01:00Z),datetime(2022-11-09T15:02:00Z),datetime(2022-11-09T15:03:00Z),datetime(2022-11-09T15:04:00Z),
datetime(2022-11-09T14:01:00Z),datetime(2022-11-09T14:02:00Z),
datetime(2022-11-09T13:01:00Z),datetime(2022-11-09T13:02:00Z),
datetime(2022-11-09T12:01:00Z),datetime(2022-11-09T12:02:00Z),
datetime(2022-11-09T11:01:00Z),datetime(2022-11-09T11:02:00Z),
datetime(2022-11-09T10:01:00Z),datetime(2022-11-09T10:02:00Z),
datetime(2022-11-09T09:01:00Z),datetime(2022-11-09T09:02:00Z),
datetime(2022-11-09T08:01:00Z),datetime(2022-11-09T08:02:00Z),
datetime(2022-11-09T07:01:00Z),datetime(2022-11-09T07:02:00Z),
datetime(2022-11-09T06:01:00Z),datetime(2022-11-09T06:02:00Z),
datetime(2022-11-09T06:01:00Z),datetime(2022-11-09T06:02:00Z),
datetime(2022-11-09T05:01:00Z),datetime(2022-11-09T05:02:00Z),
datetime(2022-11-09T04:01:00Z),datetime(2022-11-09T04:02:00Z),
datetime(2022-11-09T03:01:00Z),datetime(2022-11-09T03:02:00Z),
datetime(2022-11-09T02:01:00Z),datetime(2022-11-09T02:02:00Z),
datetime(2022-11-09T01:01:00Z),datetime(2022-11-09T01:02:00Z),
datetime(2022-11-09T00:01:00Z),datetime(2022-11-09T00:02:00Z),
];
let create_time_intervals = (start_datetime: datetime, end_datetime: datetime, frame_size: timespan)
{
let hourly_distribution_as_dk_time = datatable (hour: int, expected_documents_count: int)
[0,2, 1,2, 2,2, 3,2, 4,2, 5,2, 6,2, 7,2, 8,2, 9,2, 10,2, 11,2, 12,2, 13,2, 14,2, 15,4, 16,4, 17,4, 18,4, 19,4, 20,4, 21,4, 22,4, 23,4 ]
;
let start_datetime_dk = datetime_utc_to_local(start_datetime, "Europe/Copenhagen");
let end_datetime_dk = datetime_utc_to_local(end_datetime, "Europe/Copenhagen");
// Generate all time frames for given interval excluding the first incomplete frame.
range frame_start from bin(start_datetime + frame_size, frame_size) to end_datetime step frame_size
| project bin(frame_start, frame_size)
| extend date_dk = datetime_utc_to_local(frame_start, "Europe/Copenhagen")
| extend hour = toint(datetime_part("Hour", date_dk))
| join kind=leftouter hourly_distribution_as_dk_time on hour
| project frame_start, expected_documents_count
| order by frame_start asc
};
let msg = messages
| where timestamp >= ago(1h)
|summarize cnt = count()
by frame_start = bin(timestamp,frame_size); // *** <==== this bin(..) changes when running ***
let frame_results = create_time_intervals(ago(1h), now(), frame_size)
| join kind=leftouter msg on frame_start
| extend ok = cnt;
frame_results
| summarize
sum_expected = sum(expected_documents_count),
sum_ok = sum(ok)
| extend ok = sum_expected == sum_ok
| extend ok_int = toint(ok) //for alerting purposes
Well, an obvious work-around would be to replace bin with bin_at, e.g. -
let timestamp = datetime(2000-03-04 11:22:33);
let frame_size = 1h;
print bin_at(timestamp, frame_size, datetime(2000))
print_0
2000-03-04T11:00:00Z
Fiddle

Conditionally change record in update

I would like to have some logic worked upon the Msg and, depending on the result, update the view in a different ways.
I'm flipping some cards, and I want to test two of the selected ones. Then, accept them as a pair or discard and try again.
update : Msg -> Model -> Model
update msg model =
case msg of
ClickedCard data ->
{ model
| activeCard = data.id
, (if List.lenght selectedCards < 2 then
selectedCards = data.id :: model.selectedCards
else if (List.take 1 model.selectedCards) == (List.drop 1 model.selectedCards) then
completedPairs = ( List.take 1 model.selectedCards , List.drop 1 model.selectedCards ):: model.completedPairs
else
selectedCards = List.drop 2 model.selectedCards)
}
_ ->
model
But, seems like I can't insert the logic there. Where should I put it, instead?
-- PROBLEM IN RECORD ------------------------------------------ src/Flipping.elm
I am partway through parsing a record, but I got stuck here:
126| { model
127| | activeCard = data.id
128| , (if List.lenght selectedCards < 2 then
^
I was expecting to see another record field defined next, so I am looking for a
name like userName or plantHeight.
The record update syntax doesn't work like that.
You can do the following.
update : Msg -> Model -> Model
update msg model =
case msg of
ClickedCard data ->
let
newModel = { model | activeCard = data.id }
in
if List.length selectedCards < 2 then
{newModel | selectedCards = data.id :: model.selectedCards}
else if (List.take 1 model.selectedCards) == (List.drop 1 model.selectedCards) then
{newModel | completedPairs = ( List.take 1 model.selectedCards , List.drop 1 model.selectedCards ):: model.completedPairs}
else
{newModel | selectedCards = List.drop 2 model.selectedCards)}
_ ->
model

In Pine-Script, how do I code two conditions for my entry?

Could someone please help as I need entry conditions to include the BraidFilter indicator into my strategy. I only need a trade entry long when the green bars and short entry when the red bars cross over the filter line. This is what I did but it's not working and I'm getting a ton of error messages:
Please help. Thank you.
//-- Braid Filter
ma01 = ma(maType, close, Period1)
ma02 = ma(maType, open, Period2)
ma03 = ma(maType, close, Period3)
max = max(max(ma01, ma02), ma03)
min = min(min(ma01, ma02), ma03)
dif = max - min
filter = atr(14) * PipsMinSepPercent / 100
//-- Plots/=
//BraidColor = ma01 > ma02 and dif > filter ? color.green : ma02 > ma01 and dif > filter ? color.red : color.gray
//plot(dif, "Braid", BraidColor, 5, plot.style_columns)
//plot(filter, "Filter", color.blue, 2, plot.style_line)
//bgcolor(BraidColor)
// Condition
C1Price1 = 0.0
C1Price2 = 0.0
C1Price1 := ? ma01 > ma02 and dif > filter
C1Price2 := ? ma02 > ma01 and dif > filter
c1Cross_Long = crossover (C1Price1,C1Price2) and C1Price1 > filter
c1Cross_Short = crossover (C1Price1,C1Price2) and C1Price2 > filter
There are things missing in that code, first you have to define the script with a strategy, then define the maType variable, in addition to that:
C1Price1: =**?** ma01> ma02 and dif> filter
C1Price2: =**?** ma02> ma01 and dif> filter
prior to "?" There must be a condition to meet, I think something was deleted there, after correcting that you will have to write the entries.

Finding index using switch case statement in javascript

I'm using Pentaho(ETL) tool to achieve the output using a javascript component which accepts javascript code to achieve the desired transformation.The following table is imported into pentaho from a .csv file(source file).
For example this is my table structure
+--------+--------+--------+
| RLD | MD | INC |
+--------+--------+--------+
| 0 | 3868 | 302024 |
| 53454 | 7699 | 203719 |
| 154508 | 932 | 47694 |
| 107547 | 36168 | 83592 |
I want to use a script which would give me the max_value and its index number, such that my output would look like
Output Table
+--------+--------+--------+-----------+-----------+
| RQD | MT | IZC | max_value | max_index |
+--------+--------+--------+-----------+-----------+
| 0 | 3868 | 302024 | 302024 | 3 |
| 53454 | 7699 | 203719 | 203719 | 3 |
| 154508 | 932 | 47694 | 154508 | 1 |
| 456 | 107547| 83592 | 107547 | 2 |
To get the max value from rows I have used
var max_value = Math.max(RQD,MT,IZC);
println(max_value);
I tried to get their index using the following script
var max_index = switch (Math.max(RQD,MT,IZC))
{
case "RQD":document.write("1")
case "MT":document.write("2")
case "MT":document.write("3")
default:document.write("0")
}
How can I get the desired result in the form of javascript data structure? Any help would be much appreciated.Thanks
var list = [
{RLD:0,
MD:3868,
INC:302024
},
{RLD:53454,
MD:7699,
INC:203719
},
{RLD:154508,
MD:932,
INC:47694
},
{RLD:107547,
MD:36168,
INC:83592
},
];
list = list.map(function(item){
var keys = Object.keys(item);
item.max_value = item[keys[0]];
item.max_index = '';
for(var i = 1, l = keys.length; i < l; i++) {
var key = keys[i];
var keyValue = item[key];
if (item.max_value < keyValue){
item.max_value = keyValue;
item.max_index = key;
}
}
return item;
})
There are several issues with your code, lets solve them!
Use breaks: you must use breaks in order to avoid the switch moving to cases below its match.
switch cases do not return a value like functions, you cannot use a switch return to define a variable, you need to define the variable inside the switch case.
Math.max does not return the name of its maximum variable, instead it returns the maximum number from its given parameters.
to solve this issue, i would not use a switch case with math.max to be honest, however to answer your question:
var tableArray = [RQD,MT,IZC];
var maxIndex = tableArray.indexOf(Math.max.apply(null, arr));
if(maxIndex > -1) document.write(maxIndex+1);
i used +1 because you have your index in the example table starting from 1 instead of 0.
the way the array is sorted should match the way the table is sorted per raw.
First of all you could not solve this problem with a switch statement.
In a javascript switch you should provide a value that is one of the followed case(s), otherwise the switch will go to the default if defined.
Your problem seems to be to find out the higher value of 3 columns and print out, the colums row by row adding a column with the max value and the index of the column where you found it.
So for example on the row:
1, RLD : 0
2, MD : 3868
3, INC : 302024
In this case the higher value is INC with the column index 3.
If you have just the variables with the number values, you could do nothing more than something like this:
function getMaxValueRow (RLD, MD, INC) {
var max_value = RLD;
var max_index = 1;
if (MD > max_value) {
max_value = MD;
max_index = 2;
}
if (INC > max_value) {
max_value = INC;
max_index = 3;
}
return [RLD, MD, INC, max_value, max_index];
}
You could return an object too like this:
retrun {
'RQD': RLD,
'MT': MD,
'IZC': INC,
'max_value': max_value,
'max_index': max_index
}

How to copy data from an object row into another object row from the same class in rails

I have been searching online but I had no luck to get the best way to do this.
I have a controller, in that controller I execute a sql query to retrieve all requests from a user
#solicitudes = Solicitud.where("user_id = ?",#current_user.id)
And I want to know how to transfer each data row on the main object to the proper object with all requests with the same status. I have tried:
#solicitudes.each do |solicitud|
if solicitud.estado == 1
#solicitudes_pendientes << solicitud
else
if solicitud.estado == 2
#solicitudes_aprobadas << solicitud
else
if solicitud.estado == 3
#solicitudes_rechazadas << solicitud
end
end
end
end
But clearly is not working.
At the moment I am using 3 sql queries to retrieve all requests into their corresponding objects but that takes 3 x time + 2 extra transactions:
#solicitudes_pendientes = Solicitud.where("estado = 1 and user_id = ?",#current_aplicante.id)
#solicitudes_aprobadas = Solicitud.where("estado = 2 and user_id = ?",#current_aplicante.id)
#solicitudes_rechazadas = Solicitud.where("estado = 3 and user_id = ?",#current_aplicante.id)
Waiting for any useful advise. Thank you.
You can use Enumerable#group_by
#solicitudes = Solicitud.where(:user_id => #current_user.id).entries.group_by(&:estado)
which will give you a Hash of the form
{
1 => [#<Solicitud estado: 1>, #<Solicitud estado: 1>],
2 => [#<Solicitud estado: 2>, #<Solicitud estado: 2>, ..],
3 => ..,
..
}
You can access them like
#solicitudes_pendientes = #solicitudes[1]