Multiple values for an option in std.getopt - command-line-arguments

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

Related

While using FileReader class in java why is it compulsory to store the value of r.read in i first and then type caste it? why can't we typecast r.read

[it is giving wrong output when I use f1.read directly .. why is it compulsory to use (i=f1.read) and then type caste i into the file .. why can't we use f1.read directly..] 1
//why this code is giving wrong output
// why is it compulsory to first store the value of f1.read in i
import static java.lang.System.out;
import java.io.*;
import java.util.*;
public class third{
public static void main(String [] args) {
try{
FileReader f1 = new FileReader("C:\\Users\\Akshita Agarwal\\Desktop\\a.txt");
FileWriter f2 = new FileWriter("C:\\Users\\Akshita Agarwal\\Desktop\\b.txt");
try{
while(f1.read() !=-1){
f2.write((char)f1.read());
}
}
finally {
f2.close();
}
}
catch(IOException e){
out.println(e);
}
}
}
char is two bytes unsigned. int -1 is outside this range.
Your code does not close f1 and it writes half of the file, every second char.
It could be written as:
for (;;) {
int c = f1.read();
if (c == -1) {
break;
}
f2.write((char)c);
}
You suggestion
for (;;) {
char c = (char) f1.read();
if (c == (char)-1) {
break;
}
f2.write(c);
}
has one drawback.
You could embed a ((char) -1) or '\uFFFF' in the middle of your file, and only
half of the file would be read.
The shortest code is:
for (int c; (c = f1.read()) != -1;) {
f2.write((char)c);
}
However it:
reads and writes per character
there is a conversion reading from binary data using the platform encoding to (Unicode) text
there is a conversion writing from (Unicode) text to binary data using the platform encoding.
Here you could do:
Path path1 = Paths.get("C:\\Users\\Akshita Agarwal\\Desktop\\a.txt");
Path path2 = Paths.get(System.getProperty("user.home"), "Desktop\\b.txt");
Files.copy(path1, path2);
or read by lines:
Charset charset = Charset.defaultCharset();
try (BufferedWriter writer = Files.newBufferedWriter(path2, charset));
Stream<String> reader = Files.lines(path1, charset)) {
reader.forEach(line -> bw.write(line + "\r\n"));
} // Automatically closes reader and writer.
The charset is needed to use the platform encoding. Per default it uses UTF-8, Unicode for the full range of possible characters for all languages.
Try-with-resources is a weird syntax try (<DECLARATIONS>) { ... } that ensures closing of the (auto-)closeable variables in the declarations. Even on return, break or exception.
The lines read are stripped from line endings CR-LF = "\r\n" (Windows), LF (Unix), CR, NEL (AS/400 e.a.).

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.

Looking to Parse the following code (Apache CLI 1.4), but it doesn't get into the if loop

I have the following code in JDeveloper and I am trying to parse the output but can't seem to figure it out.
package project1;
import org.apache.commons.cli.*;
public class cmdParser
{
public static void main(String[] args)
{
try
{
Options options = new Options();
options.addOption("t", false, "display current time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("t"))
{
String optionT=cmd.getOptionValue("t");
System.out.println("Option t" + optionT);
}
else
{
System.out.println("Can't get the option");
}
}
catch(ParseException exp)
{
System.out.println("Error:" + exp.getMessage());
}
}
}
Output:
Click to enlarge the image
How do you get the option if you don't pass such an option...
Not sure how it is done in JDeveloper but from command line:
java cmdParser -t "my test option"
further more, you should use options.addOption("t", true, "display current time"); if you want to pass a value to the option. If the 2nd parameter is false, this option would just be a flag.

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)
}
}
}

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]

Resources