Program that uses jpbc takes a long time - java

This is a very simple program I have written that uses jpbc library.
It compiles without any errors, but takes an unusually long time to show the output, or in fact it doesn't show the output at all. (Who in this era will have the patience to wait for nearly half an hour for such a tiny program?) I am using a system with i7 processor but still this is the case.
Could anyone tell what might be wrong with this code?
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.*;
import it.unisa.dia.gas.jpbc.PairingParametersGenerator;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.plaf.jpbc.pairing.a1.TypeA1CurveGenerator;
public class PairingDemo {
public static void main(String [] args){
try{
int rBits = 160;
int qBits = 512;
PairingParametersGenerator pg = new TypeA1CurveGenerator(rBits, qBits);
PairingParameters params = pg.generate();
Pairing pair = PairingFactory.getPairing("D:\\JPBCLib\\params\\curves\\a1.Properties");
Field Zr = pair.getZr();
int degree = pair.getDegree();
System.out.println("Degree of the pairing : " + degree);
}catch(Exception e){
e.printStackTrace();
}
}
}

There are three issues that you're dealing with here
Generating the pairing parameters takes some time, but this only has to be done once for a system that you're building. You should store the generated pairing parameter for later use.
Since you're not using pg or params, you can remove that code. Instead you're reading precomputed parameters from a file.
jPBC is a complete and pure Java implementation of PBC. It is fully portable and therefore quite slow. jPBC has an option of using a PBCWrapper library which is a wrapper around libpbc which would enable you to get the performance of the native library. I wasn't able to make it work on Windows, but Linux should not be an issue (make sure to check the JNI version or load your own).

Related

Is there a way to take a bunch of images and turn them into an mp4 file in java?

I am currentrly working on a Way to visualize Fractals in Java. The mathematics behind it work perfectly fine and I am very happy with how the Pics turn out. Now i want to take these Images and turn them into a Video. I've written a Java Program that produces any number of Pictures and saves them (alphabetically) in a new directory. Now I need a way for Java to convert these Images into a Video.
I know there are solutions such as ffmpeg, however I need this process to be repeatable, so I don't think a Command Line Application would be the best Option.
Is there any Way to implement such a function into Java directly ?
If you're willing to use a third party library and the platform is supported (Windows or Linux, 64bit). You can use Pilecv4j (Full disclosure, I'm the main committer).
There's a test checked in that does exactly this. You can find it here: TestSplitIntoFiles.java
Here is the pertinent function that does this with the minor difference that it's not reading the image file names from the contents on the disk:
private static void encodeFiles(final File imageDir, final long numFrames, final File outputVideo) throws IOException {
try(final CvMat firstFrame = ImageFile.readMatFromFile(new File(imageDir, "image-0.jpg").getAbsolutePath());
final EncodingContext ectx = Ffmpeg2.createEncoder()
.outputStream(outputVideo.getAbsolutePath())
.openVideoEncoder("libx264", "vidEncoder")
.addCodecOptions("preset", "slow")
.addCodecOptions("crf", "40")
.enable(firstFrame, false)
;) {
final VideoEncoder ve = ectx.getVideoEncoder("vidEncoder");
ectx.ready();
LongStream.range(0, numFrames)
.mapToObj(fn -> new File(imageDir, "image-" + fn + ".jpg").getAbsolutePath())
.forEach(frameFile -> {
try(CvMat mat = uncheck(() -> ImageFile.readMatFromFile(frameFile));) {
ve.encode(mat, false);
}
});
}
}
If you decide to give it a try, let me know if you run into any issues. You can use the Issues on GitHub. I've been using it professionally for a while.
Also, see the answer to this question: Read a mp4 and write to anther mp4 creates bigger size

How to crash my OS programatically?

Have written a Java code which sends mail when whole system RAM reaches > 95%.
I want to write a Java code to test this scenario. Have written few(recursive etc...), but those are crashing the JVM but not System.
Any help please ?
UN_ORTHODOX SOLUTION but it works anyway
NOTE! I Used WINDOWS 8.1 host machine
I found this DOC on myself too! in old days; about JVM and host system access issues. I used this code to get details about host system!
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
private static void printUsage() {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get")
&& Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = e;
} // try
System.out.println(method.getName() + " = " + value);
} // if
} // for
}
NOTE !
that's not the real way To do but I did it by opening the Default browser (in most of cases I know most of the time its GOOGLE CHROME) , had 8GB ram those days so opening a few tabs with some random youtube and other links it helped me to reach up the memory usage unto 90% in no time! because it eats the RAM (No offence to CHROME people!) doing that I was able to achieve the test you are trying to get. :-)
TO Open a default browser just take a look on this thread its quite nice with different ways to do it!
well if you are using it for android well read about proguard rules for memory management and try using any external library which takes up too much memory like any dummy faceRecog library or simply just accessing some NDK features or so check this link for more

Optimize Random Forest parameters in weka?

