Import node and edge CSV using gephi toolkit in java - toolkit

I need to develop a graph using gephi toolkit in Java. I have my node and edge data in CSV format. All the toolkit tutorials have syntax to import a gml or gexf format. Since I have 2 CSV files can anyone tell me the syntax of importing this csv's in Java using gephi toolkit jar?

It's better for you to try to import csv file by gephi-tool-kit and gephi at the same time to see if there is any problem, now I will show you the way I found to import csv file by gephi-toolkit step by step.
Here I use NetBeans IDE 8.2 with the gephi-toolkit-0.9.2-all.jar and refer to several demos from github.
After create a new Java project and a new Java class like here my test class named Transfer95, of course you also need to add the gephi-toolkit jar file to your library. According to the tutorial and javadoc of gephi-toolkit, there is much changes to use the new toolkit, it seems that the import methods can be used to import several different types of file like gexf and csv file.
The first several lines of code are the same common code to init project and get controller or container.
//Init a project - and therefore a workspace
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
pc.newProject();
Workspace workspace = pc.getCurrentWorkspace();
//Get controllers and models
ImportController importController = Lookup.getDefault().lookup(ImportController.class);
//Get models and controllers for this new workspace - will be useful later
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getGraphModel();
//Import file
Container container;
try {
File file_node = new File(getClass().getResource("/resourceason2/club_1_1995.csv").toURI());
container = importController.importFile(file_node);
container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED); //Force DIRECTED
container.getLoader().setAllowAutoNode(true); //create missing nodes
container.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
container.getLoader().setAutoScale(true);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
here I just try to import the node csv file with the same importController method of gexf in demos of ImportExport or HeadlessSimple, and it worked, but here we also need to import edge csv file to the network, and I finally found the answer from demo of GenerateGraph which can append new container to the current workspace, so the code of import csv file after is
//Init a project - and therefore a workspace
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
pc.newProject();
Workspace workspace = pc.getCurrentWorkspace();
//Get controllers and models
ImportController importController = Lookup.getDefault().lookup(ImportController.class);
//Get models and controllers for this new workspace - will be useful later
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getGraphModel();
//Import file
Container container,container2;
try {
File file_node = new File(getClass().getResource("/resourceason2/club_1_1995.csv").toURI());
container = importController.importFile(file_node);
container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED); //Force DIRECTED
container.getLoader().setAllowAutoNode(true); //create missing nodes
container.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
container.getLoader().setAutoScale(true);
File file_edge = new File(getClass().getResource("/resourceason2/transfer_1_1995.csv").toURI());
container2 = importController.importFile(file_edge);
container2.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED); //Force DIRECTED
container2.getLoader().setAllowAutoNode(true); //create missing nodes
container2.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
container2.getLoader().setAutoScale(true);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
here we need to append the new container to the same workspace like
//Append imported data to GraphAPI
importController.process(container, new DefaultProcessor(), workspace);
importController.process(container2, new AppendProcessor(), workspace); //Use AppendProcessor to append to current workspace
and finally check if your network is correct
//See if graph is well imported
DirectedGraph graph = graphModel.getDirectedGraph();
System.out.println("Nodes: " + graph.getNodeCount());
System.out.println("Edges: " + graph.getEdgeCount());
and that's why I advise you to test the csv file import by gephi and gephi-toolkit at the same time. And that's my dummy code,hopefully it will help you and there may be better answer.
References
Javadoc
gephi toolkit demo
gephi forum

Related

Xamarin Forms - How do i use a Premade Local Database? [Solved] [duplicate]

