python 3.5 printing formated float number - printing

I've found something interesting with my python3.5
So this is the code
previous = 0.1234567891011121314
now = 2.98764627181
print("Before: {0:.15f}".format(float(previous)))
print("Now: {0:.15f}".format(float(now)))
print(" Before:{0:.15f} Now:{0:.15f} ".format(float(previous), float(now)))
and this is the result
Before: 0.123456789101112
Now: 2.987646271810000
Before:0.123456789101112 Now:0.123456789101112
So when I want to print them with one single print and format function
python3.5 seems to not able to handle it. Am I doing something wrong?

The 0 in the {0:.15f} replacement field is a field name, as specified in the Python documentation for string formatting. When the field name is a number, it identifies a positional argument. Since you have 0 in both replacement fields, both are replaced with the positional argument numbered 0.
To use the other argument, use {1:.15f}.

Related

Getting "trailing characters" error when trying to parse string with serde_json

I need to convert a specific string in serde_json::Value, but getting a trailing character error while using:
let new_str = "73723235c81ebbec0"
let json_value: serde_json::Value = serde_json::from_str(new_str).unwrap();
Error:
trailing characters at line 1 column 9
Is there any way to convert these kinds of strings to serde_json::Value?
Looking at the repo for serde_json, it appears from their test cases this is expected behavior. For example, see this test case. Since your string starts with numeric values, it is attempting to parse as a number and then fails when it reaches the 'c' in position 9.
Rather than calling from_str(), use to_value(). This will give you a String variant of the Value enum.
let json_value: serde_json::Value = serde_json::to_value(&new_str).unwrap();
Also, if you use to_value(), you can omit the type identifier for your variable, which I believe is probably more idiomatic.
let json_value = serde_json::to_value(&new_str).unwrap();

How to specify a range in Ruby

