Unexpected error reading GML graph - python-3.4

I have downloaded the gml file which contains the dolphins social network.
Some time ago I did some analysis on that network running python 3.4 and networkx 1.9 on a a Windows7 machine, but now I am running on a Arch linux machine (with the same version of python but with networkx 1.10) and found an issue when tried to read the file.
This is the code used to read the file:
import networkx as nx
nx.read_gml("dolphins.gml")
And this is the stack trace of the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in read_gml
File "/usr/lib/python3.4/site-packages/networkx/utils/decorators.py",line 220, in _open_file
result = func(*new_args, **kwargs)
File "/usr/lib/python3.4/site-packages/networkx/readwrite/gml.py", line 210, in read_gml
G = parse_gml_lines(filter_lines(path), label, destringizer)
File "/usr/lib/python3.4/site-packages/networkx/readwrite/gml.py", line 383, in parse_gml_lines
graph = parse_graph()
File "/usr/lib/python3.4/site-packages/networkx/readwrite/gml.py", line 372, in parse_graph
curr_token, dct = parse_kv(next(tokens))
File "/usr/lib/python3.4/site-packages/networkx/readwrite/gml.py", line 323, in tokenize
(line[pos:], lineno + 1, pos + 1))
networkx.exception.NetworkXError: cannot tokenize 'graph' at (1, 1)
Are you able to read the file? Someone has experienced a simmilar issue? or knows what is generating the error?
Thank you in advance!

