number possible part of speech of the word - stanford-nlp

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]

Related

How to do syntaxhighlighting for terminal rules in Xtext?

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.

error in projecting a shapefile from epsg:4326 to epsg:32056

I have been trying to change the projection of Shapefile from one coordinate reference system to other. The shapefile I have used has EPSG:4326 as its reference system and I need to change it to EPSG:32056.
I am using Geotools API-20.0 for the same.
I have already tried various methods available in the geotools like using ReprojectingFeatureCollection, use of JTS, use of Query API to convert the shapefile directly to the other coordinate reference system
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.SwingWorker;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFactorySpi;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Query;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.referencing.CRS;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.geotools.referencing.factory.gridshift.GridShiftLocator;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.JProgressWindow;
import org.geotools.swing.action.SafeAction;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.locationtech.jts.geom.Envelope;
import org.opengis.feature.Feature;
import org.opengis.feature.FeatureVisitor;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.FeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.util.ProgressListener;
import com.vividsolutions.jts.geom.Geometry;
public class CRSLab {
private File sourceFile;
private SimpleFeatureSource featureSource;
private MapContent map;
public static void main(String[] args) throws Exception {
CRSLab lab = new CRSLab();
lab.displayShapefile();
}
// docs end main
/**
* This method:
* <ol type="1">
* <li>Prompts the user for a shapefile to display
* <li>Creates a JMapFrame with custom toolbar buttons
* <li>Displays the shapefile
* </ol>
*/
// docs start display
private void displayShapefile() throws Exception {
sourceFile = JFileDataStoreChooser.showOpenFile("shp", null);
if (sourceFile == null) {
return;
}
FileDataStore store = FileDataStoreFinder.getDataStore(sourceFile);
featureSource = store.getFeatureSource();
// Create a map context and add our shapefile to it
map = new MapContent();
Style style = SLD.createSimpleStyle(featureSource.getSchema());
Layer layer = new FeatureLayer(featureSource, style);
map.layers().add(layer);
// Create a JMapFrame with custom toolbar buttons
JMapFrame mapFrame = new JMapFrame(map);
mapFrame.enableToolBar(true);
mapFrame.enableStatusBar(true);
JToolBar toolbar = mapFrame.getToolBar();
toolbar.addSeparator();
toolbar.add(new JButton(new ValidateGeometryAction()));
toolbar.add(new JButton(new ExportShapefileAction()));
// Display the map frame. When it is closed the application will exit
mapFrame.setSize(800, 600);
mapFrame.setVisible(true);
}
// docs end display
// docs start export
private void exportToShapefile() throws Exception {
SimpleFeatureType schema = featureSource.getSchema();
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save reprojected shapefile");
chooser.setSaveFile(sourceFile);
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
return;
}
File file = chooser.getSelectedFile();
if (file.equals(sourceFile)) {
JOptionPane.showMessageDialog(null, "Cannot replace " + file);
return;
}
// set up the math transform used to process the data
CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
CoordinateReferenceSystem worldCRS = CRS.decode("EPSG:32056", true);// map.getCoordinateReferenceSystem();
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform(dataCRS, worldCRS, lenient);
// grab all features
SimpleFeatureCollection featureCollection = featureSource.getFeatures();
// And create a new Shapefile with a slight modified schema
DataStoreFactorySpi factory = new ShapefileDataStoreFactory();
Map<String, Serializable> create = new HashMap<String, Serializable>();
create.put("url", file.toURI().toURL());
create.put("create spatial index", Boolean.TRUE);
DataStore dataStore = factory.createNewDataStore(create);
SimpleFeatureType featureType = SimpleFeatureTypeBuilder.retype(schema, worldCRS);
dataStore.createSchema(featureType);
String createdName = dataStore.getTypeNames()[0];
// carefully open an iterator and writer to process the results
Transaction transaction = new DefaultTransaction("Reproject");
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(createdName,
transaction);
SimpleFeatureIterator iterator = featureCollection.features();
try {
int counter = 0;
while (iterator.hasNext()) {
// copy the contents of each feature and transform the geometry
SimpleFeature feature = iterator.next();
SimpleFeature copy = writer.next();
org.locationtech.jts.geom.Geometry geometry = (org.locationtech.jts.geom.Geometry) feature
.getDefaultGeometry();
org.locationtech.jts.geom.Geometry geometry2 = JTS.transform(geometry, transform);
System.out.println(geometry.isSimple() && geometry2.isSimple());
// if (geometry2.isValid()) {
copy.setAttributes(feature.getAttributes());
counter++;
copy.setDefaultGeometry(geometry2);
writer.write();
// }
}
transaction.commit();
System.out.println("valid geometries : " + counter);
JOptionPane.showMessageDialog(null, "Export to shapefile complete");
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
JOptionPane.showMessageDialog(null, "Export to shapefile failed");
} finally {
writer.close();
iterator.close();
transaction.close();
}
}
// docs end export
// docs start validate
private int validateFeatureGeometry(ProgressListener progress) throws Exception {
final SimpleFeatureCollection featureCollection = featureSource.getFeatures();
// Rather than use an iterator, create a FeatureVisitor to check each
// fature
class ValidationVisitor implements FeatureVisitor {
public int numInvalidGeometries = 0;
public void visit(Feature f) {
SimpleFeature feature = (SimpleFeature) f;
Geometry geom = (Geometry) feature.getDefaultGeometry();
if (geom != null && !geom.isValid()) {
numInvalidGeometries++;
System.out.println("Invalid Geoemtry: " + feature.getID());
}
}
}
ValidationVisitor visitor = new ValidationVisitor();
// Pass visitor and the progress bar to feature collection
featureCollection.accepts(visitor, progress);
return visitor.numInvalidGeometries;
}
// docs end validate
// docs start export action
class ExportShapefileAction extends SafeAction {
ExportShapefileAction() {
super("Export...");
putValue(Action.SHORT_DESCRIPTION, "Export using current crs");
}
public void action(ActionEvent e) throws Throwable {
exportToShapefile();
}
}
// docs end export action
/**
* This class performs the task of checking that the Geometry of each
* feature is topologically valid and reports on the results. It also
* supplies the name and tool tip.
*/
// docs start validate action
class ValidateGeometryAction extends SafeAction {
ValidateGeometryAction() {
super("Validate geometry");
putValue(Action.SHORT_DESCRIPTION, "Check each geometry");
}
public void action(ActionEvent e) throws Throwable {
int numInvalid = validateFeatureGeometry(null);
String msg;
if (numInvalid == 0) {
msg = "All feature geometries are valid";
} else {
msg = "Invalid geometries: " + numInvalid;
}
JOptionPane.showMessageDialog(null, msg, "Geometry results", JOptionPane.INFORMATION_MESSAGE);
}
}
// docs end validate action
}
The output obtained after doing projection using Geotools are a lot different than what I used to get from ArcMap of esri. Is there any other transformation that I should perform.
When I try this (with v22.x) all I get is an error as too many points are outside the valid projection error. This is because you are taking a map of the world and reprojecting it to a CRS designed for Wyoming.
It seems that ESRI are being "helpful" and clipping your output to the area of validity (assuming you meant something other than EPSG:32056). GeoTools assumes that you know what you are doing and doesn't do that, which is why you have all the countries of the world shown in that map.
Here is the output for just the USA, which suggests that the ESRI image you show is a different projection again (look at the 49th parallel).

