Converting JAPE Rule to UIMA RUTA - uima

Is there any example available to explain how the JAVA code written in RHS part of the JAPE rule can be converted in the UIMA RUTA? Also is there any way to get features of the annotations in RUTA?

Is your question if you can inject annotations (found by other systems) into RUTA before starting the RUTA analysis? So, if that's the question the answer is "yes, that's possible".
You can do something like this:
private static createCASAnnotation(Cas cas, MyOwnAnnotation myOwnAnnotation) {
Type annotationType = cas.getTypeSystem().getType(myOwnAnnotation.getType());
if (annotationType != null) {
AnnotationFS casAnnotation = cas.createAnnotation(annotationType, myOwnAnnotation.getTextStart(), myOwnAnnotation.getTextEnd());
// Also possible to add features / child annotations
for (MyOwnAnnotation childAnnotation : myOwnAnnotation.getChildAnnotations()) {
String featureFullName = casAnnotation.getType().getName() + ":" + childAnnotation.getName();
Feature feature = casAnnotation.getCAS().getTypeSystem().getFeatureByFullName(featureFullName);
if (feature != null && feature.getRange().isPrimitive()
&& "uima.cas.String".equalsIgnoreCase(feature.getRange().getName())) {
casAnnotation.setStringValue(feature, childAnnotation.getText());
// Other options for example "uima.cas.Integer" -> casAnnotation.setIntValue(...
}
// if not primitive you can also add Annotation type:
// AnnotationFS childCASAnnotation = createCASAnnotation(...
// casAnnotation.setFeatureValue(feature, childCASAnnotation);
}
cas.addFsToIndexes(casAnnotation);
} else {
log.error("invalid type .... or something better");
// Or throw exception
}
}
The MyOwnAnnotation is an object from your own domain/system and can be something like:
class MyAnnotation {
private final String value; // or text or fragment ...??
private final Long startIndex;
private final Long endIndex; // or use size/length
private final List<MyAnnotation> childAnnotations;
// constructor, builder pattern?, getters ....
}
Code examples are for demonstrating the concept.

Related

What is it that should be done here?

I have been following this tutorial to come up with a simple source code editor. (The feature that I want the most is keyword highlighting.) What I do not understand is the last part:
class Scanner extends RuleBasedScanner {
public Scanner() {
WordRule rule = new WordRule(new IWordDetector() {
public boolean isWordStart(char c) {
return Character.isJavaIdentifierStart(c);
}
public boolean isWordPart(char c) {
return Character.isJavaIdentifierPart(c);
}
});
Token keyword = new Token(new TextAttribute(Editor.KEYWORD, null, SWT.BOLD));
Token comment = new Token(new TextAttribute(Editor.COMMENT));
Token string = new Token(new TextAttribute(Editor.STRING));
//add tokens for each reserved word
for (int n = 0; n < Parser.KEYWORDS.length; n++) {
rule.addWord(Parser.KEYWORDS[n], keyword);
}
setRules(new IRule[] {
rule,
new SingleLineRule("#", null, comment),
new SingleLineRule("\"", "\"", string, '\\'),
new SingleLineRule("'", "'", string, '\\'),
new WhitespaceRule(new IWhitespaceDetector() {
public boolean isWhitespace(char c) {
return Character.isWhitespace(c);
}
}),
});
}
}
The instruction is as follows:
For each of the keywords in our little language, we define a word entry in our WordRule. We pass our keyword detector, together with rules for recognizing comments, strings, and white spaces to the scanner. With this simple set of rules, the scanner can segment a stream of bytes into sections and then use the underlying rules to color the sections.
Shed me some light please? I do not know what it is I have to do to set the desired keywords..

What is the alternative for String.format() in GWT?

