How to do syntaxhighlighting for terminal rules in Xtext? - syntax-highlighting

I would like to do custom syntaxhighlighting in xtext. I would like to highlight everything that matches a terminal rule in a specific color.
For example my terminal rule:
terminal MYRULE:
('ab'|'2')*
;
I would like to color the everything like a comment what matches this terminal rule.
I tired the following:
package org.xtext.example.mydsl.ui;
import java.util.regex.Pattern;
import org.eclipse.xtext.ide.editor.syntaxcoloring.HighlightingStyles;
import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultAntlrTokenToAttributeIdMapper;
public class STAntlrTokenToAttributeIdMapper extends DefaultAntlrTokenToAttributeIdMapper {
private static final Pattern QUOTED = Pattern.compile("(?:^'([^']*)'$)|(?:^\"([^\"]*)\")$", Pattern.MULTILINE);
private static final Pattern PUNCTUATION = Pattern.compile("\\p{Punct}*");
#Override
protected String calculateId(String tokenName, int tokenType) {
System.out.println("token = " + tokenName);
if ("MYRULE".equals(tokenName)) {
return HighlightingStyles.COMMENT_ID;
}
if(QUOTED.matcher(tokenName).matches()) {
return HighlightingStyles.KEYWORD_ID;
}
if("RULE_STRING".equals(tokenName)) {
return HighlightingStyles.STRING_ID;
}
if("RULE_INT".equals(tokenName)) {
return HighlightingStyles.NUMBER_ID;
}
if("RULE_ML_COMMENT".equals(tokenName) || "RULE_SL_COMMENT".equals(tokenName)) {
return HighlightingStyles.COMMENT_ID;
}
return HighlightingStyles.DEFAULT_ID;
}
}
I see the print for "MYRULE". The code is accepted from the editor. But the special code part is not highlighted.
Of course the rule is just an example and not part of the DLS I am working on. But I can't tell details about my DSL.

Related

Ban command not working JDA please help debuged and everything

Hello so i am making a bot in JDA and i just made a ban command but it aint banning anyone the code is
i mention the user and also put a reason and put the user id and still make no difference
package me.programmer.CodeDevelopment.Commands;
import me.programmer.CodeDevelopment.Bot;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import java.util.List;
public class Ban extends ListenerAdapter {
public void onMessageGuildReceived(List<String> args, GuildMessageReceivedEvent e){
String msg = e.getMessage().getContentRaw();
if(msg.equalsIgnoreCase(Bot.PREFIX + "ban")){
TextChannel channel = e.getChannel();
Member member = e.getMember();
List<Member> mentionedMembers = e.getMessage().getMentionedMembers();
if (mentionedMembers.isEmpty() || args.size() < 2) {
channel.sendMessage("Missing Arguments").queue();
return;
}
Member target = mentionedMembers.get(0);
String reason = String.join(" ", args.subList(1, args.size()));
if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)){
channel.sendMessage("You dont have pmerission to run this command").queue();
return;
}
target.ban(1)
.reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
}
}
}
Please help i have been stuck on this for a little while.
Like Minn mentioned, You didn't override the method from ListenerAdapter properly. The name and parameter list have to match.
Also, You're checking if the entire message is equal to {PREFIX}ban yet your ban command is structured like so {PREFIX}ban (user) so your code always stops on this line:
if(msg.equalsIgnoreCase(Bot.PREFIX + "ban"))
Because that is never true when using the command correctly.
This should work instead (I've changed the msg check to starts with from equals, I've changed the method name to the right one with the right parameters from ListenerAdapter and I've then kept your usage of args by splitting the msg string and putting that into a list):
public class Ban extends ListenerAdapter {
#Override
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String msg = e.getMessage().getContentRaw();
if (msg.startsWith(Bot.PREFIX + "ban")) {
TextChannel channel = e.getChannel();
Member member = e.getMember();
List<Member> mentionedMembers = e.getMessage().getMentionedMembers();
List<String> args = Arrays.asList(msg.split(" "));
if (mentionedMembers.isEmpty() || args.size() < 2) {
channel.sendMessage("Missing Arguments").queue();
return;
}
Member target = mentionedMembers.get(0);
String reason = String.join(" ", args.subList(1, args.size()));
if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)) {
channel.sendMessage("You dont have pmerission to run this command").queue();
return;
}
target.ban(1)
.reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
}
}
}

