Why does Windows have issues with the encoding, but Linux doesn't? - windows

For my toy project mpu I have two CI solutions running:
Travis / Linux: Works
Azure / Windows: Fails
It fails with this message:
_______________________________ test_read_json ________________________________
def test_read_json():
path = "files/example.json"
source = pkg_resources.resource_filename(__name__, path)
data_real = read(source)
data_exp = {
"a list": [1, 42, 3.141, 1337, "help", "�"],
"a string": "bla",
"another dict": {"foo": "bar", "key": "value", "the answer": 42},
}
> assert data_real == data_exp
E AssertionError: assert {'a list': [1... answer': 42}} == {'a list': [1... answer': 42}}
E Omitting 2 identical items, use -vv to show
E Differing items:
E {'a list': [1, 42, 3.141, 1337, 'help', '€']} != {'a list': [1, 42, 3.141, 1337, 'help', '�']}
E Use -v to get the full diff
tests\test_io.py:175: AssertionError
Why can it read the € sign from the JSON, but within the test it fails? (Python 3.6)

I assume that the read function which is used in the test wraps open in some way or another.
TL;DR Try adding encoding='utf8' to the call to open.
From my experience, Windows does not always play nice with non-ascii characters when reading files unless the encoding is set explicitly.
Also, it does not help that the default value for encoding is platform-dependent:
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent (whatever locale.getpreferredencoding() returns),
but any text encoding supported by Python can be used. See the codecs
module for the list of supported encodings.
some tests (ran on Win 10, Python 3.7, locale.getpreferredencoding() returns cp1262):
test.csv
€
with open('test.csv') as f:
print(f.read())
# €
with open('test.csv', encoding='utf8') as f:
print(f.read())
# '€'

Related

Sphinx-autodoc with napoleon (Google Doc String Style): Warnings and Errors about Block quotes and indention

I am using Sphinx 4.4.0 with napoleon extension (Google Doc String). I have this two problems
ARNING: Block quote ends without a blank line; unexpected unindent.
ERROR: Unexpected indentation.
I found something about it on the internet but can not fit this two my code. My problem is I even do not understand the messages. I do not see where the problem could be.
This is the code:
def read_and_validate_csv(basename, specs_and_rules):
"""Read a CSV file with respect to specifications about format and
rules about valid values.
Hints: Do not use objects of type type (e.g. str instead of "str") when
specificing the column type.
specs_and_rules = {
'TEMPLATES': {
'T1l': ('Int16', [-9, ' '])
},
'ColumnA': 'str',
'ColumnB': ('str', 'no answer'),
'ColumnC': None,
'ColumnD': (
'Int16',
-9, {
'len': [1, 2, (4-8)],
'val': [0, 1, (3-9)]
}
}
Returns:
(pandas.DataFrame): Result.
"""
This are the original messages:
.../bandas.py:docstring of buhtzology.bandas.read_and_validate_csv:11: WARNING: Block quote ends without a blank line; unexpected unindent.
.../bandas.py:docstring of buhtzology.bandas.read_and_validate_csv:15: ERROR: Unexpected indentation.
.../bandas.py:docstring of buhtzology.bandas.read_and_validate_csv:17: ERROR: Unexpected indentation.
.../bandas.py:docstring of buhtzology.bandas.read_and_validate_csv:19: WARNING: Block quote ends without a blank line; unexpected unindent.
.../bandas.py:docstring of buhtzology.bandas.read_and_validate_csv:20: WARNING: Block quote ends without a blank line; unexpected unindent.
reStructuredText is not Markdown, and indentation alone is not enough to demarcate the code block. reStructuredText calls this a literal block. Although the use of :: is one option, you might want to explicitly specify the language (overriding the default) with the use of the code-block directive.
Also I noticed that you have invalid syntax in your code block—a missing ) and extra spaces in your indentation—which could have caused those errors.
Try this.
def read_and_validate_csv(basename, specs_and_rules):
"""Read a CSV file with respect to specifications about format and
rules about valid values.
Hints: Do not use objects of type type (e.g. str instead of "str") when
specificing the column type.
.. code-block:: python
specs_and_rules = {
'TEMPLATES': {
'T1l': ('Int16', [-9, ' '])
},
'ColumnA': 'str',
'ColumnB': ('str', 'no answer'),
'ColumnC': None,
'ColumnD': (
'Int16',
-9, {
'len': [1, 2, (4-8)],
'val': [0, 1, (3-9)]
}
)
}
Returns:
(pandas.DataFrame): Result.
"""

