How to change string to int in logql grafana - grafana-loki

|label_format num={{102}}
|label_format num2 = {{90}}
| label_format ans= {{if gt .num .num2 }}good {{else}} bad {{end}}
| line_format {{.ans}}
I have created two labels and assigned values to them.When I perform the gt operation the output shows bad .Its considering the value of num and num2 as string while performing gt operation.
I want the comparison to be done on integer format and the output should be good.
I

Related

how to use while loop in pseudocode

I am trying to add the user inputs using a while loop and If statements. I am having trouble figuring out how to add all the userNumbers to each other. Any help would be appreciated.
//variables
Declare Integer userIn = 0
Declare Integer total = 0
//read numbers and calculate
While decision == decY
Display “Please enter your numbers: ”
Input decision
If UserIn > 0
Display userNumbers
Set total = userIn + 1
Display “Would you like to enter another number Y/N?”
Input decision
If decision == decN
Display “Done reading numbers, your total is ”, total
End If
End If
End While
Decide on a separator for the input, unless they're only allowed to enter a single number at a time in which case you can skip to 3.
Use string splitting to cut the input up and then loop through that list with for, while, do, until, or etc.
Create a sum total variable and add each input value to it, e.g. sum = sum + split_input[index], or if it will only allow a single input at a time sum = sum + input.
Some Notes:
Adding a value to a variable can be shortened to variable += value to add a value to an existing variable and assign the result to the variable, but not all languages support this syntax.
Not all programming languages start at 0 for list indices, so be sure to change the starting index accordingly.

How is the | symbol read in Elm?

