Issue reading file containing Unicode chars using JavaProperties gem - ruby

I have mobile automation code in Ruby with locale property files and code is using JavaProperties::Properties.new(filename with path) which is returning hash and we are reading property value by providing property name.
Recently fr_CA.properties file was updated with unicode chars, something like "Solde du dernier relev\u00E9". After the update, I'm getting value "Solde du dernier relevé" instead of "Solde du dernier relevé".
I need some help how/where to provide UTF-8 conversion type.
Quick help highly appreciated.
#filePaths={
:pathTo_some_JavaProperties => #resourcesPath+"/service_"+locale+""+platform_fileName+".properties",
:pathTo_locale_other_JavaProperties => #resourcesPath+"/MoblClient_XmlService"+locale+".properties"
// more file paths
}
begin
#someHash = JavaProperties::Properties.new(#filePaths.fetch(:pathTo_some_JavaProperties))
rescue Errno::ENOENT
filesNotFound << #filePaths.fetch(:pathTo_some_JavaProperties)
end
// Reading value as #someHash['propName'] which is giving output as "Solde du dernier relevé"

Ok, here's what I am getting:
In test.properties:
item1 = Solde du dernier relev\u00E9
Then in Ruby,
> JavaProperties.load('test.properties')[:item1]
# => "item1 Solde du dernier relevé"
You should try getting your problematic code as stripped as possible, and then see if you keep getting the error.
BTW, I think you should use JavaProperties.load, not JavaProperties.new as in your sample.

Related

Angular i18n $localize - template literal with expressions

I am having so much trouble getting this syntax to translate - Angular 13.0.02 .
My two resources are:
https://angular.io/api/localize/init/$localize
https://lokalise.com/blog/angular-i18n/
As per the Angular docs:
Naming placeholders
If the template literal string contains expressions, then the expressions will be automatically associated with placeholder names for you.
For example:
$localize `Hi ${name}! There are ${items.length} items.`;
will generate a message-source of Hi {$PH}! There are {$PH_1} items.`
And providing meaning, descrip, and ID:
$localize`:meaning|description##id:source message text`;
$localize`:meaning|:source message text`;
$localize`:description:source message text`;
$localize`:##id:source message text`;
This example from lokalise.com works:
const company = "Google";
const created_by = $localize`Created by ${company}`;
in my XLIF translation file:
<trans-unit id="3990133897753911565" datatype="html">
<source>Created by <x id="PH"/></source>
<target>Creado por... <x id="PH"/></target>
</trans-unit>
This DOESN'T WQRK:
Yet when I try to reproduce the same syntax with another i18 term - it DOESN'T WORK. It only pulls the English phrase, not the Spanish one.
const company = "Google";
const createdByCompany = $localize`Created by this person ${company}`;
<trans-unit id="spanishTest123" datatype="html">
<source>Created by this person <x id="PH"/></source>
<target>Creado por esta persona <x id="PH"/></target>
</trans-unit>
FYI: for the example that does work, if I REMOVE id="3990133897753911565", then it does NOT pull that translation. So clearly this id makes it happen - yet in my 2nd example I cannot get it to work.
*** UPDATE ***
Using the Angular extract tool produces the XLF file in the required xml format (it parses all i18n tags in your html temples, and the $localize calls in your component code). Run in your app's root dir as follows ng extract-i18n --output-path src/locale - then check the messages.xlf file in the locale folder.
So as per the docs, the "pre-pending it with a colon" syntax did work - https://angular.io/api/localize/init/$localize
const msg = $localize`:Password Reset Modal|Min num of chars##passwordNumChars:Must be at least ${setting.SettingValue}:minLen: characters long.`;
Notice how I updated the trans-unit "id" attrib in the xlf - i.e. my custom ID is "passwordNumChars".
<trans-unit id="passwordNumChars" datatype="html">
<source>Must be at least <x id="minLen" equiv-text="setting.SettingValue"/> characters long.</source>
<target>Debe contener al menos <x id="minLen" equiv-text="setting.SettingValue"/> caracteres.</target>
<note priority="1" from="meaning">password edit modal</note>
</trans-unit>
One final note: if you have the $localize function setup in your ts code - but you can't figure out the xlf format - you can use ng extract-i18n --output-path src/locale from a cmd line to generate the appropriate xlf file.
Then just copy/paste the section you need into your locale file; also perhaps into whatever translation software you're using as the source of truth (i.e. poedit.com to store all i18n terms).

How to insert records into a table using Sequel

This is my code to insert a few lines in my simple "series" table:
db = sequel.postgres(config['dbname'],:user=>config['user'],:password=>config['password'],:host=>config['host'],:port=>config['port'],:max_connections=>10)
#db.create_table? 'series' do
primary_key "series_id" , :autoincrement=>true
String "series_name"
end
seriesDS = db['series']
seriesDS.insert('series_name' => 'test_value')
At seriesDS.insert I get a
Sequel::DatabaseError - PG::SyntaxError: ERREUR: erreur de syntaxe sur ou près de « series »
I didn't manage to get the full SQL query for analysys in STDOUT. It's strange because I added this:
logger = Logger.new STDOUT
logger.level = Logger::DEBUG
db.loggers << logger
It appears to be generating the wrong SQL, but I have no clue to the error's source.
I'm using:
Ruby 2.2.5
Sequel 4.4.1
Postgresql 9.6
The program is launched using ruby -E utf8.
Sequel uses Ruby symbols to represent SQL identifiers. At the very least, you must use seriesDS = db[:series].
Other cases where you want an SQL identifier you should probably switch from using strings to symbols.

