Elm : How to make use of value with (Result String Value) - elm

For example
fromIsoString : String -> Result String Date
fromIsoString will produce Ok (Value) ... Any methods that i can use to do something with the Value
As what i tested it is working with
text ( `Value` |> Date.add Days -1|> Date.toIsoString)
Method tried : Date.fromIsoString "2018-09-26" |> Result.withDefault 0 gives error -> expects:
Result String #Date#
Ideally i want to transform ISO date (2020-05-10) into Date format and do something with the date like -1 day.
Reference :
https://github.com/justinmimbs/date/blob/3.2.0/src/Date.elm

You’re seeing this Result String #Date# error because you’ve passed Result.withDefault a number where it expects a Date. If we look at the withDefault type annotation:
> Result.withDefault
<function> : a -> Result x a -> a
withDefault expects a default of the same type a as the successful result. Because you’ve specified 0 : number as the default, its type becomes:
> \result -> Result.withDefault 0 result
<function> : Result x number -> number
Note that result's type is Result x number, which doesn't line up with fromIsoString's Result String Date output type.
TLDR: Pass a Date as the default argument, e.g.:
> defaultDate = Date.fromCalendarDate 2020 Jan 1
RD 737425 : Date
> Date.fromIsoString "2018-09-26" |> Result.withDefault defaultDate
RD 736963 : Date
Take a look at the Elm Result documentation for other functions you can call on values of type Result String Date

Related

TypeError: '<' not supported between instances of 'int' and 'Timestamp'