In the newer versions of networkx, the gml file should follow a more specific format. The problem with the dolphins.gml is that there should not be any carriage return before the open square brackets. For example:
Wrong format:
graph
[
directed 0
node
[
id 0
label "Beak"
]
.
.
.
Correct format:
graph [
directed 0
node [
id 0
label "Beak"
]
.
.
.
It does not care about how many spaces there are before the square bracket as long as there is more than one and there is no carriage return.
What I ended up doing was using regular expression to get rid of the white spaces before the opening square brackets. The following regex worked for me:
\s+\[
and just replace it with " [". There has to be at least one space before the bracket.
Also keep in mind that every node has to have a unique label.
Hope it helped.

It worked by downgrading the networkx version from 1.10 to 1.9.1.
Hope this answer can help someone else.

Related

Functions work when in a Sage worksheet directly but not when in a library

I'm taking a class, Intro to Algebraic Cryptology. We're using Sage for everything and CoCalc. This class is the first I've heard of either. The instructor has provided many convenience functions for our use. I do not like repeatedly copying them into new Sage worksheets in CoCalc. So, I put them in a library.
It took some time but I finally learned that to use them I have to do this in Sage:
load_attach_path('/path/to/the/directory')
%attach elliptic_curve_common.sage
Now, there is a function which she wrote for us to use called HPSonEC. This function is about using the Hellman-Pohlig-Silver exploit for cracking encryption on elliptic curves. What's infuriating is that the function will not work when used as I have above and I get this error:
Error in lines 5-5
Traceback (most recent call last):
File "/cocalc/lib/python3.8/site-packages/smc_sagews/sage_server.py", line 1230, in execute
exec(
File "", line 1, in <module>
File "<string>", line 298, in HPSonEC
File "<string>", line 263, in listptorder
File "<string>", line 151, in ECTimes
File "sage/rings/rational.pyx", line 2401, in sage.rings.rational.Rational.__mul__ (build/cythonized/sage/rings/rational.c:20911)
return coercion_model.bin_op(left, right, operator.mul)
File "sage/structure/coerce.pyx", line 1248, in sage.structure.coerce.CoercionModel.bin_op (build/cythonized/sage/structure/coerce.c:11304)
raise bin_op_exception(op, x, y)
TypeError: unsupported operand parent(s) for *: 'Rational Field' and 'Abelian group of points on Elliptic Curve defined by y^2 = x^3 + 389787687398479 over Finite Field of size 324638246338947256483756487461'
However, if I take that function, and the others on which it depends, and copy them into my Sage worksheet, they work just fine. Literally, no differences in the code at all. What may be the issue?
When reading code from a worksheet or a .sage file,
the Sage preparser is applied.
When reading code from a .py file, it is not.
See many questions where this came up:
https://stackoverflow.com/search?q=%5Bsage%5D+preparser
https://ask.sagemath.org/questions/scope:all/sort:activity-desc/page:1/query:preparser/

TypeError: string indices must be integers on ArangoDB

Arango module gives a weird error while accessing databases:
from arango import ArangoClient
client = ArangoClient(hosts='http://localhost:8529/')
sys_db = client.db('_system', username='root', password='root')
sys_db.databases()
below is the error:
Traceback (most recent call last): File "", line 1, in
File
"/home/ubuntu/arangovenv/lib/python3.6/site-packages/arango/database.py",
line 699, in databases
return self._execute(request, response_handler) File "/home/ubuntu/arangovenv/lib/python3.6/site-packages/arango/api.py",
line 66, in _execute
return self._executor.execute(request, response_handler) File "/home/ubuntu/arangovenv/lib/python3.6/site-packages/arango/executor.py",
line 82, in execute
return response_handler(resp) File "/home/ubuntu/arangovenv/lib/python3.6/site-packages/arango/database.py",
line 697, in response_handler
return resp.body['result'] TypeError: string indices must be integers
calling database module from "packages/arango/database.py" giving me the same error.
my env:
1) ubuntu 16.4
2) python-arango==5.2.1
any help appreciated.
If you are running it on some server, it may be a server issue. It was in my case at least. I ran the following to clear the proxy and it worked fine.
export http_proxy=''
As I guessed, resp.body is not the data type that you provided. line 697 of database.py is expecting something else. For example:
>>> data = "MyName"
>>> print(data[0])
'M'
>>> print(data['anything'])
TypeError: string indices must be integers
First print command gives the result while seconds command throws the error.
I hope this might solve your problem.

Unix.error 31 write when using Functory module

I am using the functory module and I am facing a very bizarre issue with the code.
My code is working fine and I have been able to parallelized a play on my game but when I try to play once again (launch another time a parallelized function) it raises a really weird error.
Here you can find the error :
Fatal error: exception Unix.Unix_error(43, "write", "")
Raised by primitive operation at file "unix.ml", line 252, characters 7-34
Called from file "protocol.ml", line 45, characters 10-32
Re-raised at file "network.ml", line 536, characters 10-11
Called from file "network.ml", line 565, characters 47-80
Called from file "list.ml", line 73, characters 12-15
Called from file "network.ml", line 731, characters 4-27
Called from file "map_fold.ml", line 98, characters 4-242
Called from file "game_ia.ml", line 111, characters 10-54
Called from file "gameplay.ml", line 34, characters 12-48
Called from file "gameplay.ml", line 57, characters 22-37
Called from file "gameplay.ml", line 85, characters 5-22
So I've decided to search in the following folders to see what primitive operation has been raised :
(unix.ml) external rename : string -> string -> unit = "unix_rename"
(network.ml) Some jid when w.state <> Disconnected -> send w (Protocol.Master.Kill jid)
So for some reason, it seems that my worker disconnects by itself. I was wondering if any of you already had this issue and what to do in order to solve it ?
You can find my game here. The main files involved are game_ia.ml (best_move_parallelized) and gameplay.ml (at the very bottom).
Thank you in advance for your help.
The error you get is (type the following in the toploop)¹:
# (Obj.magic 43: Unix.error);;
- : Unix.error = Unix.EPROTOTYPE
which means: Protocol wrong type for socket. So you have to examine how you initialize your socket.
¹ You can also count the exceptions in unix.mli, knowing that the first one, E2BIG, is 0. Emacs C-u 43 ↓ helps.

Steps to load a .txt file and convert the strings in it to usable data in a Sage notebook

I am on a Mac with OS 10.11.6, and I'm learning the notebook interface for Sage 7.2. As a start, in a Sage worksheet I created a .txt file containing the string [1, 2, 3] and saved it. I can open the text file directly and verify its contents just by clicking on it, but I can't yet do this in Sage.
I'd like to be able to open it and convert the string to a usable Sage object. I'd appreciate explicit instructions, assuming nothing at all about my Sage background. Thank you.
Note: The procedure to do what I just asked in the Sage documentation under "Saving and Loading Individual Objects" doesn't work in my environment (specs above.) I do A = [1, 2, 3]. Then I do save(A, 'A') and Sage returns a hot link for A.sobj. Then I hit the save-and-quit button. Then I hit "sign out." Then I sign back in and go to the worksheet where I did the steps I just described. I do A = load('A'). This is what Sage says:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_3.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("QSA9IGxvYWQoJ0EnKQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
File "", line 1, in <module>
File "/private/var/folders/7n/t9k4hfyn44s2qp7wxt479kn80000gn/T/tmpEa1OkK/___code___.py", line 2, in <module>
exec compile(u"A = load('A')" + '\n', '', 'single')
File "", line 1, in <module>
File "sage/structure/sage_object.pyx", line 1032, in sage.structure.sage_object.load (build/cythonized/sage/structure/sage_object.c:11594)
IOError: [Errno 2] No such file or directory: 'A.sobj'`
I found an answer in Finch's book. First a quote:
“We used a module called os from the Python standard library module to help us write code that can run on multiple platforms. A text file must have a special character to denote the end of each line in the file. Unfortunately, for historical reasons, each family of operating systems (Mac, Windows, and UNIX) uses a different end-of-line character. The os module has a constant called linesep that contains the correct character for the platform that the code is run on. We used the statement import os to make the module available, and accessed the constant using the syntax os.linesep. We also used the function os.path.join to join the path to the file name with the correct character for the current operating system.”
Excerpt From: Craig Finch. “Sage Beginner's Guide.”
Example using a file named "File2.txt" containing a single text character, '1':
import os path='/Users/barrybrent/.sage/sage_notebook.sagenb/home/store/2/21/212/2123/admin/19/data/' fileName='File2.txt' times = [] text_file = open(os.path.join(path, fileName), 'r') line = text_file.readline()
(Comment: is just a character string. To convert it a Sage object useful in computations:)
elements=line.split(',') times.append(float(elements[0].strip()))
(Comment: evaluate:)
times[0]
(Comment: Sage says"1.0". Now can we do arithmetic with times[0]?)
times[0]+1
Sage says "2.0"

How to overcome Python 3.4 NameError: name 'basestring' is not defined

I've got a file called hello.txt in the local directory along side the test.py, which contains this Python 3.4 code:
import easywebdav
webdav = easywebdav.connect('192.168.1.6', username='myUser', password='myPasswd', protocol='http', port=80)
srcDir = "myDir"
webdav.mkdir(srcDir)
webdav.upload("hello.txt", srcDir)
When I run this I get this:
Traceback (most recent call last):
File "./test.py", line 196, in <module>
webdav.upload("hello.txt", srcDir)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/easywebdav/client.py", line 153, in upload
if isinstance(local_path_or_fileobj, basestring):
NameError: name 'basestring' is not defined
Googling this results in several hits, all of which point to the same fix which, in case the paths moved in future, is to include "right after import types":
try:
unicode = unicode
except NameError:
# 'unicode' is undefined, must be Python 3
str = str
unicode = str
bytes = bytes
basestring = (str,bytes)
else:
# 'unicode' exists, must be Python 2
str = str
unicode = unicode
bytes = str
basestring = basestring
I wasn't using import types, but to include it or not doesn't appear to make a difference in PyDev - I get an error either way. The line which causes an error is:
unicode = unicode
saying, 'undefined variable'.
OK my python knowledge falters at this point and I've looked for similar posts on this site and not found one specific enough to basestring that I understand to help. I know I need to specify basestring but I don't know how to. Would anyone be charitable enough to point me in the right direction?
You can change easywebdav's client.py file like the top two changes in this checkin: https://github.com/hhaderer/easywebdav/commit/983ced508751788434c97b43586a68101eaee67b
The changes consist in replacing basestring by str in client.py.
I came up with an elegant pattern that does not require modification of any source files. Please note it might be extended for other modules to keep all 'hacks' in one place:
# py3ports.py
import easywebdav.client
easywebdav.basestring = str
easywebdav.client.basestring = str
# mylib.py
from py3ports import easywebdav

Resources