Trying to get all paths in a YAML file

I've got an input YAML file (test.yml) as follows:
# sample set of lines
foo:
x: 12
y: hello world
ip_range['initial']: 1.2.3.4
ip_range[]: tba
array['first']: Cluster1
array2[]: bar
The source contains square brackets for some keys (possibly empty).
I'm trying to get a line by line list of all the paths in the file, ideally like:
foo.x: 12
foo.y: hello world
foo.ip_range['initial']: 1.2.3.4
foo.ip_range[]: tba
foo.array['first']: Cluster1
array2[]: bar
I've used the yamlpaths library and the yaml-paths CLI, but can't get the desired output. Trying this:
yaml-paths -m -s =foo -K test.yml
outputs:
foo.x
foo.y
foo.ip_range\[\'initial\'\]
foo.ip_range\[\]
foo.array\[\'first\'\]
Each path is on one line, but the output has all the escape characters ( \ ). Modifying the call to remove the -m option ("expand matching parent nodes") fixes that problem but the output is then not one path per line:
yaml-paths -s =foo -K test.yml
gives:
foo: {"x": 12, "y": "hello world", "ip_range['initial']": "1.2.3.4", "ip_range[]": "tba", "array['first']": "Cluster1"}
Any ideas how I can get the one line per path entry but without the escape chars? I was wondering if there is anything for path querying in the ruamel modules?
Your "paths" are nothing more than the joined string representation of the keys (and probably indices) of the
mappings (and potentially sequences) in your YAML document.
That can be trivially generated from data loaded from YAML with a recursive function:
import sys
import ruamel.yaml
yaml_str = """\
# sample set of lines
foo:
x: 12
y: hello world
ip_range['initial']: 1.2.3.4
ip_range[]: tba
array['first']: Cluster1
array2[]: bar
"""
def pathify(d, p=None, paths=None, joinchar='.'):
if p is None:
paths = {}
pathify(d, "", paths, joinchar=joinchar)
return paths
pn = p
if p != "":
pn += '.'
if isinstance(d, dict):
for k in d:
v = d[k]
pathify(v, pn + k, paths, joinchar=joinchar)
elif isinstance(d, list):
for idx, e in enumerate(d):
pathify(e, pn + str(idx), paths, joinchar=joinchar)
else:
paths[p] = d
yaml = ruamel.yaml.YAML(typ='safe')
paths = pathify(yaml.load(yaml_str))
for p, v in paths.items():
print(f'{p} -> {v}')
which gives:
foo.x -> 12
foo.y -> hello world
foo.ip_range['initial'] -> 1.2.3.4
foo.ip_range[] -> tba
foo.array['first'] -> Cluster1
array2[] -> bar
While Anthon's answer certainly produces the output you were after, I think your question was specifically about how to get the yaml-paths command to produce the desired output. I'll address that original question.
As of version 3.5.0, the yamlpath project's yaml-paths command supports a --noescape option which removes the escape symbols from output. Using your input file and the new option, you may find this output more to your liking:
$ yaml-paths --nofile --expand --keynames --noescape --values --search='=~/.*/' test.yml
foo.x: 12
foo.y: hello world
foo.ip_range['initial']: 1.2.3.4
foo.ip_range[]: tba
foo.array['first']: Cluster1
array2[]: bar
Note:
Using the --values option includes the value with each YAML Path.
For interest, I changed the --search expression to match every node in the input file rather than only the "foo" data.
The default output (without setting --noescape) produces YAML Paths which can be used as direct input into other YAML Path parsers and processors; setting --noescape changes this to render human-friendly paths which may not work as downstream YAML Path input.
Disclaimer: I am the author of the yamlpath project. Should you ever run into issues or have questions about it, please visit the project's GitHub project site and engage me via Issues (bugs and feature requests) or Discussions (questions). Thank you!

Cannot read unicode .csv into R

I have a .csv file, which contains the following data:
"Ա","Բ"
1,10
2,20
I cannot read it into R so that the column names are displayed like they are in the file.
d <- read.csv("./Data/1.csv", fileEncoding="UTF-8")
head(d)
Produces the following:
> d <- read.csv("./Data/1.csv", fileEncoding="UTF-8")
Warning messages:
1: In read.table(file = file, header = header, sep = sep, quote = quote, :
invalid input found on input connection './Data/1.csv'
2: In read.table(file = file, header = header, sep = sep, quote = quote, :
incomplete final line found by readTableHeader on './Data/1.csv'
> head(d)
[1] X.
<0 rows> (or 0-length row.names)
Meanwhile, doing the same without specifying the fileEncoding produces this:
> d <- read.csv("./Data/1.csv")
> head(d)
Ô. Ô²
1 1 10
2 2 20
When I run the "file" utility to find out the encoding of the file, it says it is UTF-8:
Data\1.csv: UTF-8 Unicode text, with CRLF line terminators
I am using RStudio, Windows 7, R version 2.15.2, 32-bit.
Thanks in advance.
I wrote a longer answer on the same issue here: R on Windows: character encoding hell .
Quick answer, using the parameter encoding instead of fileEncoding should fix your first issue. You will not be able to read it possibly in either console or table view in RStudio, but you will be able to use it in formulaes.
d <- read.csv("./Data/1.csv", encoding="UTF-8")
head(d)
Having saved your table into a UTF-8 file:
> test2 <- read.csv("test2.csv", header = FALSE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "", encoding = "UTF-8")
Warning message:
In read.table(file = file, header = header, sep = sep, quote = quote, :
incomplete final line found by readTableHeader on 'test2.csv'
This gives you how it looks like in the console and RStudio view
> test2
V1 V2
1 <U+0531> <U+0532>
2 1 10
3 2 20
However importantly you are able to manipulate this within R. Thus in my case it is possible to see that the script window input Ա has UTF-8 encoding, and a grep correctly finds this encoding in your table.
> Encoding("Ա")
[1] "UTF-8"
> grep("Ա", as.character(test2[1,1]))
[1] 1
You may need to find suitable encoding variants that work on your settings, or possibly change them. Unfortunately I am not sure where it is done.
You might not be able to make it pretty in all stages, but it is definitely possible to get it to work also in Windows 7 environment.
I tried two ways to replicate your problem.
I copied the characters above into RStudio, saved it to a csv with this code:
write.csv(c("Ա","Բ",
1,10,
2,20), "test.csv")
df <- read.csv("test.csv")
This worked fine.
Then I thought, well maybe R is cheating when I save it to CSV with R? So I just pasted the characters to a text file and save it as a CSV. This approach doesn't have problems either.
Here's my session info:
sessionInfo()
R version 3.0.1 (2013-05-16)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_CA.UTF-8 LC_NUMERIC=C LC_TIME=en_CA.UTF-8
[4] LC_COLLATE=en_CA.UTF-8 LC_MONETARY=en_CA.UTF-8 LC_MESSAGES=en_CA.UTF-8
[7] LC_PAPER=C LC_NAME=C LC_ADDRESS=C
[10] LC_TELEPHONE=C LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats4 grid stats graphics grDevices utils datasets methods base
other attached packages:
[1] party_1.0-9 modeltools_0.2-21 strucchange_1.4-7 sandwich_2.2-10 zoo_1.7-10
[6] GGally_0.4.4 reshape_0.8.4 plyr_1.8 ggplot2_0.9.3.1
loaded via a namespace (and not attached):
[1] coin_1.0-23 colorspace_1.2-2 dichromat_2.0-0 digest_0.6.3
[5] gtable_0.1.2 labeling_0.2 lattice_0.20-23 MASS_7.3-29
[9] munsell_0.4.2 mvtnorm_0.9-9995 proto_0.3-10 RColorBrewer_1.0-5
[13] reshape2_1.2.2 scales_0.2.3 splines_3.0.1 stringr_0.6.2
I had the same problem and found out that the file was corrupted.
I opened the file with OpenOffice and saved it back using "UTF8" character set (you need to click the edit filter settings box) and then imported it with the read.csv()(no encoding or filencoding option) and it worked fine.

String "<<" operator producing warnings and unexpected result in Ruby1.9.3

Please find the code which I ran from the IRB terminal:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\rakshiar>irb
irb(main):001:0> src = 'E:\WIPData\Ruby\Scripts\TaxDocumentDownload'
=> "E:\\WIPData\\Ruby\\Scripts\\TaxDocumentDownload"
irb(main):002:0> dest = 'E:\WIPData\Ruby\Scripts'
=> "E:\\WIPData\\Ruby\\Scripts"
irb(main):003:0> dest<<'H00371101'
=> "E:\\WIPData\\Ruby\\ScriptsH00371101"
irb(main):004:0>
Why here such \\ is coming? How to fix that?
When i am running the same part from the script getting the below warnings:
CODE
src = 'E:\WIPData\Ruby\Scripts\TaxDocumentDownload'
dest = 'E:\WIPData\Ruby\Scripts'
dest<<'H00371101'
FileUtils.copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
Warning:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\rakshiar>cd..
C:\Documents and Settings>cd..
C:\>e:
E:\>cd E:\WIPData\Ruby\Scripts
E:\WIPData\Ruby\Scripts>downloadv1.rb
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:93: warning: already initialized constant
OPT_TABLE
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1268: warning: already initialized consta
nt S_IF_DOOR
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1496: warning: already initialized consta
nt DIRECTORY_TERM
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1500: warning: already initialized consta
nt SYSCASE
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1619: warning: already initialized consta
nt LOW_METHODS
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1625: warning: already initialized consta
nt METHODS
Could you please say why such warnings are coming?
When try the below from the IRB again different output:
C:\Documents and Settings\rakshiar>irb
irb(main):001:0> src = "E:\WIPData\Ruby\Scripts\TaxDocumentDownload"
=> "E:WIPDataRubyScriptsTaxDocumentDownload"
irb(main):002:0> est = "E:\WIPData\Ruby\Scripts"
=> "E:WIPDataRubyScripts"
irb(main):003:0> est<<"H00371101"
=> "E:WIPDataRubyScriptsH00371101"
irb(main):004:0> est<<"H00371101"
EDIT:
ERROR
E:\WIPData\Ruby\Scripts>downloadv1.rb
E:/WIPData/Ruby/Scripts/downloadv1.rb:87: syntax error, unexpected tCONSTANT, ex
pecting $end
dest<<"H00371101"
^
From the script code part:
src = "E:\WIPData\Ruby\Scripts\TaxDocumentDownload"
dest = "E:\WIPData\Ruby\Scripts\"
dest<<"H00371101"
FileUtils.copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
I want that src and dest directory as the real directory path. How to get that?
Thanks.
Ruby has, broadly speaking, two types of strings. In a double-quoted string, backslashes "escape" characters - a backslash followed by another letter produces a special character. For example, "\n" gives you a newline. Inside single-quoted strings, the backslash doesn't escape characters - '\n' is just a backslash followed by the letter n. (Actually this isn't 100% true, the exception is '\'' which is a single quote - otherwise there would be no way to embed a single quote in a single-quoted string.
That's why your single-quoted src = 'E:\WIPData\Ruby\Scripts\TaxDocumentDownload' will work, and double-quoted src = "E:\WIPData\Ruby\Scripts\TaxDocumentDownload" will not.
The double-backslashes are printed there because irb uses inspect on the resulting output, which returns the string in double-quoted form (with special characters escaped):
'"Hello," said Andy'.inspect # => "\"Hello,\" said Andy"
They're not really in the string, as you can see with puts:
puts '"Hello," said Andy' # => "Hello," said Andy
The error you have is because of using a double-quoted string, the backslashes are treated as escape characters, so your string is unterminated:
src = "E:\WIPData\Ruby\Scripts\"
dest<<"H00371101"
is parsed the same as
src = 'E:WIPDataRubyScripts"dest<<'H00371101
which is a syntax error.
You should go and read about the difference between single- and double-quoted strings. Here's one resource.
A quick google suggests that you might be doing require 'FileUtils' not require 'fileutils'? This post said that the same warnings disappeared once they changed to the latter. It's because Windows' file system is not case-sensitive - to Ruby, FileUtils.rb and fileutils.rb are two different files, but to Windows, they're the same.
The FileUtils warning it is because you have to change your required gem, like this:
require 'FileUtils' WRONG
require 'fileutils' OKAY
This will solve your warnings :)

Checking version of file in Ruby on Windows

Is there a way in Ruby to find the version of a file, specifically a .dll file?
For Windows EXE's and DLL's:
require "Win32API"
FILENAME = "c:/ruby/bin/ruby.exe" #your filename here
s=""
vsize=Win32API.new('version.dll', 'GetFileVersionInfoSize',
['P', 'P'], 'L').call(FILENAME, s)
p vsize
if (vsize > 0)
result = ' '*vsize
Win32API.new('version.dll', 'GetFileVersionInfo',
['P', 'L', 'L', 'P'], 'L').call(FILENAME, 0, vsize, result)
rstring = result.unpack('v*').map{|s| s.chr if s<256}*''
r = /FileVersion..(.*?)\000/.match(rstring)
puts "FileVersion = #{r ? r[1] : '??' }"
else
puts "No Version Info"
end
The 'unpack'+regexp part is a hack, the "proper" way is the VerQueryValue API, but this should work for most files. (probably fails miserably on extended character sets.)
What if you want to get the version info with ruby, but the ruby code isn't running on Windows?
The following does just that (heeding the same extended charset warning):
#!/usr/bin/ruby
s = File.read(ARGV[0])
x = s.match(/F\0i\0l\0e\0V\0e\0r\0s\0i\0o\0n\0*(.*?)\0\0\0/)
if x.class == MatchData
ver=x[1].gsub(/\0/,"")
else
ver="No version"
end
puts ver
As of Ruby 2.0, the DL module is deprecated. Here is an updated version of AShelly's answer, using Fiddle:
version_dll = Fiddle.dlopen('version.dll')
s=''
vsize = Fiddle::Function.new(version_dll['GetFileVersionInfoSize'],
[Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP],
Fiddle::TYPE_LONG).call(filename, s)
raise 'Unable to determine the version number' unless vsize > 0
result = ' '*vsize
Fiddle::Function.new(version_dll['GetFileVersionInfo'],
[Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG,
Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP],
Fiddle::TYPE_VOIDP).call(filename, 0, vsize, result)
rstring = result.unpack('v*').map{|s| s.chr if s<256}*''
r = /FileVersion..(.*?)\000/.match(rstring)
puts r[1]
If you are working on the Microsoft platform, you should be able to use the Win32 API in Ruby to call GetFileVersionInfo(), which will return the information you're looking for.
http://msdn.microsoft.com/en-us/library/ms647003.aspx
For any file, you'd need to discover what format the file is in, and then open the file and read the necessary bytes to find out what version the file is. There is no API or common method to determine a file version in Ruby.
Note that it would be easier if the file version were in the file name.

Resources