Make it work: ICU/php-intl mnemonic tag "few" for pluralization formatting - icu

ICU message formatting doesn't seem to work for me. Here's the example:
$n = 22;
$f = MessageFormatter::create('ru', '{n, plural, one{корова} few{коровы} many{коров} other{коров}}');
echo $n.' '.$f->format(['n' => $n])."\n";
I get 22 коров in output, but obviously should get 22 коровы. Tried on several ubuntu servers.
Language: Russian
php-intl version 1.1.0
ICU version 52.1
Any help will be appriciated, cause I stuck on it.

That's one nasty bug, one that I've spent almost hour figuring out. Well, it turns out in ICU 52.1 (probably before, too) we have the following:
set34{
many{
"v = 0 and i % 10 = 0 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100"
" = 11..14 #integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, …"
}
one{
"v = 0 and i % 10 = 1 and i % 100 != 11 #integer 1, 21, 31, 41, 51, 6"
"1, 71, 81, 101, 1001, …"
}
other{
" #integer 2~4, 22~24, 32~34, 42~44, 52~54, 62, 102, 1002, … #decimal"
" 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, …"
}
}
Source: http://source.icu-project.org/repos/icu/icu/tags/release-52-1/source/data/misc/plurals.txt
So, cases of 2-4, 22-24 and so on (22 коровы) fall under other modifier, so the correct syntax for your case would be {n, plural, one{корова} few{коровы} many{коров} other{коровы}}. I left few in for compatibility with newer ICU versions (which indeed use few modifier for this case).

Related

Functional way of creating a vector of vector of &str in Rust where the separator will be an empty new line

I am doing the advent of code 2022 day 11, where I have the following input as a &str:
Monkey 0:
Starting items: 52, 60, 85, 69, 75, 75
Operation: new = old * 17
Test: divisible by 13
If true: throw to monkey 6
If false: throw to monkey 7
Monkey 1:
Starting items: 96, 82, 61, 99, 82, 84, 85
Operation: new = old + 8
Test: divisible by 7
If true: throw to monkey 0
If false: throw to monkey 7
Monkey 2:
Starting items: 95, 79
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 5
If false: throw to monkey 3
how can I use the functional api of rust to get a vector of vector where the inner vector would contain the phrases of a monkey block? The separator should be the empty new line.
The output should be something like this:
[["Monkey 0:", " Starting items: 52, 60, 85, 69, 75, 75", " Operation: new = old * 17", " Test: divisible by 13", " If true: throw to monkey 6", " If false: throw to monkey 7"], [" Monkey 1:", " Starting items: 96, 82, 61, 99, 82, 84, 85", " Operation: new = old + 8", " Test: divisible by 7", " If true: throw to monkey 0", " If false: throw to monkey 7"]]
I have managed to do it in the imperative way, but I was not able to create it using the functional way (map, filter, fold, etc). I think the functional way is way more idiomatic rust
https://doc.rust-lang.org/std/primitive.str.html#method.split
let sections: Vec<Vec<&str>> = inpu
.split("\n\n")
.map(|section| -> Vec<&str> { section.lines().collect() })
.collect();

Python3 Global Variable Issue