How to paste the text copied in clipboard through Selenium and Java on MacOS

I want to paste some text in one of the textbox in MACOS. I am trying below code. But Control + v and Command + v both are not working. I have also seen that this is known issue, but not sure if it is resolved or not.
https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5919
The code is as below.
public void copyToClipbord(String copyTo)
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection str = new StringSelection(copyTo);
clipboard.setContents(str, null );
}
// And paste into required input/testfield/testarea field object
public void pasteText(WebElement element, String value)
{
copyToClipbord(value);
element.click();
//new Actions( driver ).contextClick( element ).sendKeys( "P" ).sendKeys("\n").perform();
element.sendKeys(Keys.CONTROL, "V");
}
I have also tried context click, that also does not work. I have validated that copyToClipboard function is working properly. Please suggest me, if there are any work around to this.
Thanks,
Umang
You have to select paste option in pop up which open after right and then click on paste option.
You can write code like this.
new Actions(driver ).contextClick(element).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).
sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
For me Paste option is present at 5th position. So I have written sendKeys(Keys.ARROW_DOWN) 5 times. You can write this as per your requirement.
I hope this will work for you.
As you have mentioned copyToClipboard() function is working properly moving forward to send the character sequence through sendKeys() you can use the following solution:
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
copyToClipbord(value);
String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
element.sendKeys(data);
public String copyFromClipboard() {
boolean found = false
String data = ''
int count = 0
while (found == false) {
count++
try {
WebDriver driver = DriverFactory.getWebDriver()
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
data = ((Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor)) as String)
if (!(data.contains('https'))) {
found = false
} else {
println((('Found the data in the ' + count) + ' try: ') + data)
return data
found = true
break
}
}
catch (UnsupportedFlavorException e) {
println(e)
}
catch (IOException e) {
println(e)
}
}
}

