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 - memory-management

[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.).

Related

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

How to remove Objects from PDF File using PDFClown

I have a pdf which contains a lot of invisible paths. Since the amount of path produces problems later on, I would like to remove the ones that have white colors.
So far I am trying to do this with a ContentScanner:
public class FilterWhitePathScanner implements Scanner {
private static final Logger LOG = LoggerFactory.getLogger(FilterWhitePathScanner.class);
private int count = 0;
public void scan(ContentScanner level) {
if (level == null)
return;
while (level.moveNext()) {
ContentObject object = level.getCurrent();
if (object instanceof ContainerObject) {
// Scan the inner level!
scan(level.getChildLevel());
} else if (object instanceof org.pdfclown.documents.contents.objects.Path) {
AffineTransform ctm = level.getState().getCtm();
Color<?> strokeColor = level.getState().getStrokeColor();
Color<?> fillColor = level.getState().getFillColor();
if (checkWhite(fillColor) && checkWhite(strokeColor)) {
level.remove();
} else {
LOG.info("Stroke Color " + strokeColor + " - Fill Color " + fillColor);
}
} else {
LOG.info("Object:" + object);
}
}
}
It recognizes the paths correctly, but in the end these are not removed from the PDF. Here the code handling the PDF (it extracts only one page from the source pdf):
Document targetDoc = new File().getDocument();
targetDoc.getPages().add(sourceDoc.getPages().get(pageNum).clone(targetDoc));
Page page = targetDoc.getPages().get(0);
Contents contents = page.getContents();
FilterWhitePathScanner filterWhitePathScanner = new FilterWhitePathScanner();
filterWhitePathScanner.scan(new ContentScanner(contents));
LOG.info("White Paths: " + filterWhitePathScanner.getCount());
targetDoc.getFile().save(tempFilePath.toFile(), SerializationModeEnum.Standard);
The saved PDF file still contains the paths I tried to remove. How can I remove objects from the PDF finally?
Thanks,
Thomas
Finally found the solution in the Java doc:
You have to call contents.flush(); to persist the changes into the pdf file.
So I added this line to the PDF handling code before calling save and it works!

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 create a Mathematica Notebook in Java?

I am looking for the prototypical 'Hello World' program that creates a Mathematica Notebook file.
I have this working program.
package graphica;
import com.wolfram.jlink.*;
/**
*
* #author Nilo
*/
public class MathematicaTester {
public static void main(String[] args) {
KernelLink ml = null;
String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\SystemFiles\\Links\\JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir);
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
ml.discardAnswer();
String expr = "Sum[k^2,{k,1,11}]";
ml.evaluate(expr);
ml.waitForAnswer();
String x = ml.getString();
System.out.println("Result = " + x);
} catch (MathLinkException e) {
System.out.println("Fatal error opening link: " +
e.getMessage());
return;
}
}
}
When I run this I get the following -expected- output.
run:
Result = 506
BUILD SUCCESSFUL (total time: 2 seconds)
QUESTION:
I want to change this program so that a Mathematica Notebook is created. The program will ( eventually ) add line after line of mma command strings. It would be nice if a Mathematica frontend is started at the same time and that the mma code is evaluated by request from the Java program. Essential is the creation of a Notebook that can be opened later by the mma front-end.
A method for creating a formatted notebook file is shown here:
How to create a notebook with a properly formatted expression
You can box format your Mathematica code (mathCommand) using a kernel call, e.g.
String mathCommand = "Plot[Sin[x], {x, 0, 6}]";
mathCommand = "FullForm[ToBoxes[Defer[" + mathCommand + "]]]";
MathKernel kernel = new MathKernel();
kernel.Compute(mathCommand);
mathCommand = kernel.Result.ToString();
Then encapsulate it like so, and save it with .nb extension.
Notebook[{Cell[BoxData[
... ( inserted box-formatted output ) ...
], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]
Mathematica notebooks are plaintext files with structures like
Notebook[{Cell[],Cell[]}]
You can work out the required structure by viewing them with a text editor. Assuming you can get Java to create a text file, save it with a .nb file name ending, and invoke the command-line version of Mathematica, then what you want should be doable. You will probably want to set the input cells to initialization type.
It took some research but I managed to answer the question myself.
package graphica;
import com.wolfram.jlink.*;
/**
*
* #author Nilo
*/
public class MathematicaTester {
public static void main(String[] args) {
KernelLink ml = null;
String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\ \SystemFiles\\Links\\JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir);
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
//test-1
ml.discardAnswer();
String expr = "Sum[k,{k,1,11}]";
ml.evaluate(expr);
ml.waitForAnswer();
String x = ml.getString();
System.out.println("Result = " + x);
//test-2
expr = "UsingFrontEnd[nb=NotebookPut[Notebook[{Cell[\"Graphics3D[Cuboid[]]\", \"Input\"]}]]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
expr = "UsingFrontEnd[NotebookSave[nb,\"TERRANOVA1\"]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
} catch (MathLinkException e) {
System.out.println("Fatal error opening link: " +
e.getMessage());
return;
}
}
}

Determining object types in Qt

I have a series of QTextEdits and QLineEdits connected to a slot through a QSignalMapper(which emits a textChanged(QWidget*) signal). When the connected slot is called (pasted below), I need to be able to differentiate between the two so I know whether to call the text() or toPlainText() function. What's the easiest way to determine the subclass type of a QWidget?
void MainWindow::changed(QWidget *sender)
{
QTextEdit *temp = qobject_cast<QTextEdit *>(sender);
QString currentText = temp->toPlainText(); // or temp->text() if its
// a QLineEdit...
if(currentText.compare(""))
{
...
}
else
{
...
}
}
I was considering using try-catch but Qt doesn't seem to have very extensive support for Exceptions... Any ideas?
Actually, your solution is already almost there. In fact, qobject_cast will return NULL if it can't perform the cast. So try it on one of the classes, if it's NULL, try it on the other:
QString text;
QTextEdit *textEdit = qobject_cast<QTextEdit*>(sender);
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender);
if (textEdit) {
text = textEdit->toPlainText();
} else if (lineEdit) {
text = lineEdit->text();
} else {
// Return an error
}
You can also use sender->metaObject()->className() so you won't make unnecesary casts. Specially if you have a lot of classes to test. The code will be like this:
QString text;
QString senderClass = sender->metaObject()->className();
if (senderClass == "QTextEdit") {
QTextEdit *textEdit = qobject_cast<QTextEdit*>(sender);
text = textEdit->toPlainText();
} else if (senderClass == "QLineEdit") {
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender);
text = lineEdit->text();
} else {
// Return an error
}
I know is an old question but I leave this answer just in case it would be useful for somebody...

Resources