I am trying to learn about loops and conditions. Therefore I coded a generator, which randomly create lotto/lottery numbers. However I created a global variable 'valCount', which stores the generation count. But still got this error:
Bitte die Anzahl zu erzeugender Lottoscheine angeben: 2
Input is an integer number. Number = 2
Traceback (most recent call last):
File "/Volumes/HDD/Users/Stephan/PycharmProjects/LottZahlenGeneratorLoop/main.py", line 87, in
check_user_input(userCountInput)
File "/Volumes/HDD/Users/Stephan/PycharmProjects/LottZahlenGeneratorLoop/main.py", line 70, in check_user_input
outPutCount()
File "/Volumes/HDD/Users/Stephan/PycharmProjects/LottZahlenGeneratorLoop/main.py", line 55, in outPutCount
for x in range(valCount):
NameError: name 'valCount' is not defined
Correct behaviour:
User needs to input a number. This number get validated, if it is a digit or a letter. If this is a digit, the lotto/lottery numbers should be created by the count of users input. Otherwise, user is asked to enter number.
My code:
# IMPORTS
import random
from datetime import datetime
import os
# CLEAR CONSOLE
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If Machine is running on Windows, use cls
command = 'cls'
os.system(command)
# VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
mainNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
superNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
mainNumbersLotto = mainNumbers
del mainNumbersLotto[49] # löscht die 49. Stelle von mainnumbers, da Lotto 6aus49 nur Zahlen von 1-49 existieren
global valCount
# countToCreate = input("Bitte geben sie die Anzahl zum generieren an.")
# FUNCTION EUROJACKPOT GENERATOR
def eurojackpotFunc():
global eurojackpotOutput
RandomMainNumbers = str(sorted(random.sample(mainNumbers, 5)))
RandomSuperNumbers = str(sorted(random.sample(superNumbers, 2)))
eurojackpotOutput = "\nEurojackpot\n5 aus 50: " + RandomMainNumbers + "\nEurozahlen: " + RandomSuperNumbers
print(eurojackpotOutput)
# FUNCTION Lotto6aus49 GENERATOR
def lottoNumbersFunc():
global lottoNumbersOutput
RandomLottoNumber = str(sorted(random.sample(mainNumbersLotto, 6)))
lottoNumbersOutput = "\nLotto6aus49\n6 aus 49: " + RandomLottoNumber
print(lottoNumbersOutput)
# FUNCTION GENERATE TEXTFILE WITH RESULT
def generateTxtFile():
f = open("Lottozahle" + "- " + dateFormat + ".txt", "+w")
f.write(eurojackpotOutput + "\n " + lottoNumbersOutput)
def check_user_input(input):
try:
# Convert it into integer
valCount = int(input)
print("Input is an integer number. Number = ", valCount)
outPutCount()
except ValueError:
try:
# Convert it into float
valCount = float(input)
print("Input is a float number. Number = ", valCount)
userCountInputFunc()
except ValueError:
print("No.. input is not a number. It's a string")
userCountInputFunc()
def userCountInputFunc():
global userCountInput
userCountInput = input("Bitte die Anzahl zu erzeugender Lottoscheine angeben: ")
#
def outPutCount():
# LOOP FOR GENERATING COUNT
global valCount
xCount = 0
for x in range(valCount):
xCount = xCount + 1
print("\n#################")
print(xCount, ". Generation")
eurojackpotFunc()
lottoNumbersFunc()
generateTxtFile()
valCount = str(valCount)
print("\nEs wurden erfolgreich " + valCount + " Lottoscheine generiert.")
userCountInputFunc()
check_user_input(userCountInput)
The error message shows NameError: name 'valCount' is not defined (within your loop), and from the looks of it, you're attempting to define it twice– within outPutCount and in the true global scope. As an aside, no matter where you use the keyword global, it will always belong to the global scope.
Anyways, this is the problem with global variables (especially ones that have no value assigned to them before run-time)– figuring out their value while letting various areas in the code mutate them is a self-induced headache worth avoiding.
Try passing the value you want into the function by way of its arguments. You can implement this entire program without the usage of a global variable.
Hope that helps, and keep learning!

Python, print colored duplicates found in 2 list

I'm 63 and just started with Python (My first steps with Udemy).
I'm Croatian so this is croatian language in program but you will understand when you run a program. I know it can be cleaner, shorter, more elegant etc, but as I mentioned before - I'm beginner.
import random
jedan = random.sample(range(1,99),15)
dva = random.sample(range(1,99),15)
def raspaljot(jedan, dva, i):
for x in jedan:
for y in dva:
if y == x:
index1 = jedan.index(x)
index1_str = str(index1)
index2 = dva.index(y)
index2_str = str(index2)
i += 1
x = str(x)
print(" Broj \033[31m" + x + "\033[0m,je dupli i nalazi se u listi jedan: na poziciji: \033[34m"
+ index1_str + "\033[0m a u listi dva na poziciji: \033[35m"+ index2_str + "\033[0m")
print()
print(jedan)
print(dva)
if i != 0:
print("\n *** Ukupno ima ", i, 'duplih brojeva. ***')
elif i == 0:
print("Nema duplih brojeva. :) ")
i = 0
raspaljot(jedan, dva,i)
What program do is finding duplicates in 2 random lists, them print duplicates in color and detecting position inside list[1] and list[2].
What I trying to do is printing list1 and list2 but showing duplicates in color.
For example:
[14, 78, 85, 31, 5, 54, 13, 46, 83, 4, 35, 41, 52, 51, 32]
[72, 40, 67, 85, 54, 76, 77, 39, 51, 36, 91, 70, 71, 38, 55]
here we have 3 duplicates (85,54,51). This above example on the console End was printed in white color, but I wanna these 3 numbers in red color in those two lines above.
Is this possible? I couldn't find a solution.
PS. Wing Pro version 7 on Fedora 33 Workstation / In WIngIde colors are only displayed in an external console and not the Debug I/O tool. :)
Simple solution would be something like this:
# Change list to string
jedan_str = str(jedan)
# Create set with numbers that need new color
num_set = {"85", "54", "51"}
# Iterate over every number and wrap it with color change
for i in num_set:
# Note that I used f-string to format string
# But you can also do this as "\033[31m" + i + "\033[0m"
jedan_str = jedan_str.replace("85", f"\033[31m{i}\033[0m")
# Print string that represent list
print(jedan_str)
Following the idea of using a set to determine which elements are in both lists (as Cv4niak proposed in his answer), I created a function to print the output as you desire. There are numerous other ways of achieving it, but I think this is a simple yet effective way.
The idea is to use the cprint() function from the termcolor package. You can install it with pip install termcolor, and then print normally all elements, except the ones that are duplicates, which will be printed using cprint(item, "red").
The "{:0>2d}" formatting in each ìtem print serves only to pad the number with zeros (so 2 will be printed as 02, for example), in order for the output of both lists to be aligned.
import random
from termcolor import cprint
def mark_duplicates(first, second):
duplicates = list(set(first).intersection(second))
if duplicates:
for list_ in [first, second]:
print("[", end="")
for item in list_:
if item in duplicates:
cprint("{:0>2d}".format(item), "red", end=",")
else:
print("{:0>2d}".format(item), end=",")
print("\b]")
else:
print("No duplicates.")
jedan = random.sample(range(1, 99), 15)
dva = random.sample(range(1, 99), 15)
mark_duplicates(jedan, dva)
With this, if there are no duplicates, the No duplicates. string will be printed. Also you can change the color with not much effort, and use other nice functionalities from termcolor package.