No such file or directory - ruby

I am trying to read the contents of the file from a local disk as follows :
content = File.read("C:\abc.rb","r")
when I execute the rb file I get an exception as Error: No such file or directory .What am I missing in this?
In a double quoted string, "\a" is a non-printable bel character. Similar to how "\n" is a newline. (I think these originate from C)
You don't have a file with name "C:<BEL>bc.rb" which is why you get the error.
To fix, use single quotes, where these interpolations don't happen:
content = File.read('C:\abc.rb')
content = File.read("C:\/abc.rb","r")
First of all:
Try using:
Dir.glob(".")
To see what's in the directory (and therefore what directory it's looking at).
open("C:/abc.rb", "rb") { |io| a = a + io.read }
EDIT: Unless you're concatenating files together, you could write it as:
data = File.open("C:/abc.rb", "rb") { |io| io.read }

I always get an UndefinedConversionError in Ruby 2.0 while scraping with Mechanize

When I try to submit a textarea with Mechanize and Ruby 2.0, I always get an
Encoding::UndefinedConversionError: U+0151 from UTF-8 to ISO-8859-1
Then I tryied to convert the text with Iconv, I got a similar result:
Iconv.iconv("LATIN1", "UTF-8", text)
I get this error message:
Iconv::IllegalSequence: "őzködik, melyet "...
As the text contains east-european characters. What can I do to avoid this kind of inconveniences or how can I convert properly between different encodings?
I have found an elegant solution:
replacements = [["À", "À"], ["Á", "Á"], ["Â", "Â"], ["Ã", "Ã"], ["Ä", "Ä"], ["Å", "Å"], ["Æ", "Æ"], ["Ç", "Ç"], ["È", "È"], ["É", "É"], ["Ê", "Ê"], ["Ë", "Ë"], ["Ì", "Ì"], ["Í", "Í"], ["Î", "Î"], ["Ï", "Ï"], ["Ð", "Ð"], ["Ñ", "Ñ"], ["Ò", "Ò"], ["Ó", "Ó"], ["Ô", "Ô"], ["Õ", "Õ"], ["Ö", "Ö"], ["Ø", "Ø"], ["Ù", "Ù"], ["Ú", "Ú"], ["Û", "Û"], ["Ü", "Ü"], ["Ý", "Ý"], ["Þ", "Þ"], ["ß", "ß"], ["à", "à"], ["á", "á"], ["â", "â"], ["ã", "ã"], ["ä", "ä"], ["å", "å"], ["æ", "æ"], ["ç", "ç"], ["è", "è"], ["é", "é"], ["ê", "ê"], ["ë", "ë"], ["ì", "ì"], ["í", "í"], ["î", "î"], ["ï", "ï"], ["ð", "ð"], ["ñ", "ñ"], ["ò", "ò"], ["ó", "ó"], ["ô", "ô"], ["õ", "õ"], ["ö", "ö"], ["ø", "ø"], ["ù", "ù"], ["ú", "ú"], ["û", "û"], ["ü", "ü"], ["ý", "ý"], ["þ", "þ"], ["ÿ", "ÿ"]]
def replace(str,replacements)
replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}
return str
end
my_string=replace(my_string,replacements)

How to use Unix pager programs like `less` from Ruby?

Suppose I have a string called very_long_string whose content I want to send to the standard output. But since the string is very long, I want to use less to display the text on the terminal. When I use
`less #{very_long_string}`
I get File not found error message, and if I use:
`less <<< #{very_long_string}`
I get unexpected redirection error message.
So, how to use less from inside Ruby?
You could open a pipe and feed your string to less via its stdin.
IO.popen("less", "w") { |f| f.puts very_long_string }
(Assuming very_long_string is the variable holding your string.)
See: http://www.ruby-doc.org/core-1.8.7/IO.html#method-c-popen
A simple hack:
require 'tempfile'
f = Tempfile.new('less')
f.write(long_string)
system("less #{f.path}")
Although less can read text files its natural fit is to use it as the last command in a pipe. So a natural fit would be:
shell-command-1 | shell-command-2 | shell-command-3 | less
At your shell prompt:
echo tanto va la gatta al lardo che ci lascia lo zampino|less
..So you can try this in irb:
`echo tanto va la gatta al lardo che ci lascia lo zampino|less`
but I will prefer to use:
your_string = "tanto va la gatta al lardo che ci lascia lo zampino"
`echo "#{your_string}"|less`
If you have time read this SO question.
For a thorough demonstration of using system calls in ruby see this gist:
https://gist.github.com/4069

Resources