I've been looking for a good way to see if a string of items are all numbers, and thought there might be a way of specifying a range from 0 to 9 and seeing if they're included in the string, but all that I've looked up online has really confused me.
def validate_pin(pin)
(pin.length == 4 || pin.length == 6) && pin.count("0-9") == pin.length
end
The code above is someone else's work and I've been trying to identify how it works. It's a pin checker - takes in a set of characters and ensures the string is either 4 or 6 digits and all numbers - but how does the range work?
When I did this problem I tried to use to_a? Integer and a bunch of other things including ranges such as (0..9) and ("0..9) and ("0".."9") to validate a character is an integer. When I saw ("0-9) it confused the heck out of me, and half an hour of googling and youtube has only left me with regex tutorials (which I'm interested in, but currently just trying to get the basics down)
So to sum this up, my goal is to understand a more semantic/concise way to identify if a character is an integer. Whatever is the simplest way. All and any feedback is welcome. I am a new rubyist and trying to get down my fundamentals. Thank You.
Regex really is the right way to do this. It's specifically for testing patterns in strings. This is how you'd test "do all characters in this string fall in the range of characters 0-9?":
pin.match(/\A[0-9]+\z/)
This regex says "Does this string start and end with at least one of the characters 0-9, with nothing else in between?" - the \A and \z are start-of-string and end-of-string matchers, and the [0-9]+ matches any one or more of any character in that range.
You could even do your entire check in one line of regex:
pin.match(/\A([0-9]{4}|[0-9]{6})\z/)
Which says "Does this string consist of the characters 0-9 repeated exactly 4 times, or the characters 0-9, repeated exactly 6 times?"
Ruby's String#count method does something similar to this, though it just counts the number of occurrences of the characters passed, and it uses something similar to regex ranges to allow you to specify character ranges.
The sequence c1-c2 means all characters between c1 and c2.
Thus, it expands the parameter "0-9" into the list of characters "0123456789", and then it tests how many of the characters in the string match that list of characters.
This will work to verify that a certain number of numbers exist in the string, and the length checks let you implicitly test that no other characters exist in the string. However, regexes let you assert that directly, by ensuring that the whole string matches a given pattern, including length constraints.
Count everything non-digit in pin and check if this count is zero:
pin.count("^0-9").zero?
Since you seem to be looking for answers outside regex and since Chris already spelled out how the count method was being implemented in the example above, I'll try to add one more idea for testing whether a string is an Integer or not:
pin.to_i.to_s == pin
What we're doing is converting the string to an integer, converting that result back to a string, and then testing to see if anything changed during the process. If the result is =>true, then you know nothing changed during the conversion to an integer and therefore the string is only an Integer.
EDIT:
The example above only works if the entire string is an Integer and won’t properly deal with leading zeros. If you want to check to make sure each and every character is an Integer then do something like this instead:
pin.prepend(“1”).to_i.to_s(1..-1) == pin
Part of the question seems to be exactly HOW the following portion of code is doing its job:
pin.count("0-9")
This piece of the code is simply returning a count of how many instances of the numbers 0 through 9 exist in the string. That's only one piece of the relevant section of code though. You need to look at the rest of the line to make sense of it:
pin.count("0-9") == pin.length
The first part counts how many instances then the second part compares that to the length of the string. If they are equal (==) then that means every character in the string is an Integer.
Sometimes negation can be used to advantage:
!pin.match?(/\D/) && [4,6].include?(pin.length)
pin.match?(/\D/) returns true if the string contains a character other than a digit (matching /\D/), in which case it it would be negated to false.
One advantage of using negation here is that if the string contains a character other than a digit pin.match?(/\D/) would return true as soon as a non-digit is found, as opposed to methods that examine all the characters in the string.

In Lua: How to write a HEX value to an app that expects a HEX value?

I have an app UI that expects a HEX value e.g. foo = 0x113
I'm doing this in Lua to try to write to foo:
menu.set("Presets", "foo", "0x318")
menu.set("Presets", "888x", "-258")
menu.set("Presets", "89ab", "-60"
The values for 888x and 89ab in the app are set. The HEX value field remains empty. Could someone help please? Thanks.
There is no such thing as an hex value. There are numbers expressed in hex.
So your API expects a number. No wonder "0x318" does not work. The other two work because the strings are convertible to numbers.
Bottom line: use menu.set("Presets", "foo", 0x318).

Retrieve value by variable name in erlang function

Is it possible somehow to retrieve variable value by its name (name represented as string)?
% we are calling foo function as foo(3)
foo(Param) ->
Var1 = Param * 2,
% some magic code here which can evaluate
% "Var1" string to Var1's value (6)
ok.
I want to implement (if it is possible) some kind of logger macro, like
Param = 3*4,
% This should write "My parameter value is 12" to log
?LOG("My parameter value is $Param").
Thanks.
The common way to log is to have formatting string and list of parameters. However your idea is achievable through usage of parse transform.
Thanks to Dmitry Belyaev for mentioning parse transform.
Say we have logging code:
?dump("My parameter value is $Param")
What I need here is to parse variables within format string ("My parameter value is $Param") with some regular expression. This format string contains single var name (Param). And we need to insert io_lib:format function call (by transforming original AST) with modified format string:
print_message(io_lib:format("My parameter value is ~p~n", [Param]))
In result we can archive required behavior:
Bar = "hello",
Buzz = buzz123,
?dump("Say $Bar to $Buzz"),
% => example:19: Say "hello" to buzz123
You can look at my implementation here
For toy problems you could use:
io:format("My parameter value is ~p~n", [Param]).
See io_lib and io.
Alternatively:
error_logger:info_report/1
or other error_logger functions.
The logging library lager is commonly used.

TeX edef macro blues

I spent some time trying to write a 'helper' macro to test a parameter for a new value, else use the existing value -- default values exist for all parameter positions.
I wanted to be able to write:
\foo{left}{nil}{}{20pt}
so that the second parameter would used its current value but the third value would be the value empty string. I wanted to use the notation:
\edef\pA{\isnil{#1}{\pA){#1}} % one for each parameter
I defined \isnil like so:
\def\nil{nil}
\def\isnil#1#2#3{%
\edef\nilTest{#1}%
\ifx\nilTest\nil#2\else#3\fi
}
but when I tried to run it, TeX complained that \nilTest is an undefined control sequence.
That is true of course, but I want \pA to hold a value, not a recipe for a value, so it must be an \edef which means that all the macro test will be expanded but while will the \edef not protect the \nilTest -- is this a place to use \noexpand -- that did not seem to work for me.
EDIT: no digits in \cs names (yeah, I knew that.)
Why doesn't your solution work? \edef\pA{\isnil{#1}{\pA){#1}} expands \isnil and gets \edef\nilTest{.... Now \edef is not expandable and falls into a sequence of \pA as the first element. An attempt to expand the next macro \nilTest fails.
Use \setpar from the following code to change your parameter.
\def\nil{nil}
\def\setpar#1#2{%
\edef\nilTest{#2}%
\ifx\nilTest\nil\else\let#1\nilTest\fi}
\def\first{old first}
\def\second{old second}
\setpar \first{nil}
\setpar \second{new}
first = ``\first'', second = ``\second''
P.S. Do not use digits in your macro.

Resources