Is there a way to convert a list of integers to a single variable?

I'd like to convert a list of integers to a singe variable.
I tried this (found on another question):
r = len(message) -1
res = 0
for n in message:
res += n * 10 ** r
r -= 1
This does not work for me at all.
I basically need this:
message = [17, 71, 34, 83, 81]
(This can vary in length as I use a variable to change each one)
To convert into this:
new_message = 1771348381
A combination of join, map and str will do.
message = [17, 71, 34, 83, 81]
new_message = int(''.join(map(str, message)))
# 1771348381

checking range of number and writing a value in a new column in pandas dataframe

I need to iterate over column 'movies_rated', check the value against the conditions, and write a value in a newly create column 'expert_level'. When I test on a subset of data, it works. But when I run it against my whole dateset, it only gets filled with value 1.
for num in df_merge['movies_rated']:
if num in range(20,31):
df_merge['expert_level'] = 1
elif num in range(31,53):
df_merge['expert_level'] = 2
elif num in range(53,99):
df_merge['expert_level'] = 3
elif num in range(99,202):
df_merge['expert_level'] = 4
else:
df_merge['expert_level'] = 5
here's a sample dataframe.
movies = [88,20,35,55,1203,99,2222,847]
name = ['angie','chris','pine','benedict','alice','spock','tony','xena']
df = pd.DataFrame(movies,name,columns=['movies_rated'])
certainly there's a less verbose way of doing this?
You could build an IntervalIndex and then apply pd.cut. I'm sure this is a duplicate, but I can't find one right now which uses both closed='left' and .codes, though I'm sure it exists.
bins = pd.IntervalIndex.from_breaks([0, 20, 31, 53, 99, 202, np.inf], closed='left')
df["expert_level"] = pd.cut(movies, bins).codes
which gives me
In [242]: bins
Out[242]:
IntervalIndex([[0.0, 20.0), [20.0, 31.0), [31.0, 53.0), [53.0, 99.0), [99.0, 202.0), [202.0, inf)]
closed='left',
dtype='interval[float64]')
and
In [243]: df
Out[243]:
movies_rated expert_level
angie 88 3
chris 20 1
pine 35 2
benedict 55 3
alice 1203 5
spock 99 4
tony 2222 5
xena 847 5
Note that I've set this up so that scores below 20 get a 0 value, so they can be distinguished from really high rankings. If you really want everything outside the bins to get 5, it'd be straightforward to remap 0 to 5, or just pass breaks of [20, 31, 53, 99, 202] and then map anything with a code of -1 (which means 'not binned') to 5.
I think np.select with the pandas function between is a good choice for you:
conds = [df.movies_rated.between(20,30), df.movies_rated.between(31,52),
df.movies_rated.between(53,98), df.movies_rated.between(99,202)]
choices = [1,2,3,4]
df['expert_level'] = np.select(conds,choices, 5)
>>> df
movies_rated expert_level
angie 88 3
chris 20 1
pine 35 2
benedict 55 3
alice 1203 5
spock 99 4
tony 2222 5
xena 847 5
you could do it with apply and a function:
def expert_level_check(num):
if 20<= num < 31:
return 1
elif 31<= num < 53:
return 2
elif 53<= num < 99:
return 3
elif 99<= num < 202:
return 4
else:
return 5
df['expert_level'] = df['movies_rated'].apply(expert_level_check)
it is slower to manually iterate over a df, I recommend reading this

Resources