Not able to set Redaction Color in iText7 (C#)

I'm not able to change PDF redaction's color in iText7 + PDFSweep using the C# code below. The RED redaction box takes effect only on the first page of the PDF file, then on subsequent pages the color of the redaction box reverts back to BLACK
String input = SRC_FOLDER + "/report.pdf";
String output = SRC_FOLDER + "/report_redacted.pdf";
CompositeCleanupStrategy strategy = new CompositeCleanupStrategy();
strategy.Add(new RegexBasedCleanupStrategy(#"(\d\d\d\d)").SetRedactionColor(ColorConstants.RED));
PdfDocument pdf = new PdfDocument(new PdfReader(input), new PdfWriter(output));
PdfAutoSweep autoSweep = new PdfAutoSweep(strategy);
autoSweep.CleanUp(pdf);
pdf.Close();
It's a bug in pdfSweep.
ìText handles documents on a page by page basis.
In order to be able to re-use the same strategy on different pages, every ICleanupStrategy needs to provide a reset method.
The current implementation for that reset method for RegexBasedCleanupStragegy is
public ICleanupStrategy reset() {
return new RegexBasedCleanupStrategy(this.pattern);
}
Which copies the strategy's pattern, but not its color. As a result, on every page but the first one, the color will default back to black.
To fix this, simply create your own implementation that overrides this behavior to also copy the color.
I will report this as a bug (iText developer here)
for the sake of completion, this would be the fixed approach:
public class RegexBasedCleanupStrategy extends
RegexBasedLocationExtractionStrategy implements ICleanupStrategy {
private Pattern pattern;
private Color redactionColor = ColorConstants.BLACK;
public RegexBasedCleanupStrategy(String regex) {
super(regex);
this.pattern = Pattern.compile(regex);
}
public RegexBasedCleanupStrategy(Pattern pattern) {
super(pattern);
this.pattern = pattern;
}
#Override
public Color getRedactionColor(IPdfTextLocation location) {
return redactionColor;
}
public RegexBasedCleanupStrategy setRedactionColor(Color color) {
this.redactionColor = color;
return this;
}
public ICleanupStrategy reset() {
RegexBasedCleanupStrategy copy = new RegexBasedCleanupStrategy(pattern);
copy.redactionColor = redactionColor;
return copy;
}
}

How to add search bar in navigation bar

I need to implement the search bar in navigation bar for android in xamarin.forms,while searching i found many examples for ios but not for android.How to achieve this for android through customrenderer?
Easy way to create a Search is to create class and make use of Filter options
like this
Search Bar Button on Top
<item android:id="#+id/action_search"
android:title="Search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="always" />
Classes You May Require
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
//getting text from user
#Override
public boolean onQueryTextChange(String newText) {
activity.getFilter().filter(newText);
return false;
}
//submitting Text
#Override
public boolean onQueryTextSubmit(String newText) {
activity.getFilter().filter(newText);
return false;
}
This is other Activity
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Pokemon> to_be_filtered = new ArrayList<>();
String filterPattern = constraint.toString().toLowerCase().trim();
//implement search
if(filterPattern.isEmpty()) {
to_be_filtered.addAll(fulllist);
}
else {
for (some this iterate over ) {
if (get_name_of_required
search.getName().toLowerCase().contains(filterPattern)) {
add_created_database_to_be_filtered.add(name of list variable);
}
}
}
In this you have to use inbuilt function called getfilter() it will handle Search bar.
Here I had used statements like to_be_filtered and add_created_database, You have to modify code according to database you are using.
I my case I am having 2 activities in which the first three class i.e. OnQuerySearch... , Submit text and Save text are in MainActivity and getFilter() is in another Activity
Thanks I hope you got your answer

number possible part of speech of the word

I know how to get pos of a word in the text but I need to know what would be the possible pos of a word in a sentence for example "like" can have 4 part of speechs: verb noun preposition ....
Is it possible to get that from Stanford library?
Stanford CoreNLP doesn't seem to have an interface to WordNet, but it's pretty easy to do this with one of the other small Java WordNet libraries. For this example, I used JWI 2.3.3.
Besides JWI, you'll need to download a copy of the WordNet database. For example, you can download WordNet-3.0.tar.gz from Princeton. Untar the dictionary.
The following code includes a function that returns a list of the possible parts of speech for a word:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import edu.mit.jwi.Dictionary;
import edu.mit.jwi.item.POS;
import edu.mit.jwi.item.IIndexWord;
import edu.mit.jwi.morph.WordnetStemmer;
public class WNDemo {
/**
* Given a dictionary and a word, find all the parts of speech the
* word can be.
*/
public static Collection getPartsOfSpeech(Dictionary dict, String word) {
ArrayList<POS> parts = new ArrayList<POS>();
WordnetStemmer stemmer = new WordnetStemmer(dict);
// Check every part of speech.
for (POS pos : POS.values()) {
// Check every stem, because WordNet doesn't have every surface
// form in its database.
for (String stem : stemmer.findStems(word, pos)) {
IIndexWord iw = dict.getIndexWord(stem, pos);
if (iw != null) {
parts.add(pos);
}
}
}
return parts;
}
public static void main(String[] args) {
try {
Dictionary dict = new Dictionary(new File("WordNet-3.0/dict"));
dict.open();
System.out.println("'like' is a " + getPartsOfSpeech(dict, "like"));
} catch (IOException e) {
System.err.println("Error: " + e);
}
}
}
And the output:
'like' is a [noun, verb, adjective]

JFace TreeView not launching when Input is a String

I'm trying launch a simple JFace Tree.
It's acting really strange however. When I setInput() to be a single String, the tree opens up completely blank. However, when I set input to be a String array, it works great.
This has nothing to do with the LabelProvider or ContentProvider since these behave the same no matter what (it's a really simple experimental program).
setInput() is officially allowed to take any Object. I am confused why it will not take a String, and knowing why may help me solve my other problems in life.
Setting a single String as input:
TreeViewer treeViewerLeft = new TreeViewer(shell, SWT.SINGLE);
treeViewerLeft.setLabelProvider(new TestLabelProvider());
treeViewerLeft.setContentProvider(new TestCompareContentProvider());
treeViewerLeft.expandAll();
treeViewerLeft.setInput(new String("Stooge"));
Setting an array of Strings:
TreeViewer treeViewerLeft = new TreeViewer(shell, SWT.SINGLE);
treeViewerLeft.setLabelProvider(new TestLabelProvider());
treeViewerLeft.setContentProvider(new TestCompareContentProvider());
treeViewerLeft.expandAll();
treeViewerLeft.setInput(new String[]{"Moe", "Larry", "Curly"});
The second works, and launches a tree using the following providers:
public class TestCompareContentProvider extends ArrayContentProvider implements ITreeContentProvider {
public static int children = 0;
public Object[] getChildren(Object parentElement) {
children++;
if (children > 20){
return null;
}
return new String[] {"Moe", "Larry", "Curly"};
}
public Object getParent(Object element) {
return "Parent";
}
public boolean hasChildren(Object element) {
if (children >20){
return false;
}
return true;
}
}
and
public class TestLabelProvider extends LabelProvider {
public String getText(Object element){
return "I'm something";
}
public Image getImage(Object element){
return null;
}
}
You've inherited getElements from the ArrayContentProvider and that only works with arrays. You should override this method.
I don't think you need to extend ArrayContentProvider at all.

Resources