While GWT is not emulate all java's core, what can be used as alternative for:
String.format("The answer is - %d", 42)?
What is the ellegant and efficient pattern to inject arguments to message in GWT?
One elegant solution is using SafeHtml templates. You can define multiple such templates in an interface like:
public interface MyTemplates extends SafeHtmlTemplates {
#Template("The answer is - {0}")
SafeHtml answer(int value);
#Template("...")
...
}
And then use them:
public static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class);
...
Label label = new Label(TEMPLATES.answer(42));
While this is a little bit more work to set up, it has the enormous advantage that arguments are automatically HTML-escaped. For more info, see https://developers.google.com/web-toolkit/doc/latest/DevGuideSecuritySafeHtml
If you want to go one step further, and internationalize your messages, then see also https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nMessages#SafeHtmlMessages
You can simply write your own format function instead of doing brain storm.
public static String format(final String format, final String... args,String delimiter) {
String[] split = format.split(delimiter);//in your case "%d" as delimeter
final StringBuffer buffer= new StringBuffer();
for (int i= 0; i< split.length - 1; i+= 1) {
buffer.append(split[i]);
buffer.append(args[i]);
}
buffer.append(split[split.length - 1]);
return buffer.toString();
}
Because most (as in 99.999%) message formats are static, known at compile-time, the way GWT approaches it is to parse them at compile-time.
You'll generally use a Messages subinterface for its ability to localize the message, but you'll sometimes rather need SafeHtmlTemplates.
In the 0.001% when template is not known at compile time you can use Javascript sprintf (see: http://www.diveintojavascript.com/projects/javascript-sprintf) as in:
public static native String format (String format, JsArrayMixed values) /*-{
return vsprintf(format, values);
}-*/;
You can write your own.
I wrote a version that just work with Strings(%s):
public static String format(final String format, final Object... args)
{
checkNotNull(format);
checkNotNull(args);
final String pattern = "%s";
int start = 0, last = 0, argsIndex = 0;
final StringBuilder result = new StringBuilder();
while ((start = format.indexOf(pattern, last)) != -1)
{
if (args.length <= argsIndex)
{
throw new IllegalArgumentException("There is more replace patterns than arguments!");
}
result.append(format.substring(last, start));
result.append(args[argsIndex++]);
last = start + pattern.length();
}
if (args.length > argsIndex)
{
throw new IllegalArgumentException("There is more arguments than replace patterns!");
}
result.append(format.substring(last));
return result.toString();
}
why not writing a method like:
String appendAnswer(int result) {
return "The answer is - " + Integer.toString(result);
}
is resolving your problem because you do nothing like formatting in your code.
if you ever face the problem like converting integer/byte to Hex String you should use:
Integer.toString(int, 16);
I don't know GWT much but I am working on a GWT project and I needed this. While trying some alternatives, I have found that this is working;
import java.text.MessageFormat;
MessageFormat.format("The answer is - {0}", 42);
I don't know if the project's developers added something special to make this work or it is working by default.

AspectJ - Retrieve list of annotated parameters

From the following previous question (AspectJ - Presence of annotation in join point expression not recognized),
My goal:
In an aspect, i'd like to be able to extract/retrieve all annotated parameters from matching functions, no matter how many there are. (and then apply some treatment on but it's not the scope of this question)
So for the moment, this is what i did (not working):
#Before("execution (* org.xx.xx.xx..*.*(#org.xx.xx.xx.xx.xx.Standardized (*),..))")
public void standardize(JoinPoint jp) throws Throwable {
Object[] myArgs = jp.getArgs();
getLogger().info("Here: arg length=" + myArgs.length);
// Roll on join point arguments
for (Object myParam : myArgs) {
getLogger().info(
"In argument with " + myParam.getClass().getAnnotations().length
+ " declaread annotations");
getLogger().info("Class name is " + myParam.getClass().getName());
// Get only the one matching the expected #Standardized annotation
if (myParam.getClass().getAnnotation(Standardized.class) != null) {
getLogger().info("Found parameter annotated with #Standardized");
standardizeData(myParam.getClass().getAnnotation(Standardized.class), myParam);
}
}
}
This is the code matched by the advice:
public boolean insertLog(#Standardized(type = StandardizedData.CLIPON) CliponStat theStat) {
// ...
}
And the traces generated by a junit test:
INFO: ICI: arg lenght=1
INFO: In argument with 0 declaread annotations
Looks like it doesn't detect the annotation
So my question is: how to detect parameters which have specific annotation(s) ?
Does somebody have an idea how to do it?
Thanks in advance for your help.
Regards.
Edit: i found this thread Pointcut matching methods with annotated parameters, discussing of the same thing, and applied the given solution but it doesn't work..
I hope I understand you right.
myParam.getClass().getAnnotations() gives you the annotations on a class. Something like:
#Standardized(type = StandardizedData.CLIPON)
public class Main{...}
Maybe this pointcut/advice helps you:
#Before("execution (* org.xx.xx.xx..*.*(#org.xx.xx.xx.xx.xx.Standardized (*),..))")
public void standardize(JoinPoint jp) throws Throwable {
Object[] args = jp.getArgs();
MethodSignature ms = (MethodSignature) jp.getSignature();
Method m = ms.getMethod();
Annotation[][] parameterAnnotations = m.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
Annotation[] annotations = parameterAnnotations[i];
System.out.println("I am checking parameter: " + args[i]);
for (Annotation annotation : annotations) {
System.out.println(annotation);
if (annotation.annotationType() == Standardized.class) {
System.out.println("we have a Standardized Parameter with type = "
+ ((Standardized) annotation).type());
}
}
}
}
This gives me the following output:
I am checking parameter: main.CliponStat#331f2ee1
#annotation.Standardized(type=CLIPON)
we have a Standardized Parameter with type = CLIPON