Consider the following example code:
-- Update the fields of a record. (It must have the fields already.)
{ person |
name = "George" }
-- Update multiple fields at once, using the current values.
{ particle |
position = particle.position + particle.velocity,
velocity = particle.velocity + particle.acceleration }
Source: Learn Elm in X Minutes
How is one supposed to read | in this example, and in Elm generally?
I'm familiar with it in set-builder notation as "where" / "such that", and in list comprehensions in Haskell it has a very similar purpose, e.g.
[ x*2 | x <- [1..10] ]
is logically equivalent to
source: Learn You A Haskell
(Obviously I'm also familiar with its use as the unary "or" operator in C-like languages)
What about something like type Msg = Increment | Decrement ?
Source: https://guide.elm-lang.org
Or, in this example when discussing Union Types:
type Boolean
= T
| F
| Not Boolean
| And Boolean Boolean
| Or Boolean Boolean
In types I read it as 'or'. In the counter example:
type Msg = Increment | Decrement
I would read it as "a Msg is Increment or Decrement". In a slightly more complex but still common example of the Result type:
type Result error value
= Ok value
| Err error
I would read "a Result is either Ok with a value or Err with an error".
In the example you give of the record update syntax, I would read it as 'with' rather than 'where'. For example:
{ person | name = "George" }
is "the person value with its name field set to "George"" (rather than "where the name = 'George'" which seems to imply that you're filtering based on what values are in person). This one is I think more ambiguous than the type case though.

Convert date with milliseconds using PIG

Really stuck on this! Assume I have a following data set:
A | B
------------------
1/2/12 | 13:3.8
04:4.1 | 12:1.4
15:4.3 | 1/3/13
Observations A and B are in general in the format minutes:seconds.milliseconds like A is a click and B is a response. Sometimes time format has a form of month/day/year if any of the events happens to be in the beginning of the new day.
What I want? Is to calculate average difference between B and A. I can easily handle m:s.ms as splitting them into two parts for each A and B and then cast as DOUBLE and perform all needed operations but it all fails when m/d/yy are introduced. The easiest way to omit them but it is not a really good practice. Is there is a clear way to handle such exceptions using PIG?
A thought worth contemplating ....
Ref : http://pig.apache.org/docs/r0.12.0/func.html for String and Date functions used.
Input :
1/2/12|13:3.8
04:4.1|12:1.4
15:4.3|1/3/13
Pig Script :
A = LOAD 'input.csv' USING PigStorage('|') AS (start_time:chararray,end_time:chararray);
B = FOREACH A GENERATE (INDEXOF(end_time,'/',0) > 0 AND LAST_INDEX_OF(end_time,'/') > 0 AND (INDEXOF(end_time,'/',0) != LAST_INDEX_OF(end_time,'/'))
? (ToUnixTime(ToDate(end_time,'MM/dd/yy'))) : (ToUnixTime(ToDate(end_time,'mm:ss.S')))) -
(INDEXOF(start_time,'/',0) >0 AND LAST_INDEX_OF(start_time,'/') > 0 AND (INDEXOF(start_time,'/',0) != LAST_INDEX_OF(start_time,'/'))
? (ToUnixTime(ToDate(start_time,'MM/dd/yy'))) : (ToUnixTime(ToDate(start_time,'mm:ss.S')))) AS diff_time;
C = FOREACH (GROUP B ALL) GENERATE AVG(B.diff_time);
DUMP C;
N.B. In place of ToUnixTime we can use ToMilliSeconds() method.
Output :
(1.0569718666666666E7)

VBS logical operators initialise empty variables?

Consider the following bit of VBS:
dim msg, myVar, myVar2
msg = "myVar = " & myVar
msg = msg & vbcrlf & "myVar = empty: " & isempty(myVar)
msg = msg & vbcrlf & "TypeName(myVar) = " & TypeName(myVar)
msgbox msg, , "BEFORE"
if not myVar then myVar2 = true
msg = "myVar = " & myVar
msg = msg & vbcrlf & "myVar = empty: " & isempty(myVar)
msg = msg & vbcrlf & "TypeName(myVar) = " & TypeName(myVar)
msgbox msg, , "AFTER"
I would expect the output from "BEFORE" and "AFTER" to be the same... all we're doing is making a comparison to an uninitialised (empty) variant right?
However - it seems like the "if not" actually initialises it to a (long)zero!
I've been coding in VBS (ASP) for donkey's years, and this is a new one on me!
A few things to note:
The behaviour is the same in both a .vbs and the equivalent ASP code (on my Win 7 desktop and on Server 2008 R2.)
All logical operators - and/or/not/xor produce this effect
Comparison operators do not.
It seems like a potential trap for the unwary... Can anyone explain this behaviour?
I couldn't find anything official about this issue.
After doing some test, I decided that this is a bug or an un-documented effect.
This behaviour does not apply on other similar platforms like VBA and VB6.
Visual Basic for Application:
Visual Basic 6:
VBScript:
As a workaround, passing expressions by value works.
If Not (exp) Then
'or
If Not CBool(exp) Then
ByRef and ByVal Parameters
CBool Function
If you change that statement in the middle to
if not (myVar) then myVar2 = true 'with parenthesis around myVar
then you will not witness the same behavior. BEFORE and AFTER are the same now.
That's because apparently the parenthesis force the Not operator to only perform a logical test and will skip the side effect of Not.
On https://msdn.microsoft.com/en-us/subscriptions/9cy86sfb%28v=vs.84%29.aspx you will find the following about Not
In addition, the Not operator inverts the bit values of any variable and
sets the corresponding bit in result according to the following table:
+-------------------+---------------+
| Bit in expression | Bit in result |
+-------------------+---------------+
| 0 | 1 |
| 1 | 0 |
+-------------------+---------------+
For example
Msgbox Not 2 ' is -3
Msgbox Not -3 ' is 2
That makes sense if you consider that internally the values are stored as signed bytes/words.
000 -4
001 -3 --> 001 inverted is 110
010 -2
011 -1
100 0
101 1
110 2 --> 110 inverted is 001
111 3
Let's convert Empty to Long with
x = CLng(myVar)
You will find that the value of x is 0.
If you use
if not myVar then myVar2 = true
then the result of not myVar will be evaluated (and the resulting value of -1 will subsequently be thrown away). But the calculation takes place anyhow and for this it is necessary to convert Empty to a long first.
https://technet.microsoft.com/en-us/library/ee198865.aspx
So, if you create a variable without initializing it, the variable will take on one of these default values:
If you use the variable as a string, the initial value will be Empty.
If you use the variable as a number, the initial value will be 0.
I would think that since you are doing a Boolean check, you are essentially using myVar as a number, and your statement is read like:
if not 0 then myVar2 = true
'same as: if not FALSE then myVar2 = true
And so myVar is initialized to 0
These are the rules from VBA https://msdn.microsoft.com/en-us/library/ee177324.aspx?f=255&MSPPError=-2147217396
The point is that variables (though not objects) always have a usuable value (objects do have a value of nothing).
5.5.1.2.2 Let-coercion to and from Boolean
When not stored as a Boolean value, False is represented by 0, and True is represented by nonzero values, usually -1.
The semantics of Boolean Let-coercion depend on the source’s value type and the destination’s declared type:
Source Value Type Destination Declared Type Semantics
Boolean Boolean The result is a copy of the source value.
Boolean Any numeric type except Byte If the source value is False, the result is 0. Otherwise, the result is -1.
Boolean Byte If the source value is False, the result is 0. Otherwise, the result is 255.
Any numeric type Boolean If the source value is 0, the result is False. Otherwise, the result is True
5.5.1.2.11 Let-coercion from Empty
The semantics of Empty Let-coercion depend on the destination’s declared type:
Source Value Type Destination Declared Type Semantics
Empty Any numeric type The result is 0.
Empty Boolean The result is False.
Empty Date The result is 12/30/1899 00:00:00.
Empty String The result is a 0-length string.
Empty String * length The result is a string containing length spaces.
Empty Any class or Object Runtime error 424 (Object required) is raised.
Empty Any other type except Variant Runtime error 13 (Type mismatch) is raised.
Your variable is coerced as a string when you first messagebox it.
Then it is coerced as false in line above.
5.6.9.5 Relational Operators
Relational operators are simple data operators that perform comparisons between their operands.
relational-operator = equality-operator / inequality-operator / less-than-operator / greaterthan-operator / less-than-equal-operator / greater-than-equal-operator
Static semantics:
Relational operators are statically resolved as simple data operators.
A relational operator is invalid if the declared type of any operand is an array or UDT.
A relational operator has the following declared type, based on the declared type of its operands:
Left Operand Declared Type Right Operand Declared Type Operator Declared Type
Any type except an array, UDT or Variant Any type except an array, UDT or Variant Boolean Any type except an array or UDT Variant
Variant Any type except an array or UDT Variant
Runtime semantics:
Relational operators are first evaluated as simple data operators.
If the value type of any operand is an array or UDT, runtime error 13 (Type mismatch) is raised.
Before evaluating the relational operator, its non-Null operands undergo Let-coercion to the operator’s effective value type.
The effective value type is determined as follows, based on the value types of the operands:
5.6.9.5.1 = Operator
The = operator performs a value equality comparison on its operands.
equality-operator = expression "=" expression
Runtime semantics:
If the operands are considered equal, True is returned. Otherwise, False is returned.

Encode a string variable in non-alphanumeric order

I want to encode a string variable in such a way that assigned numerical codes respect the original order of string values (as shown when using browse). Why? I need encoded variable labels to get the correct variable names when using reshape wide.
Suppose var is a string variable with no labels:
var label(var)
"zoo" none
"abc" none
If you start with:
encode var, gen(var2)
the labels are 1="abc" 2="zoo" as can be seen with
label li
But I want the labels sorted as they come, as shown in browse for an unchanged order of variables later.
I didn't find an encode option in which the labels are added in the order I see when using browse.
My best idea is to do it by hand:
ssc install labutil
labvalch var, f(1 2) t(2 1)
This is nice, but I have >50 list entries.
Other approach: When using reshape use another order, but I don't think that works.
reshape wide x, i(id) j(var)
I only found
ssc install labutil
labmask regioncode, values(region)
as some alternative to encode but I'm not able to cope with strings using labmask.
First off, it's a rule in Stata that string variables can't have value labels. Only numeric variables can have value labels. In essence, what you want as value labels are already in your string variable as string values. So, the nub of the problem is that you need to create a numeric variable with values in the right order.
Let's solve the problem in its easiest form: string values occur once and once only. So
gen long order = _n
labmask order, values(var)
then solves the problem, as the numeric values 1, 2, ... are linked with the string values zoo, abc, whatever, which become value labels. Incidentally, a better reference for labmask, one of mine, is
http://www.stata-journal.com/sjpdf.html?articlenum=gr0034
Now let's make it more complicated. String values might occur once or more times, but we want the numeric variable to respect first occurrence in the data.
gen long order1 = _n
egen order2 = min(order1), by(var)
egen order = group(order2)
labmask order, values(var)
Here's how that works.
gen long order1 = _n
puts the observation numbers 1, 2, whatever in a new variable.
egen order2 = min(order1), by(var)
finds the first occurrence of each distinct value of var.
egen order = group(order2)
maps those numbers to 1, 2, whatever.
labmask order, values(var)
links the numeric values of order and the string values of var, which become its value labels.
Here is an example of how that works in practice.
. l, sep(0)
+---------------------------------+
| var order1 order2 order |
|---------------------------------|
1. | zoo 1 1 zoo |
2. | abc 2 2 abc |
3. | zoo 3 1 zoo |
4. | abc 4 2 abc |
5. | new 5 5 new |
6. | newer 6 6 newer |
+---------------------------------+
. l, nola sep(0)
+---------------------------------+
| var order1 order2 order |
|---------------------------------|
1. | zoo 1 1 1 |
2. | abc 2 2 2 |
3. | zoo 3 1 1 |
4. | abc 4 2 2 |
5. | new 5 5 3 |
6. | newer 6 6 4 |
+---------------------------------+
You would drop order1 order2 once you have got the right answer.
See also sencode for another solution. (search sencode to find references and download locations.)
The user-written command sencode (super encode) by Roger Newson, and available running ssc describe sencode can be used for what you want. Instead of assigning numerical codes based on the alphanumeric order of the string variable, they can be assigned using the order in which the values appear in the original dataset.
clear all
set more off
*------- example data ---------
input str10 var
abc
zoo
zoo
zoo
elephant
elephant
abc
abc
elephant
zoo
end
*------- encode ---------------
encode var, generate(var2)
sencode var, generate(var3)
list, separator(0)
list, separator(0) nolabel
The variable var3 is in the desired form. Contrast that with var2.
I'm not sure if there's an elegant solution, because I think that levelsof orders strings alphabetically.
As long as your list is unique this should work.
clear
input str3 myVar
"zoo"
"abc"
"def"
end
* for reshape
generate iVar = 1
generate jVar = _n
* reshape to wide
reshape wide myVar, i(iVar) j(jVar)
list
* create label
local i = 0
foreach v of varlist myVar* {
local ++i
local myVarName = `v'
label define myLabel `i' "`myVarName'", add
}
* reshape to wide
reshape long myVar, i(iVar) j(myVarEncoded)
* assign label
label value myVarEncoded myLabel

Resources