I have started using the Xamarin plugin for Visual Studio to create an Android app.
I have a local SQL database, and I want to call it to display data. I don't see how I can do this. Is it possible?
After thinking this was a trivial thing to do, I was proven wrong when I tried setup a quick test project. This post will contain a full tutorial on setting up a DB for an Android App in Xamarin that will come in handy as a reference for future Xamarin users.
At a glance:
Add Sqlite.cs to your project.
Add your database file as an Asset.
Set your database file to build as an AndroidAsset.
Manually copy the database file out of your apk to another directory.
Open a database connetion using Sqlite.SqliteConnection.
Operate on the database using Sqlite.
Setting up a local database for a Xamarin Android project
1. Add Sqlite.cs to your project.
Start by going to this repository and downloading Sqlite.cs; this provides the Sqlite API that you can use to run queries against your db. Add the file to your project as a source file.
2. Add DB as asset.
Next, get your DB and copy it into the Assets directory of your Android project and then import it into your project so that it appears beneath the Assets folder within your solution:
I'm using the Chinook_Sqlite.sqlite database sample renamed to db.sqlite from this site throughout this example.
3. Set DB to build as AndroidAsset.
Right click on the DB file and set it to build action AndroidAsset. This will ensure that it is included into the assets directory of the APK.
4. Manually copy DB out of your APK.
As the DB is included as an Asset (packaged within the APK) you will need to extract it out.
You can do this with the following code:
string dbName = "db.sqlite";
string dbPath = Path.Combine (Android.OS.Environment.ExternalStorageDirectory.ToString (), dbName);
// Check if your DB has already been extracted.
if (!File.Exists(dbPath))
{
using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(dbName)))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
{
byte[] buffer = new byte[2048];
int len = 0;
while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write (buffer, 0, len);
}
}
}
}
This extracts the DB as a binary file from the APK and places it into the system external storage path. Realistically the DB can go wherever you want, I've just chosen to stick it here.
I also read that Android has a databases folder that will store databases directly; I couldn't get it to work so I've just ran with this method of using an existing DB.
5. Open DB Connection.
Now open a connection to the DB through the Sqlite.SqliteConnection class:
using (var conn = new SQLite.SQLiteConnection(dbPath))
{
// Do stuff here...
}
6. Operate on DB.
Lastly, as Sqlite.net is an ORM, you can operate on the database using your own data types:
public class Album
{
[PrimaryKey, AutoIncrement]
public int AlbumId { get; set; }
public string Title { get; set; }
public int ArtistId { get; set; }
}
// Other code...
using (var conn = new SQLite.SQLiteConnection(dbPath))
{
var cmd = new SQLite.SQLiteCommand (conn);
cmd.CommandText = "select * from Album";
var r = cmd.ExecuteQuery<Album> ();
Console.Write (r);
}
Summary
And that's how to add an existing Sqlite database to your Xamarin solution for Android! For more information check out the examples included with the Sqlite.net library, its unit tests and the examples in the Xamarin documentation.
Here is the one that I'm using and it's working
install the Sqlite plugin
create interface to access different platforms services
create a model for the table
implement the interface that you created earlier on all of the
platform you want to use
use the plugin to create, get, insert, etc on your table
for more detailed information check this

Playing Background Music From Bundled File in Codenameone

I'm trying to have a background sound play in codenameone from an mp3 file that's packaged with the app (beep-07.mp3 is just in the src folder).
I can make it work using MediaManager.createMedia, with code borrowed from this post: How to bundle sounds with Codename One?
But the MediaManager.createBackgroundMedia function only takes in a uri, so I try using MediaManager.createBackgroundMedia("file://beep-07.mp3"); but no sound plays.
Am I doing something wrong in the file string?
The src directory doesn't exist on the device. The files that are there are packaged as resources into the equivalent of a jar. So you need to extract them if you want a URL. Notice this might work with "jar://beep-07.mp3" but I'm not sure.
A more correct approach would be to extract it from the jar on first use then use this URL (the code below assumes static import of the CN class):
String fileName = getAppHomePath() + "beep-07.mp3";
if(!existsInFileSystem(fileName)) {
try(InputStream i = getResourceAsStream("/beep-07.mp3");
OutputStream o = openFileOutputStream(fileName)) {
copy(i, o);
}
}
Media m = MediaManager.createBackgroundMedia(fileName);
FYI since your app is running you don't need background media only foreground media.

Android studio how delete downloaded files parse?

I am new in android studio and I am using Parse to store images. I am creating an image gallery and I am able to display downloaded images from parse to gridview. The problem is everytime I restart the app, my SDcard will download the exact same files from Parse. Is there a way to delete these unnecessary files? Or how can I put these Downloaded image files into a temporary storage where they will be deleted once the user is finished with the app?
This is my code for downloading the images and store them in gridview:
for (ParseObject imageOb : objects) {
final ParseFile file = (ParseFile) imageOb.get("image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Uri uri = getImageUri(getApplicationContext(), bitmap);
File imageFiles = new File(getRealPathFromURI(uri));
imageAdapter.add(imageFiles.toString());
}
imageAdapter.notifyDataSetChanged();
}
});
}
There are some answers already on Stack overflow about temporary files, for example What is the best way to create temporary files
You could also manually delete the downloaded files when the application doesn't need them anymore. If you download them in onCreate you should delete them in onDestroy. Otherwise, check out this Article about the Android lifecycle

Intelligent Agents using Jade framework