I am trying to optimize random forest parameters using weka, the java class is as the following:
package pkg10foldcrossvalidation;
import weka.core.*;
import weka.classifiers.meta.*;
import weka.classifiers.trees.RandomForest;
import java.io.*;
public class RF_Optimizer {
public static void main(String[] args) throws Exception {
// load data
BufferedReader reader = new BufferedReader(new FileReader("C:\\Prediction Results on the testing set\\Dataset.arff"));
Instances data = new Instances(reader);
reader.close();
data.setClassIndex(data.numAttributes() - 1);
// setup classifier
CVParameterSelection ps = new CVParameterSelection();
ps.setClassifier(new RandomForest());
ps.setNumFolds(10); // using 10-fold CV
ps.addCVParameter("C 0.1 0.5 5");
// build and output best options
ps.buildClassifier(data);
System.out.println(Utils.joinOptions(ps.getBestClassifierOptions()));
}
}
But I am facing difficulty of understanding which parameters should replace the "C" and how the range of each one could be determined? And is it workable to use .addCVParameter several times for several parameters at the same time?
I tried to search for some youtube or website tutorials that explain how to change random forest parameters in java but nothing found.
Thank you
I think what you are describing, -C are the Cross-Validation parameters, not the RandomForest parameters.
Can't you just use the Explorer GUI, open a sample dataset such as glass.arff, and then right-click on the bold RandomForest string at the top of the window, then from the context menu choose "copy configuration to clipboard", and then paste that string into your java code?
After doing this right now, I've copied this string to the clipboard:
weka.classifiers.trees.RandomForest -P 100 -I 100 -num-slots 1 -K 0 -M 1.0 -V 0.001 -S 1
These are the default parameters for Weka's RandomForest learner. What these parameters mean, and which of them is most suitable for optimization, and which range of values to use for optimization I really can't tell. Most likely a very important parameter is numIterations, the -I parameter. Maybe vary it from 100, 200,... to 1000 and plot numIterations vs Accuracy, and check if the curve has smoothed out already.

Using/Reading FMOD (.fsb) Files in Java

Heyo Everyone. I am currently working on an Application which should play music files from an FMOD Database. It currently does it by Extracting the files (using a runtime and an external programm called "fsbextract.exe" (link)) as MP3 and then playing them. I am okay with this as it is, but i would now also love to edit/replace the files within the .fsb file. So my question is: Can i somehow directly acces the MP3 files in there without extracting them? I searched the internet for something like this but couldn't find any help.
For reference, here are some informations i can get from within fsbextract:
FileID is |FSB4> | Version is 4.0 | Number of Entries 7412
Global Flags:
0x40 | FMOD_FSB_SOURCE_MPEG_PADDED4 | MPEG frames are aligned to the nearest 4 bytes, 16 bytes for multichannel (Use Frame Verification option)
And from the first (index 0) file within the fsb file:
Format: MP3 (85)
Sample rate: 44100Hz
Channels: Mono
Duration: 01.541
Bitrate: 160,62 kbit/s
Bits/Sample 3.64
Sample Mode Flags [0x10000200]
0x200 | FSOUND_MPEG | Sample is stored in MPEG format
0x10000000 | FSOUND_MPEG_LAYER3 | Samples are stored in MPEG Layer 3 format
I hope someone knows more than me, but thanks in advance
Marenthyu
Jérôme Jouvie wrote a JNI wrapper for FMOD 4+, NativeFmodEx. If your FSB files are not encrypted I think you can use the API to extract streaming data from the FSB banks.
I tried to write my own wrapper as well but I didn't have the time to get past a simple proof of concept.
UPDATE: Sure. So basically what I did was to use JNAerator to wrap the native FMODex libraries and then targeting the resulting glue code to the BridJ runtime environment. That essentially allows you to invoke the native FMOD C library.
I'm not exactly sure if Jerome did something similar or if he created his own JNI stubs to achieve the same result. You'd have to check out and read his project's code.
But essentially, once you're able to make FMOD calls inside your application, you can use the API to do as you please. If you download the latest FMOD studio or FMODex SDK's from the FMOD web site you'll find a help .chm file which contains some documentation for the API.
You should also take a look at the examples in the SDK.
The following code is basically one example translated into Java, using the above mentioned strategy. The code isn't portable, robust or actually useful for an application. It really needs cleanup yet it still illustrates the point.
Like I said, you should be much better off using Jerome's SDK port.
Hope it helps.
package net.unsungstories.fmodex;
import net.unsungstories.fmodex.FmodexLibrary.FMOD_CHANNEL;
import net.unsungstories.fmodex.FmodexLibrary.FMOD_SOUND;
import net.unsungstories.fmodex.FmodexLibrary.FMOD_SYSTEM;
import org.apache.log4j.Logger;
import org.bridj.IntValuedEnum;
import org.bridj.Platform;
import org.bridj.Pointer;
import org.junit.Test;
import static org.bridj.Pointer.*;
import static net.unsungstories.fmodex.FmodexLibrary.*;
import static com.google.common.base.Throwables.*;
import static java.lang.String.format;
public class PlaySound {
private static final Logger log = Logger.getLogger(PlaySound.class);
#Test
public void playSound() {
log.info("Test started...");
String soundPath = "./src/test/resources/picus_get_to_finicular_music_0.fsb";
Platform.addEmbeddedLibraryResourceRoot("net/unsungstories/fmodex/");
IntValuedEnum<FMOD_RESULT> result;
Pointer<Pointer<FMOD_SYSTEM>> ppSystem = allocatePointer(FMOD_SYSTEM.class);
Pointer<Pointer<FMOD_SOUND>> ppSound1 = allocatePointer(FMOD_SOUND.class);
Pointer<Integer> pSubSounds = allocateInt();
Pointer<Pointer<FMOD_CHANNEL>> ppChannel = allocatePointer(FMOD_CHANNEL.class);
#SuppressWarnings("unchecked")
Pointer<FMOD_CREATESOUNDEXINFO> soundExInfo = Pointer.NULL;
Pointer<Byte> targetSoundPath = allocateBytes(soundPath.length() + 1);
targetSoundPath.setCString(soundPath);
result = FMOD_System_Create(ppSystem);
result = FMOD_System_Init(ppSystem.get(), 2, FmodexLibrary.FMOD_INIT_NORMAL, Pointer.NULL);
result = FMOD_System_CreateSound(ppSystem.get(), targetSoundPath, FMOD_HARDWARE, soundExInfo, ppSound1);
result = FMOD_Sound_GetNumSubSounds(ppSound1.get(), pSubSounds);
try {
Pointer<Integer> pChanelPlaying = allocateInt();
for (int k = 0; k < pSubSounds.get(); k++) {
Pointer<Pointer<FMOD_SOUND>> ppSubSound = allocatePointer(FMOD_SOUND.class);
result = FMOD_Sound_GetSubSound(ppSound1.get(), k, ppSubSound);
result = FMOD_System_PlaySound(ppSystem.get(), FMOD_CHANNELINDEX.FMOD_CHANNEL_FREE, ppSubSound.get(), 0, ppChannel);
FMOD_Channel_IsPlaying(ppChannel.get(), pChanelPlaying);
while (ppChannel.getBoolean()) {
log.info("Playing...");
Thread.sleep(1000);
FMOD_Channel_IsPlaying(ppChannel.get(), pChanelPlaying);
}
result = FMOD_Sound_Release(ppSubSound.get());
}
result = FMOD_System_Close(ppSystem.get());
result = FMOD_System_Release(ppSystem.get());
} catch (Exception e) {
log.error(getStackTraceAsString(getRootCause(e)));
}
log.info(format("Finished... %s", result));
}
}
Hope this helps.