DataSet does not support System.Nullable<>

i have an app which has btn to preview report made in crystal report. I added Dataset as datasource of the report and dragged datatable from the toolbox and added the fields I need as columns. I got the instruction from this link http://aspalliance.com/2049_Use_LINQ_to_Retrieve_Data_for_Your_Crystal_Reports.2. This is my 2nd report the first one works and did not encounter any prob at all that is why i am confused, not to mention it also has nullable column. the error says: DataSet does not support System.Nullable<>.
private void ShowReportView()
{
string reportFile = "JudgeInfoFMReport.rpt";
ObservableCollection<tblJudgeFileMaint> judgeFileMaintList;
judgeFileMaintList = GenerateReport();
if (judgeFileMaintList.Count > 0)
{
CrystalReportViewerUC crview2 = new CrystalReportViewerUC();
crview2.SetReportPathFile(reportFile, judgeFileMaintList);
crview2.ShowDialog();
}
else
{
System.Windows.MessageBox.Show("No record found.", module, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private ObservableCollection<tblJudgeFileMaint> GenerateReport()
{
var result = FileMaintenanceBusiness.Instance.GetAllJudgeInfoList();
return new ObservableCollection<tblJudgeFileMaint>(result);
}
The error is in the part where I set datasource report.SetDataSource
public bool SetReportPathFile(string reportPathFile, IEnumerable enumerable)
{
string reportFolder = #"\CrystalReportViewer\Reports\";
string filename = System.Windows.Forms.Application.StartupPath + reportFolder + reportPathFile; // "\\Reports\\CrystalReports\\DateWiseEmployeeInfoReport.rpt";
ReportPathFile = filename;
report.Load(ReportPathFile);
report.SetDataSource(enumerable);
report.SetDatabaseLogon("sa", "admin007");
bRet = true;
}
_IsLoaded = bRet;
return bRet;
}
I read some answers and says I should set the null value to DBNUll which I did in the properties window of each column if it is nullable. Can anyone help me please? thanks
Your question can be seen in this post, but in a generic way ... that way you can pass an Object to a DataSet typed!
.NET - Convert Generic Collection to DataTable
figured it out. by using a collectionextention, copied somewhere, I forgot the link. Os to whoever it is who made the class, credits to you.
class method looks like this.
public statis class CollectionExtension {
public static DataSet ToDataSet<T>(this IEnumerable<T> collection, string dataTableName)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (string.IsNullOrEmpty(dataTableName))
{
throw new ArgumentNullException("dataTableName");
}
DataSet data = new DataSet("NewDataSet");
data.Tables.Add(FillDataTable(dataTableName, collection));
return data;
}
}
then you can use it by doing this in getting your source to your report:
private DataSet GenerateNeutralContEducReport(string dsName)
{
var contEduHistoryList = FileMaintenanceBusiness.Instance.GetManyNeutralFMContEducHistoryInfobyKeyword(CurrentNeutralFM.NeutralID, "NeutralID").ToList();
return CollectionExtensions.ToDataSet<tblContinuingEducationHistory>(contEduHistoryList, dsName);
}
I found little help from the other proposed answers but this solution worked.
A different way to solve this problem is to make the data column nullable.
DataColumn column = new DataColumn("column", Type.GetType("System.Int32"));
column.AllowDBNull = true;
dataTable.Columns.Add(column);
https://learn.microsoft.com/en-us/dotnet/api/system.data.datacolumn.allowdbnull?view=netcore-3.1
foreach (PropertyDescriptor property in properties)
{
dt.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}

How can I obtain the version number of a custom Eclipse feature at runtime?

I would like to display the version number of a custom Eclipse feature I am developing in the title bar of its perspective. Is there a way to obtain the version number from the runtime plugin and/or workbench?
Something like:
Platform.getBundle("my.feature.id").getHeaders().get("Bundle-Version");
should do the trick.
Note (from this thread) that it can not be used anywhere within the plugin itself:
this.getBundle() is not valid until AFTER super.start(BundleContext) has been called on your plugin.
So if you are using this.getBundle() within your constructor or within your start(BundleContext) before calling super.start() then it will return null.
If that fails, you have here a more complete "version":
public static String getPlatformVersion() {
String version = null;
try {
Dictionary dictionary =
org.eclipse.ui.internal.WorkbenchPlugin.getDefault().getBundle().getHeaders();
version = (String) dictionary.get("Bundle-Version"); //$NON-NLS-1$
} catch (NoClassDefFoundError e) {
version = getProductVersion();
}
return version;
}
public static String getProductVersion() {
String version = null;
try {
// this approach fails in "Rational Application Developer 6.0.1"
IProduct product = Platform.getProduct();
String aboutText = product.getProperty("aboutText"); //$NON-NLS-1$
String pattern = "Version: (.*)\n"; //$NON-NLS-1$
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(aboutText);
boolean found = m.find();
if (found) {
version = m.group(1);
}
} catch (Exception e) {
}
return version;
}
I use the first option:
protected void fillStatusLine(IStatusLineManager statusLine) {
statusItem = new StatusLineContributionItem("LastModificationDate"); //$NON-NLS-1$
statusItem.setText("Ultima Actualizaci\u00f3n: "); //$NON-NLS-1$
statusLine.add(statusItem);
Dictionary<String, String> directory = Platform.getBundle("ar.com.cse.balanza.core").getHeaders();
String version = directory.get("Bundle-Version");
statusItem = new StatusLineContributionItem("CopyRight"); //$NON-NLS-1$
statusItem.setText(Messages.AppActionBar_18);
statusLine.add(statusItem);
}
As #zvikico says above, the accepted answer does not work for Features, only Plug-ins (OSGi Bundles, which Features are not). The way to get info about installed features is via org.eclipse.core.runtime.Platform.getBundleGroupProviders() as described here.
A version of what VonC provided to retrieve the primary Eclipse version number, but one that doesn't reference internal classes (which you should avoid doing):
Platform.getBundle(PlatformUI.PLUGIN_ID).getHeaders().get("Bundle-Version");