I want to develop a multi-agent system and I want to run different agents from different containers. I'm using eclipse with Jade framework for this and i have no idea how to configure the "run configuration" for the project in order to accomplish this. So far I have this: -gui -container main:Sender;a1:Receiver;a2:Pong and I want to put agents a1 and a2 in a separate container. Please help.
When starting a new jade project I usually create a Coordinator agent with the methods to launch and destroy other agents. I think this is good practice as you can extend these methods to other agents if need be.
I hope that this will help.
First Run the Agent jade graphical user interface (Ejade) (By Installing the Ejade Library)
or you can run it on the console:
C:\java jade.Boot -gui (You have to fix the system variable path to "C:\..\jade.far" and create a variable name classpath = "C:\..\jdk7\")
Run the code that allows you to create a new container to deploy on it your agents.
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.domain.ams;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
public class ContainerDeploy {
public static void main(String[] args) {
try{
Runtime runtime=Runtime.instance();
ProfileImpl profileImpl = new ProfileImpl(false);
profileImpl.setParameter(ProfileImpl.MAIN_HOST, "localhost");
AgentContainer agentContainer=runtime.createAgentContainer(profileImpl);
AgentController agentcontroller1 = agentContainer.createNewAgent("Name of Agent", "com.package.AgentClass", new Object[]{});
agentController1.start();
}catch(Exception e) {
System.out.println("Runtime Error\t");
e.printStackTrace();
}
}
}

Silverlight: Business Application Needs Access To Files To Print and Move

I have the following requirement for a business application:
(All of this could be on local or server)
Allow user to select folder location
Show contents of folder
Print selected items from folder (*.pdf)
Display which files have been printed
Potentially move printed files to new location (sub-folder of printed)
How can I make this happen in Silverlight?
Kind regards,
ribald
First of all, all but the last item can be done (the way you expect). Due to security protocols, silverlight cannot access the user's drive and manipulate it. The closest you can get is accessing silverlight's application storage which will be of no help to you whatsoever in this case. I will highlight how to do the first 4 items.
Allow user to select folder location & Show contents of folder
public void OnSelectPDF(object sender)
{
//create the open file dialog
OpenFileDialog ofg = new OpenFileDialog();
//filter to show only pdf files
ofg.Filter = "PDF Files|*.pdf";
ofg.ShowDialog();
byte[] _import_file = new byte[0];
//once a file is selected proceed
if (!object.ReferenceEquals(ofg.File, null))
{
try
{
fs = ofg.File.OpenRead();
_import_file = new byte[fs.Length];
fs.Read(_import_file, 0, (int)fs.Length);
}
catch (Exception ex)
{
}
finally
{
if (!object.ReferenceEquals(fs, null))
fs.Close();
}
//do stuff with file - such as upload the file to the server
};
}
If you noticed, in my example, once the file is retrieved, i suggest uploading it to a webserver or somewhere with temporary public access. I would recommend doing this via a web service. E.g
//configure the system file (customn class)
TSystemFile objFile = new TNetworkFile().Initialize();
//get the file description from the Open File Dialog (ofg)
objFile.Description = ofg.File.Extension.Contains(".") ? ofg.File.Extension : "." + ofg.File.Extension;
objFile.FileData = _import_file;
objFile.FileName = ofg.File.Name;
//upload the file
MasterService.ToolingInterface.UploadTemporaryFileAsync(objFile);
Once this file is uploaded, on the async result, most likely returning the temporary file name and upload location, I would foward the call to some javascript method in the browser for it to use the generic "download.aspx?fileName=givenFileName" technique to force a download on the users system which would take care of both saving to a new location and printing. Which is what your are seeking.
Example of the javascript technique (remember to include System.Windows.Browser):
public void OnInvokeDownload(string _destination)
{
//call the browser method/jquery method
//(I use constants to centralize the names of the respective browser methods)
try
{
HtmlWindow window = HtmlPage.Window;
//where BM_INVOKE_DOWNLOAD is something like "invokeDownload"
window.Invoke(Constants.TBrowserMethods.BM_INVOKE_DOWNLOAD, new object[] { _destination});
}
catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
}
Ensure you have the javascript method existing either in an included javaScript file or in the same hosting page as your silverlight app. E.g:
function invokeDownload(_destination) {
//some fancy jquery or just the traditional document.location change here
//open a popup window to http://www.myurl.com/downloads/download.aspx? fileName=_destination
}
The code for download.aspx is outside the scope of my answer, as it varies per need and would just lengthen this post (A LOT MORE). But from what I've given, it will "work" for what you're looking for, but maybe not in exactly the way you expected. However, remember that this is primarily due to silverlight restrictions. What this approach does is rather than forcing you to need a pluging to view pdf files in your app, it allows the user computer to play it's part by using the existing adobe pdf reader. In silverlight, most printing, at least to my knowledge is done my using what you call and "ImageVisual" which is a UIElement. To print a pdf directly from silverlight, you need to either be viewing that PDF in a silverlight control, or ask a web service to render the PDF as an image and then place that image in a control. Only then could you print directly. I presented this approach as a lot more clean and direct approach.
One note - with the temp directory, i would recommend doing a clean up by some timespan of the files on the server side everytime a file is being added. Saves you the work of running some task periodically to check the folder and remove old files. ;)

Resources