Running Calabash XML From Code

I downloaded Calabash XML a couple of days back and got it working easily enough from the command prompt. I then tried to run it from Java code I noticed there was no API (e.g. the Calabash main method is massive with code calls to everywhere). To get it working was very messy as I had to copy huge chunks from the main method to a wrapper class, and divert from the System.out to a byte array output stream (and eventually into a String) i.e.
...
ByteArrayOutputStream baos = new ByteArrayOutputStream (); // declare at top
...
WritableDocument wd = null;
if (uri != null) {
URI furi = new URI(uri);
String filename = furi.getPath();
FileOutputStream outfile = new FileOutputStream(filename);
wd = new WritableDocument(runtime,filename,serial,outfile);
} else {
wd = new WritableDocument(runtime,uri,serial, baos); // new "baos" parameter
}
The performance seems really, really slow e.g. i ran a simple filter 1000 times ...
<p:filter>
<p:with-option name="select" select="'/result/meta-data/neighbors/document/title'" />
</p:filter>
On average each time took 17ms which doesn't seem like much but my spring REST controller with calls to Mongo DB and encryption calls etc take on average 3/4 ms.
Has anyone encountered this when running Calabash from code? Is there something I can do to speed things up?
For example, I this is being called each time -
XProcRuntime runtime = new XProcRuntime(config);
Can this be created once and reused? Any help is appreciated as I don't want to have to pay money to use Calamet but really want to get Xproc working from code to an acceptable performance.
For examples on how you could integrate XMLCalabash in a framework, I can mention Servlex by Florent Georges. You'd have to browse the code to find the relevant bit, but last time I looked it shouldn't be too hard to find:
http://servlex.net/
XMLCalabash wasn't build for speed unfortunately. I am sure that if you run profile, and can find some hotspots, Norm Walsh would be interested to hear about it.
Alternative is to look into Quixprox, which is derived from XMLCalabash:
https://code.google.com/p/quixproc/
I am also very sure that if you can send Norm a patch to improve the main class for better integration, he'd be interested to hear about it. In fact, the code should be on github, just fork it, fix it, and do a pull request..
HTH!

Categories