I am trying to change the product name when the period between the expiry date and today is less than 6 months. When I try to add the color, the following error appears:
TypeError: '<' not supported between instances of 'int' and 'Timestamp'.
Validade is the column where the products expiry dates are in. How do I solve it?
epi1 = pd.read_excel('/content/timadatepandasepi.xlsx')
epi2 = epi1.dropna(subset=['Validade'])`
pd.DatetimeIndex(epi2['Validade'])
today = pd.to_datetime('today').normalize()
epi2['ate_vencer'] = (epi2['Validade'] - today) /np.timedelta64(1, 'M')
def add_color(x):
if 0 <x< epi2['ate_vencer']:
color='red'
return f'background = {color}'
epi2.style.applymap(add_color, subset=['Validade'])
Looking at your data, it seems that you're subtracting two dates and using this result inside your comparison. The problem is likely occurring because df['date1'] - today returns a pandas.Series with values of type pandas._libs.tslibs.timedeltas.Timedelta, and this type of object does not allow you to make comparisons with integers. Here's a possible solution:
epi2['ate_vencer'] = (epi2['Validade'] - today).dt.days
# Now you can compare values from `"ate_vencer"` with integers. For example:
def f(x): # Dummy function for demonstration purposes
return 0 < x < 10
epi2['ate_vencer'].apply(f) # This works
Example 1
Here's a similar error to yours, when subtracting dates and calling function f without .dt.days:
Example 2
Here's the same code but instead using .dt.days:

Select columns based on exact row value matches

I am trying to select columns of a specified integer value (24). However, my new dataframe includes all values = and > 24. I have tried converting from integer to both float and string, and it gives the same results. Writing "24" and 24 gives same result. The dataframe is loaded from a .csv file.
data_PM1_query24 = data_PM1.query('hours == "24"' and 'averages_590_nm_minus_blank > 0.3')
data_PM1_sorted24 = data_PM1_query24.sort_values(by=['hours', 'averages_590_nm_minus_blank'])
data_PM1_sorted24
What am I missing here?
Please try out the below codes. I'm assuming that the data type of "hours" and "averages_590_nm_minus_blank" is float. If not float, convert them to float.
data_PM1_query24 = data_PM1.query('hours == 24 & averages_590_nm_minus_blank > 0.3')
or you can also use,
data_PM1_query24 = data_PM1[(data_PM1.hours == 24) & (data.averages_590_nm_minus_blank > 0.3)]
Hope this solves your query!

String to Int throwing a NumberFormatException

I am wanting to convert a String to an Int.
The String, in question, is 1585489022235.
I have to convert to a String, first, which appears to be successful (I am printing out the above).
val id = data.get("id").toString()
println(id)
val toInt = id.toInt()
When I attempt to convert from a String to an Int, this exception is thrown:
Error Message: java.lang.NumberFormatException: For input string: "1585489022235"
Stacktrace:
java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
java.base/java.lang.Integer.parseInt(Integer.java:658)
java.base/java.lang.Integer.parseInt(Integer.java:776)
Many thanks in advance
The value "1585489022235" can't be converted to an Int because it is greater than the maximum value of the data type Int which you can get by Int.MAX_VALUE and it is equal to 2147483647.
What you can do is covert the string to Long:
val x = id.toLong()
The maximum value of the data type long is 9223372036854775807, which you can get by Long.MAX_VALUE.
You can find more here: Basic Types - Numbers

Sorting List of Objects Containing Maybe Time.Posix

I have a List of custom types that I would like to sort on one attribute which is of type Maybe Time.Posix. In reading the docs I've come to the conclusion I should use List.sortWith, as neither Maybe nor Time.Posix values are comparable. I've written a set of functions to prepare the values so they are comparable. The challenge that I'm facing, though, is pulling the values from the types in the list.
Here are the functions:
maybeCompare : (a -> a -> Order) -> Maybe a -> Maybe a -> Order
maybeCompare f a b =
case a of
Just some_a ->
case b of
Just some_b ->
f some_a some_b
Nothing ->
GT
Nothing ->
LT
posixCompare : Time.Posix -> Time.Posix -> Order
posixCompare a b = compare (posixToMillis(a)) (posixToMillis(b))
posMay = maybeCompare (posixCompare)
Which I combine and use like this:
List.sortWith (posMay .time) objList
On data that looks like this:
obj1 = {id=1,time= Just time1}
obj2 = {id=2,time= Just time2}
obj3 = {id=3,time= Just time3}
obj4 = {id=4,time= Just time4}
obj5 = {id=5,time= Nothing}
objList = obj1 :: obj2 :: obj3 :: obj4 :: obj5 :: []
Now, this approach works for a list like this List (Maybe Time.Posix). By which I mean I get the output I expect, the list is sorted on the Posix time with the Nothing values in the desired location.
However, for a List of types where Maybe Time.Posix is one of the values I get this error (one of many, but I think this is the source):
List.sortWith (posMay .time) objList
^^^^^
This .time field access function has type:
{ b | time : a } -> a
But `posMay` needs the 1st argument to be:
Maybe Time.Posix
Is there are way to make the types of my functions align to sort this kind of data? Or, should I rethink my approach?
I've created a working example at https://ellie-app.com/8dp2qD6fDzBa1
Your posMay function is of the type Maybe a -> Maybe a -> Order, so it's not expecting .time, which is a function of type {id:Int,time:Maybe Posix} -> Maybe Posix.
Instead, you can create a different function which shims between posMay and List.sortWith, which would look like this: List.sortWith (\a b -> posMay a.time b.time)
If you want to be able to pass a getter function to posMay, you could rewrite it to accept that function:
posMay getter a b =
maybeCompare posixCompare (getter a) (getter b)
Then, you would use it like this: List.sortWith (posMay .time) (or List.sortWith (posMay identity) for a List (Maybe Posix). A version that works like this is at https://ellie-app.com/8dp7gm3qthka1

Octave keyboard input function to filter concatenated string and integer?

if we write 12wkd3, how to choose/filter 123 as integer in octave?
example in octave:
A = input("A?\n")
A?
12wkd3
A = 123
while 12wkd3 is user keyboard input and A = 123 is the expected answer.
assuming that the general form you're looking for is taking an arbitrary string from the user input, removing anything non-numeric, and storing the result it as an integer:
A = input("A? /n",'s');
A = int32(str2num(A(isdigit(A))));
example output:
A?
324bhtk.p89u34
A = 3248934
to clarify what's written above:
in the input statement, the 's' argument causes the answer to get stored as a string, otherwise it's evaluated by Octave first. most inputs would produce errors, others may be interpreted as functions or variables.
isdigit(A) produces a logical array of values for A with a 1 for any character that is a 0-9 number, and 0 otherwise.
isdigit('a1 3 b.') = [0 1 0 1 0 0 0]
A(isdigit(A)) will produce a substring from A using only those values corresponding to a 1 in the logical array above.
A(isdigit(A)) = 13
that still returns a string, so you need to convert it into a number using str2num(). that, however, outputs a double precision number. so finally to get it to be an integer you can use int32()