Multiple values for an option in std.getopt

Just as an example, I have made a program for filtering out empty lines of a file and write the result into a new file:
// dlang filter out empty lines
import std.stdio;
import std.string;
import std.getopt;
string inputFile;
string outputFile;
void main(string[] args)
{
getopt(args, "if", &inputFile, "of", &outputFile);
File ifh = File(inputFile, "r");
File ofh = File(outputFile, "w");
foreach(line; ifh.byLine) {
line = line.chomp;
if(line != "") {
ofh.writeln(line);
}
}
}
It is quite nice and the setup is super easy, but what if I want to take multiple values for the --if option?
You can use a string[] receiver:
string[] inputFiles
getopt(args, "if", &inputFiles);
foreach(f; inputFiles) {...}
Then give multiple --if options when running the program, and they all end up in inputFiles.
See also: http://dlang.org/phobos/std_getopt.html - Array options

How to make a dynamic image at run time?

I'm working on a card game based on the NetBeans platform and I'm struggling to get my head around dynamic images. Why dynamic? Well I want the cards to adjust at run time to changes to the page (i.e. name, text, cost, etc).
My first hack at it was creating a component (JPanel) with labels pre-placed where I loaded the text/image based on the card values. That seems to work fine but then it became troublesome when I thought about some pages having a different look in later editions (meaning not everything would be on the same place).
So I'm trying to get an idea about ways to do this based on some kind of template.
Any idea?
There's a follow-up question at: JList of cards?
Finally I got some time to get back to this and was able to figure out a way using Java 2D tutorial.
The pictures are not near what I will use in my application but serves as proof of concept.
package javaapplication3;
import java.awt.*; import java.awt.font.FontRenderContext; import
java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute;
import java.awt.font.TextLayout; import java.awt.image.BufferedImage;
import java.io.File; import java.io.IOException; import
java.net.MalformedURLException; import java.net.URL; import
java.text.AttributedCharacterIterator; import
java.text.AttributedString; import java.util.ArrayList; import
java.util.HashMap; import java.util.logging.Level; import
java.util.logging.Logger; import javax.imageio.ImageIO;
/** * * #author Javier A. Ortiz Bultrón
*/ public class DefaultImageManager {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
DefaultImageManager manager = new DefaultImageManager();
URL url = DefaultImageManager.class.getResource("weather-rain.png");
manager.getLayers().add(ImageIO.read(url));
url = DefaultImageManager.class.getResource("weather-sun.png");
manager.getLayers().add(ImageIO.read(url));
manager.addText(new Font("Arial", Font.PLAIN, 10), "Many people believe that Vincent van Gogh painted his best works "
+ "during the two-year period he spent in Provence. Here is where he "
+ "painted The Starry Night--which some consider to be his greatest "
+ "work of all. However, as his artistic brilliance reached new "
+ "heights in Provence, his physical and mental health plummeted. ",
200, 150, new Point(0, 0));
manager.generate();
} catch (MalformedURLException ex) {
Logger.getLogger(DefaultImageManager.class.getName()).log(Level.SEVERE,
null, ex);
} catch (IOException ex) {
Logger.getLogger(DefaultImageManager.class.getName()).log(Level.SEVERE,
null, ex);
}
}
/**
* Layers used to create the final image
*/
private ArrayList layers = new ArrayList();
private ArrayList textLayers = new ArrayList();
/**
* #return the layers
*/
public ArrayList<BufferedImage> getLayers() {
return layers;
}
private Dimension getMaxSize() {
int width = 0, height = 0;
for (BufferedImage img : getLayers()) {
if (img.getWidth() > width) {
width = img.getWidth();
}
if (img.getHeight() > height) {
height = img.getHeight();
}
}
return new Dimension(width, height);
}
public void addText(Font font, String text, int height, int width, Point location) {
BufferedImage textImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
HashMap<TextAttribute, Object> map =
new HashMap<TextAttribute, Object>();
map.put(TextAttribute.FAMILY, font.getFamily());
map.put(TextAttribute.SIZE, font.getSize());
map.put(TextAttribute.FOREGROUND, Color.BLACK);
AttributedString aString = new AttributedString(text, map);
AttributedCharacterIterator paragraph = aString.getIterator();
// index of the first character in the paragraph.
int paragraphStart = paragraph.getBeginIndex();
// index of the first character after the end of the paragraph.
int paragraphEnd = paragraph.getEndIndex();
Graphics2D graphics = textImage.createGraphics();
FontRenderContext frc = graphics.getFontRenderContext();
// The LineBreakMeasurer used to line-break the paragraph.
LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);
// Set break width to width of Component.
float breakWidth = width;
float drawPosY = 0;
// Set position to the index of the first character in the paragraph.
lineMeasurer.setPosition(paragraphStart);
// Get lines until the entire paragraph has been displayed.
while (lineMeasurer.getPosition() < paragraphEnd) {
// Retrieve next layout. A cleverer program would also cache
// these layouts until the component is re-sized.
TextLayout layout = lineMeasurer.nextLayout(breakWidth);
// Compute pen x position. If the paragraph is right-to-left we
// will align the TextLayouts to the right edge of the panel.
// Note: this won't occur for the English text in this sample.
// Note: drawPosX is always where the LEFT of the text is placed.
float drawPosX = layout.isLeftToRight()
? 0 : breakWidth - layout.getAdvance();
// Move y-coordinate by the ascent of the layout.
drawPosY += layout.getAscent();
// Draw the TextLayout at (drawPosX, drawPosY).
layout.draw(graphics, drawPosX, drawPosY);
// Move y-coordinate in preparation for next layout.
drawPosY += layout.getDescent() + layout.getLeading();
}
getTextLayers().add(textImage);
}
public void generate() throws IOException {
Dimension size = getMaxSize();
BufferedImage finalImage = new BufferedImage(size.width, size.height,
BufferedImage.TYPE_INT_ARGB);
for (BufferedImage img : getLayers()) {
finalImage.createGraphics().drawImage(img,
0, 0, size.width, size.height,
0, 0, img.getWidth(null),
img.getHeight(null),
null);
}
for(BufferedImage text: getTextLayers()){
finalImage.createGraphics().drawImage(text,
0, 0, text.getWidth(), text.getHeight(),
0, 0, text.getWidth(null),
text.getHeight(null),
null);
}
File outputfile = new File("saved.png");
ImageIO.write(finalImage, "png", outputfile);
}
/**
* #return the textLayers
*/
public ArrayList<BufferedImage> getTextLayers() {
return textLayers;
}
/**
* #param textLayers the textLayers to set
*/
public void setTextLayers(ArrayList<BufferedImage> textLayers) {
this.textLayers = textLayers;
} }
It still needs some refining specially on the placement of the text but it works. I guess I can implement a xml format to store all this information so is easily configurable. In the example below suns are drawn on top of rain, and the text is on top of all that. For my application each layer will build together the page I want.
Here are the images I used:
And the final result:

Resources