This is a follow up question to Programatically writing Java
I am looking at JDT to construct a standalone app (not an eclipse plugin) to programatically write JUnit test classes.
I'd like to know if what I am intending is possible.
Additionally I'd like to know of some tutorials to get me started, the tutorial posted in my last question seems a little to advanced for me.
I found some code that uses the ASTParser standalone. This may help. You will need to add the following jars to your project. I cut and pasted from the .classpath file.
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.osgi_3.6.1.R36x_v20100806.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.core.contenttype_3.4.100.v20100505-1235.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.core.jobs_3.5.1.R36x_v20100824.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.core.resources_3.6.0.R36x_v20100825-0600.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.core.runtime_3.6.0.v20100505.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.equinox.common_3.6.0.v20100503.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.equinox.preferences_3.3.0.v20100503.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.jdt.junit.core_3.6.1.r361_v20100825-0800.jar"/>
<classpathentry kind="lib" path="/Applications/eclipse 3.6/plugins/org.eclipse.jdt.core_3.6.1.xx-20101215-2100-e36.jar"/>
And here is the test code that I found (I cleaned up a few warnings):
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
public class TestAstParser {
public static void main(String args[]){
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource("public class A { int i = 9; \n int j; \n ArrayList<Integer> al = new ArrayList<Integer>();j=1000; }".toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
Set<String> names = new HashSet<String>();
public boolean visit(VariableDeclarationFragment node) {
SimpleName name = node.getName();
this.names.add(name.getIdentifier());
System.out.println("Declaration of '"+name+"' at line"+cu.getLineNumber(name.getStartPosition()));
return false; // do not continue to avoid usage info
}
public boolean visit(SimpleName node) {
if (this.names.contains(node.getIdentifier())) {
System.out.println("Usage of '" + node + "' at line " + cu.getLineNumber(node.getStartPosition()));
}
return true;
}
});
}
}
The original post can be found here: http://www.programcreek.com/2011/01/a-complete-standalone-example-of-astparser/
Related
I am trying to fetch an audio file from MediaStore, extract audio data from it, decode it, and play it, on Android 10.
I am getting the following error when I call setDataSource on my MediaExtractor instance:
Error setting extractor data source, err -10002
To reproduce:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val path = getSong().get(0).path
stringToJNI("file://"+ path)
val URI = Uri.parse(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString() + "/" + getSong().get(0).id)
stringToJNI(URI!!.toString())
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
external fun stringToJNI(URI: String)
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
fun getSong() : MutableList<Songs> {
val SONGS_PROJECTION = arrayOf(
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA
)
val cursor = contentResolver.query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
SONGS_PROJECTION,
null,
null,
MediaStore.Audio.Media._ID +
" ASC LIMIT 100"
)
val items: MutableList<Songs> = mutableListOf()
cursor?.let {
if (cursor.count > 0) {
cursor.moveToFirst()
while (!cursor.isAfterLast) {
val s0 = cursor.getString(cursor.getColumnIndex(SONGS_PROJECTION[0]))
val s1 = cursor.getString(cursor.getColumnIndex(SONGS_PROJECTION[1]))
val s2 = cursor.getString(cursor.getColumnIndex(SONGS_PROJECTION[2]))
items.add(Songs(s0, s1, s2))
cursor.moveToNext()
}
}
cursor.close()
}
return items
}
}
In MainActivity, I pass to native side once the path and second time the URI, each time without luck.
#include <jni.h>
#include <string>
#include <media/NdkMediaExtractor.h>
#include <android/log.h>
#include <bitset>
#define APP_NAME "MediaStoreToNativeAudio"
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, APP_NAME, __VA_ARGS__))
extern "C" JNIEXPORT void JNICALL
Java_com_example_mediastoretonativeaudio_MainActivity_stringToJNI(
JNIEnv *env,
jobject jobj,
jstring URI) {
const char *uri = env->GetStringUTFChars(URI, NULL);
std::string s(uri);
AMediaExtractor *extractor = AMediaExtractor_new();
media_status_t amresult = AMediaExtractor_setDataSource(extractor, uri);
if (amresult != AMEDIA_OK) {
LOGE("AMediaExtractor_setDataSource called with: [%s]", s.c_str());
LOGE("Error setting extractor data source, err %d", amresult);
}
return;
}
from logs:
2019-11-20 01:09:03.519 8270-8270/com.example.mediastoretonativeaudio E/NdkMediaExtractor: can't create http service
2019-11-20 01:09:03.519 8270-8270/com.example.mediastoretonativeaudio E/MediaStoreToNativeAudio: AMediaExtractor_setDataSource called with: [file:///storage/emulated/0/Music/Thank you for the drum machine/01 - Everything Moves.mp3]
2019-11-20 01:09:03.519 8270-8270/com.example.mediastoretonativeaudio E/MediaStoreToNativeAudio: Error setting extractor data source, err -10002
2019-11-20 01:09:03.543 8270-8270/com.example.mediastoretonativeaudio E/NdkMediaExtractor: can't create http service
2019-11-20 01:09:03.543 8270-8270/com.example.mediastoretonativeaudio E/MediaStoreToNativeAudio: AMediaExtractor_setDataSource called with: [content://media/external/audio/media/472]
2019-11-20 01:09:03.543 8270-8270/com.example.mediastoretonativeaudio E/MediaStoreToNativeAudio: Error setting extractor data source, err -10002
My manifest:
After installing app I also give permission through settings.
Edit:
A public repository with test code: https://github.com/AndrewBloom/MediaStoreToNativeAudioSample
the same behaviour results using:
android:requestLegacyExternalStorage="true"
This to me seems a bug on Android 10. It seems that android:requestLegacyExternalStorage="true" does not change the situation. You may have to request on manifest and ask same permission at runtime. The AMediaExtractor_setDataSource function must be called on a thread that is attached to Java. Doing all of that correctly will allow you to make it work on other versions of Android but not on Android 10. I've reported the issue on Android Bug Tracker here: https://issuetracker.google.com/144837266 As per google answer, it seems that all the app using native libraries that require file access through path can be affected and they know the issue https://www.youtube.com/watch?v=UnJ3amzJM94 .
A workaround in my case was to use AMediaExtractor_setDataSourceFd, getting the file descriptor at Java level through contentResolver and its method openFileDescriptor.
bool guess( string aNumberString );
i got this in header file in x.h but how do you define that in the class .
I don't know How to do that !!
By the way I am using c++ !!!
bool x::guess(string aNumberString)
{
// Defination
};
I need to extract the amplitudes of a wav file and want to do it as a simple commandline app. What's an easy way to do that? Cross-platform would be great. Needs to at least work on windows.
You can download an audio file for testing from soundcloud (or from https://dl.dropboxusercontent.com/u/313647/hosted/one_pos_to_neg_crossing.wav until soundcloud processes it).
Some libraries for potential use:
.NET
NAudio
Python
scipy.io.wavfile
pydub
PySoundFile
friture
snack
Here is a solution I came up with using Accord.NET:
public IEnumerable<float> AmplitudesFromFile(string fileName)
{
Accord.Audio.Formats.WaveDecoder sourceDecoder = new Accord.Audio.Formats.WaveDecoder(fileName);
Signal sourceSignal = sourceDecoder.Decode();
for (int i = 0; i < sourceSignal.Samples; i++) yield return sourceSignal.GetSample(1, i);
}
Project Page: http://accord-framework.net/
Documentation: http://accord-framework.net/docs/Index.html
Here's the first way I figured out how to do it with NAudio.
Output
>SoundToAmplitudes.exe w:\materials\audio\one_pos_to_neg_crossing.wav
0.04284668
-0.005615234
-0.1177368
Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
namespace SoundToAmplitudes {
class Program {
private static int Main(string[] args) {
#if DEBUG
Console.WriteLine(String.Join(", ", args));
args = new[] { #"W:\materials\audio\one_pos_to_neg_crossing.wav" };
#endif
return Cli(args);
}
static int Cli(string[] args) {
string fileName = args[0];
var soundFile = new FileInfo(fileName);
foreach (float s in AmplitudesFromFile(soundFile)) {
Console.WriteLine(s);
}
//Console.WriteLine();
#if DEBUG
Console.Read();
#endif
return 0;
}
public static IEnumerable<float> AmplitudesFromFile(FileInfo soundFile) {
var reader = new AudioFileReader(soundFile.FullName);
int count = 4096; // arbitrary
float[] buffer = new float[count];
int offset = 0;
int numRead = 0;
while ((numRead = reader.Read(buffer, offset, count)) > 0) {
foreach (float amp in buffer.Take(numRead)) {
yield return amp;
}
}
}
}
}
Here's one way to do it in python (using scipy), although I assume that the wav file is 16-bit.
Output
W:\>python amplitudes.py w:\materials\audio\one_pos_to_neg_crossing.wav
0.0428479873043
-0.00561540574358
-0.117740409558
Code
"""Usage:
amplitudes WAV_FILE
Returns the (linear) amplitude of the signal inside the wav file, sample by sample.
"""
from __future__ import division
import docopt
import scipy.io.wavfile
MAX_WAV16_AMP = 32767 # = 2**15-1 # because wav16 is signed (wav8 isn't)
def main():
args = docopt.docopt(__doc__)
one_pos_to_neg_crossing_path = r"W:\materials\audio\one_pos_to_neg_crossing.wav"
if False: args['WAV_FILE'] = one_pos_to_neg_crossing_path
rate, amp_arr = scipy.io.wavfile.read(args['WAV_FILE'])
for amp in (amp_arr / MAX_WAV16_AMP):
print amp
if __name__ == '__main__':
main()
See also
Reading *.wav files in Python
Extracting an amplitude list from *.wav file for use in Python
Using C# and Visual Studio 2010, how can I make a grayscaled emf from a colored one? Should I enumerate records and change color settings somehow?
As a result I want to have a new emf image.
Here is an open source emf read/write utility. I don't think it can be done with GDI+ and preserve the vector content. So this hopefully will help you, but I haven't remotely tested all possible emf cases.
https://wmf.codeplex.com/
this works for both wmf and emf formats. We can combine the Oxage.Wmf strategy with the strategy from the other post which essentially re-colors a pen or brush when it is created so that anything drawn with that pen or brush should be gray.
using Oxage.Wmf;
using Oxage.Wmf.Records;
using Oxage.Wmf.Objects;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetafileTest
{
public class GrayMap
{
public void GrayFile(string sourceFile, string destFile){
WmfDocument wmf = new WmfDocument();
wmf.Load(sourceFile);
foreach (var record in wmf.Records)
{
if (record is WmfCreateBrushIndirectRecord)
{
var brush = record as WmfCreateBrushIndirectRecord;
brush.Color = Gray(brush.Color);
}
else if (record is WmfCreatePenIndirectRecord)
{
var pen = record as WmfCreatePenIndirectRecord;
pen.Color = Gray(pen.Color);
}
else if (record is WmfCreatePalette) {
var pal = record as WmfCreatePalette;
foreach (PaletteEntry entry in pal.Palette.PaletteEntries) {
Color test = Color.FromArgb(entry.Red, entry.Green, entry.Blue);
Color grayTest = Gray(test);
entry.Red = grayTest.R;
entry.Green = grayTest.G;
entry.Blue = grayTest.B;
}
}
}
wmf.Save(destFile);
}
public Color Gray(Color original) {
int r = (int)(original.R*0.2989);
int g = (int)(original.G*0.5870);
int b = (int)(original.B*0.1140);
Color result = Color.FromArgb(r, g, b);
return result;
}
}
}
This was tested with the following super simple case of filling a blue rectangle, so for at least the simple cases this will work. It may not be able to handle all cases, but in such a case you can probably extend the original source to suite your needs since it is open source.
private void button1_Click(object sender, EventArgs e)
{
var wmf = new WmfDocument();
wmf.Width = 1000;
wmf.Height = 1000;
wmf.Format.Unit = 288;
wmf.AddPolyFillMode(PolyFillMode.WINDING);
wmf.AddCreateBrushIndirect(Color.Blue, BrushStyle.BS_SOLID);
wmf.AddSelectObject(0);
wmf.AddCreatePenIndirect(Color.Black, PenStyle.PS_SOLID, 1);
wmf.AddSelectObject(1);
wmf.AddRectangle(100, 100, 800, 800);
wmf.AddDeleteObject(0);
wmf.AddDeleteObject(1);
wmf.Save("D:\\test.emf");
}
private void button2_Click(object sender, EventArgs e)
{
GrayMap map = new GrayMap();
map.GrayFile("D:\\test.emf", "D:\\test2.emf");
}
I am parsing xml from remote server using kxml parser. I am using the following code to parse xml
public void validateUser(String name, String password, String mobile, String code)
{
Display.getDisplay(parent).setCurrent(new LoadingBarCanvas(parent));
ReadXML xmlThread = new ReadXML();
xmlThread.start();
int count = 0;
URL = "http://www.acb.info/mobapp/Web_service/checkLogin.php?mobile=" + mobile + "&userId=dbz&password=123&code=" + code + "&output=xml";
while (xmlThread.isAlive())
{
if (count == 0)
{
System.out.println("thread is alive");
}
count++;
}
StringBuffer sb = new StringBuffer();
System.out.println("bookVector " + bookVector.size());
for (int i = 0; i < bookVector.size(); i++) {
ChapterClass book = (ChapterClass) bookVector.elementAt(i);
sb.append("\n");
sb.append("Name : ");
sb.append(book.getName());
status = book.getName();
sb.append("\n");
sb.append("Descrition : ");
sb.append(book.getDescription());
smcID = book.getDescription();
userName.setString(book.getRating());
//=book.getRating();
sb.append("\n");
}
System.out.println(sb.toString());
if (status.equalsIgnoreCase("Sucess.."))
{
StoreData("smcid",smcID);
StoreData("userid",userName.getString());
showInputLogInSuccessfull();
}
else
{
showInputLogInFailed();
}
}
I want to show loading Form from another class while xml is parsing. I have tried Display.getDisplay(parent).setCurrent(new LoadingBarCanvas(parent)); to display loading form but it don't show the loading Form. So how can I solve this problem ?
you can use the GIF file for loading screen
Here you can find the sample code
if u r using the Netbeans then
Go to library->Add Netbeans MIDP compaonent
U'll get the class of netbeans.splachscreen,netbeans.waitingsceen
Which u can use and integrate in ur code