Using VIM to fix badly formatted code - vim

Ihave this piece of code that i need to 'format/indent'.. Can you please suggest a fix?
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PrimeSearcher extends HttpServlet implements Runnable { long lastprime = 0; // last prime found Date lastprimeModified = new Date(); // when it was found Thread searcher; // background search thread public void init(ServletConfig config) throws ServletException { super.init(config); // always! searcher = new Thread(this); searcher.setPriority(Thread.MIN_PRIORITY); // be a good citizen searcher.start(); } public void run() { // QTTTBBBMMMTTTOOO long candidate = 1000000000000001L; // one quadrillion and one // Begin loop searching for primes while (true) { // search forever if (isPrime(candidate)) { lastprime = candidate; // new prime lastprimeModified = new Date(); // new "prime time" } candidate += 2; // evens aren't prime // Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try { searcher.sleep(200); } catch (InterruptedException ignored) { } } } private static boolean isPrime(long candidate) { // Try dividing the number by all odd numbers between 3 and its sqrt double sqrt = Math.sqrt(candidate); for (long i = 3; i <= sqrt; i += 2) { if (candidate % i == 0) return false; // found a factor } // Wasn't evenly divisible, so it's prime return true; } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); if (lastprime == 0) { out.println("Still searching for first prime..."); } else { out.println("The last prime discovered was " + lastprime); out.println(" at " + lastprimeModified); } } public void destroy() { searcher.stop(); } }

Break lines around brackets:
:%s/[{}]/\r&\r/g
Break lines after semicolons:
:%s/;/&\r/g
Remove empty lines:
:g/^\s*$/d
Indent:
:set ft=java
gg=G
After this, you need to tweak the code just a little to split comments.
import java.io.;
import java.util.;
import javax.servlet.;
import javax.servlet.http.;
public class PrimeSearcher extends HttpServlet implements Runnable
{
long lastprime = 0;
// last prime found Date lastprimeModified = new Date();
// when it was found Thread searcher;
// background search thread public void init(ServletConfig config) throws ServletException
{
super.init(config);
// always! searcher = new Thread(this);
searcher.setPriority(Thread.MIN_PRIORITY);
// be a good citizen searcher.start();
}
public void run()
{
// QTTTBBBMMMTTTOOO long candidate = 1000000000000001L;
// one quadrillion and one // Begin loop searching for primes while (true)
{
// search forever if (isPrime(candidate))
{
lastprime = candidate;
// new prime lastprimeModified = new Date();
// new "prime time"
}
candidate += 2;
// evens aren't prime // Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try
{
searcher.sleep(200);
}
catch (InterruptedException ignored)
{
}
}
}
private static boolean isPrime(long candidate)
{
// Try dividing the number by all odd numbers between 3 and its sqrt double sqrt = Math.sqrt(candidate);
for (long i = 3;
i <= sqrt;
i += 2)
{
if (candidate % i == 0) return false;
// found a factor
}
// Wasn't evenly divisible, so it's prime return true;
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
if (lastprime == 0)
{
out.println("Still searching for first prime...");
}
else
{
out.println("The last prime discovered was " + lastprime);
out.println(" at " + lastprimeModified);
}
}
public void destroy()
{
searcher.stop();
}
}

You could at least start by replacing all ; with a ; + line-break:
:%s/;/;\n\r/g
Then you could replace all { with { + line-break:
:%s/{/{\n\r/g
Then replace all } with } + line-break:
:%s/}/}\n\r/g
This will get you started. You'd still have to clean up all the indentation. Too bad there isn't ReSharper for Java (that I know of anyway).

Use:
http://www.prettyprinter.de/
import java.io.;
import java.util.;
import javax.servlet.;
import javax.servlet.http.;
public class PrimeSearcher extends HttpServlet implements Runnable {
long lastprime = 0;
// last prime found Date lastprimeModified = new Date();
// when it was found Thread searcher;
// background search thread public void init(ServletConfig config) throws ServletException {
super.init(config);
// always! searcher = new Thread(this);
searcher.setPriority(Thread.MIN_PRIORITY);
// be a good citizen searcher.start();
}
public void run() {
// QTTTBBBMMMTTTOOO long candidate = 1000000000000001L;
// one quadrillion and one // Begin loop searching for primes while (true) {
// search forever if (isPrime(candidate)) {
lastprime = candidate;
// new prime lastprimeModified = new Date();
// new "prime time"
}
candidate += 2;
// evens aren't prime // Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try {
searcher.sleep(200);
}
catch (InterruptedException ignored) {
}
}
}
private static boolean isPrime(long candidate) {
// Try dividing the number by all odd numbers between 3 and its sqrt double sqrt = Math.sqrt(candidate);
for (long i = 3;
i <
= sqrt;
i += 2) {
if (candidate % i == 0) return false;
// found a factor
}
// Wasn't evenly divisible, so it's prime return true;
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
if (lastprime == 0) {
out.println("Still searching for first prime...");
}
else {
out.println("The last prime discovered was " + lastprime);
out.println(" at " + lastprimeModified);
}
}
public void destroy() {
searcher.stop();
}
}
Tweak the settings to get it looking how you want.

Probably you best proceed as following:
Add line breaks after characters like ;, { and }:
:s/[;{}]/\0\r/g
Go through the code and fix bad line breaks. For example comment lines started with // don't usually end in some special character and will need manual splitting
Fix the indentation with =. Use it with some movement command like =G or select the code in visual mode and then hit = to indent it.

Related

How to avoid java.util.NoSuchElementException

The code below is giving me the error java.util.NoSuchElementException right after I Ctrl+Z
to indicate that the user input is complete. By the looks of it seems as if it does not know how to just end one method without messing with the other scanner object.
I try the hasNext method and I ended up with an infinite loop, either way is not working. As a requirement for this assignment I need to be able to tell the user to use Ctrl+Z or D depending on the operating system. Also I need to be able to read from a text file and save the final tree to a text file please help.
/* sample input:
CSCI3320
project
personal
1 HW1
1 HW2
1 2 MSS.java
2 p1.java
*/
import java.util.Scanner;
import java.util.StringTokenizer;
public class Directory {
private static TreeNode root = new TreeNode("/", null, null);
public static void main(String[] args) {
userMenu();
System.out.println("The directory is displayed as follows:");
root.listAll(0);
}
private static void userMenu(){ //Displays users menu
Scanner userInput = new Scanner(System.in);//Scanner option
int option = 0;
do{ //I believe the problem is here since I am not using userInput.Next()
System.out.println("\n 1. add files from user inputs ");
System.out.println("\n 2. display the whole directory ");
System.out.println("\n 3. display the size of directory ");
System.out.println("\n 0. exit");
System.out.println("\n Please give a selection [0-3]: ");
option = userInput.nextInt();
switch(option){
case 1: addFileFromUser();
break;
case 2: System.out.println("The directory is displayed as follows:");
root.listAll(0);
break;
case 3: System.out.printf("The size of the directory is %d.\n", root.size());
break;
default:
break;
}
}while( option !=0);
userInput.close();
}
private static void addFileFromUser() {
System.out.println("To terminate inp1ut, type the correct end-of-file indicator ");
System.out.println("when you are prompted to enter input.");
System.out.println("On UNIX/Linux/Mac OS X type <ctrl> d");
System.out.println("On Windows type <ctrl> z");
Scanner input = new Scanner(System.in);
while (input.hasNext()) { //hasNext being used Crtl Z is required to break
addFileIntoDirectory(input); // out of the loop.
}
input.close();
}
private static void addFileIntoDirectory(Scanner input) {
String line = input.nextLine();
if (line.trim().equals("")) return;
StringTokenizer tokens = new StringTokenizer(line);
int n = tokens.countTokens() - 1;
TreeNode p = root;
while (n > 0 && p.isDirectory()) {
int a = Integer.valueOf( tokens.nextToken() );
p = p.getFirstChild();
while (a > 1 && p != null) {
p = p.getNextSibling();
a--;
}
n--;
}
String name = tokens.nextToken();
TreeNode newNode = new TreeNode(name, null, null);
if (p.getFirstChild() == null) {
p.setFirstChild(newNode);
}
else {
p = p.getFirstChild();
while (p.getNextSibling() != null) {
p = p.getNextSibling();
}
p.setNextSibling(newNode);
}
}
private static class TreeNode {
private String element;
private TreeNode firstChild;
private TreeNode nextSibling;
public TreeNode(String e, TreeNode f, TreeNode s) {
setElement(e);
setFirstChild(f);
setNextSibling(s);
}
public void listAll(int i) {
for (int k = 0; k < i; k++) {
System.out.print('\t');
}
System.out.println(getElement());
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
t.listAll(i+1);
t = t.getNextSibling();
}
}
}
public int size() {
int s = 1;
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
s += t.size();
t = t.getNextSibling();
}
}
return s;
}
public void setElement(String e) {
element = e;
}
public String getElement() {
return element;
}
public boolean isDirectory() {
return getFirstChild() != null;
}
public void setFirstChild(TreeNode f) {
firstChild = f;
}
public TreeNode getFirstChild() {
return firstChild;
}
public void setNextSibling(TreeNode s) {
nextSibling = s;
}
public TreeNode getNextSibling() {
return nextSibling;
}
}
}
Exception Details:
/*Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Directory.userMenu(Directory.java:36)
at Directory.main(Directory.java:21)*/
Your problem is this line:
option = userInput.nextInt(); //line 24
If you read the Javadoc, you will find that the nextInt() method can throw a NoSuchElementException if the input is exhausted. In other words, there is no next integer to get. Why is this happening in your code? Because you this line is in a loop once that first iteration completes (on the outer while loop) your initial input selection has been consumed. Since this is a homework, I am not going to write the code. But, if you remove the loop, you know this works at least once. Once you try to loop, it breaks. So I will give you these hints:
Change the do/while to a while loop.
Prompt the user once outside the loop.
Recreate the prompt and recapture the user input inside the loop.
For example, the code below can be used for the basis of your outer loop.
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Guess the secret number: (Hint: the secret number is 1)");
int guess = input.nextInt();
while (guess != 1) {
System.out.println("Wrong guess. Try again: ");
guess = input.nextInt();
}
System.out.println("Success");
input.close();
}
}
The reason why this works is because I don't reuse the same, exhausted, scanner input object to get the next integer. In your example, the initial input is inside the loop. The second time around, that input has already been consumed. Follow this pattern and you should be able to complete your assignment.

List getting threadsafe with removing items

I'm trying to remove items from a list until its empty with multithreading.
Code:
public void testUsers() {
final List<User> users = userDao.findAll();
final int availableProcessors = Runtime.getRuntime().availableProcessors() * multiplier;
final List<String> loggingList = Lists.newArrayList();
final List<Integer> sizeChecked = Lists.newArrayList();
int totalSizeChecked = 0;
int sizeList = users.size();
ExecutorService executorService = Executors.newFixedThreadPool(availableProcessors);
for (int i = 0; i < availableProcessors; i++) {
createThread(executorService, users, loggingList, sizeChecked);
}
executorService.shutdown();
try {
// wait for all threads to die
executorService.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException ex) {
}
for (Integer count : sizeChecked) {
totalSizeChecked += count;
}
Assert.assertTrue(totalSizeChecked==sizeList);
}
private void createThread(ExecutorService executorService, final List<User> users,
final Collection<String> loggingList, final List<Integer> sizeChecked) {
executorService.execute(new Runnable() {
#Override
public void run() {
int totalChecked = 0;
while (!users.isEmpty()) {
User user = null;
synchronized (users) {
if (!users.isEmpty()) {
user = users.remove(0);
}
}
totalChecked++;
if (user != null) {
String reason = checkUser(user);
if (reason != null) {
loggingList.add(reason);
}
} else {
LOGGER.info("user is null");
}
}
sizeChecked.add(totalChecked);
}
});
}
Now I was thinking this couldn't be so wrong cause I made the list synchronised for removing the first item.
I'm testing with a multiplier of 6.(on prod it will be lowered to 1-2)
I get this in the email :
The batch was not correctly executed.
Size of accounts that must be checked : 28499. Size of accounts that have been checked: 25869
What do I wrong to get it threadsafe?
List<Integer> sizeChecked is not thread safe. Therefore you cannot add elements in parallel in it.
Synchronize your add operation or use a thread-safe structure. If sizeChecked is just a counter, use an AtomicLong instead and make each thread increment it.

getting list of broken constraints for final best solution in drools-planner

I'm using drools-planner-5.4.0.CR1 and I wanna get list of broken constraints for final best solution
and also looked of examples of 5.4.0.CR1
I've implemented like in example but it returns empty list, in other words getScoreDetailList().size() is equal to 0, but solution.getScore() is equal to -54.
is there any suggestions?
public class SomeClass {
...
private volatile Solver solver;
private ScoreDirector scoreDirector;
...
public void someMethod() {
SolverFactory solverFactory = new XmlSolverFactory(SOLVER_CONFIG);
solver = solverFactory.buildSolver();
scoreDirector = solver.getScoreDirectorFactory().buildScoreDirector();
...
this.scoreDirector.setWorkingSolution(solution);
this.solver.setPlanningProblem(this.scoreDirector.getWorkingSolution());
this.solver.solve();
SomeSolution solution = (SomeSolution) solver.getBestSolution();
this.scoreDirector.setWorkingSolution(solution);
System.out.println( "Score: " + solution.getScore());
System.out.println( "getScoreDetailList size:" + getScoreDetailList().size());
}
public List<ScoreDetail> getScoreDetailList() {
if (!(scoreDirector instanceof DroolsScoreDirector)) {
return null;
}
Map<String, ScoreDetail> scoreDetailMap = new HashMap<String, ScoreDetail>();
WorkingMemory workingMemory = ((DroolsScoreDirector) scoreDirector).getWorkingMemory();
if (workingMemory == null) {
return Collections.emptyList();
}
Iterator<ConstraintOccurrence> it = (Iterator<ConstraintOccurrence>) workingMemory.iterateObjects(
new ClassObjectFilter(ConstraintOccurrence.class));
while (it.hasNext()) {
ConstraintOccurrence constraintOccurrence = it.next();
ScoreDetail scoreDetail = scoreDetailMap.get(constraintOccurrence.getRuleId());
if (scoreDetail == null) {
scoreDetail = new ScoreDetail(constraintOccurrence.getRuleId(), constraintOccurrence.getConstraintType());
scoreDetailMap.put(constraintOccurrence.getRuleId(), scoreDetail);
}
scoreDetail.addConstraintOccurrence(constraintOccurrence);
}
List<ScoreDetail> scoreDetailList = new ArrayList<ScoreDetail>(scoreDetailMap.values());
Collections.sort(scoreDetailList);
return scoreDetailList;
}
}
After
this.scoreDirector.setWorkingSolution(solution);
you forgot to call
this.scoreDirector.calculateScore();
I 'll docs about using Solver.getScoreDirectorFactory() in 5.4.0.Final.

Validation in swt text

I would like to validate numbers input in text box.
I want the user to input only integer, decimal in the box between a maximum and minimum values.
How can I make sure of this?
Thank you.
Use a VerifyListener as this will handle paste, backspace, replace.....
E.g.
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
You can register a ModifyListener with the text control and use it to validate the number.
txt.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent event) {
String txt = ((Text) event.getSource()).getText();
try {
int num = Integer.parseInt(txt);
// Checks on num
} catch (NumberFormatException e) {
// Show error
}
}
});
You could also use addVerifyListener to prevent certain characters being entered. In the event passed into that method there is a "doit" field. If you set that to false it prevents the current edit.
Integer validation in SWT
text = new Text(this, SWT.BORDER);
text.setLayoutData(gridData);
s=text.getText();
this.setLayout(new GridLayout());
text.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
});
If you only want to allow Integer values you could use a Spinner instead of a text field.
For the validation of Double values you have to consider that characters like E may be included in Doubles and that partial input like "4e-" should be valid while typing. Such partial expressions will give a NumberFormatException for Double.parseDouble(partialExpression)
Also see my answer at following related question:
How to set a Mask to a SWT Text to only allow Decimals
1.create a utill class implement verify listener
2.override verifytext method
3.implement your logic
4.create a object of utill class where you want to use verify listener (on text)
5.text.addverifylistener(utillclassobject)
Example :-
1. utill class:-
public class UtillVerifyListener implements VerifyListener {
#Override
public void verifyText(VerifyEvent e) {
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
2.use of verifylistener in other class
public class TestVerifyListenerOne {
public void createContents(Composite parent){
UtillVerifyListener listener=new UtillVerifyListener();
textOne = new Text(composite, SWT.BORDER);
textOne .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textOne .addVerifyListener(listener)
textTwo = new Text(composite, SWT.BORDER);
textTwo .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textTwo .addVerifyListener(listener);
}
}
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
Text text = (Text) e.getSource();
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
boolean isValid = true;
try {
if(! "".equals(newS)){
Float.parseFloat(newS);
}
} catch (NumberFormatException ex) {
isValid = false;
}
e.doit = isValid;
}
});

Implementing Runnable and extending thread

I have been given the task of running two threads one using extends and one using implements runnable, the output is meant to be similair to this
F(0)
F(1)
F(2)
.........
S(0)
S(1)
S(2)
So far im getting
F(0)
S(1)
F(1)
F(2)
S(2)
public class Fast implements Runnable
{
/** Creates a new instance of Fast */
public void run()
{
for(int i = 0; i <= 9; i++)
{
try
{
System.out.println("F("+ i + ")");
Thread.sleep(200);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
and
public class Slow extends Thread
{
/** Creates a new instance of Slow */
public void run()
{
for(int i = 0; i <= 6; i++)
{
try
{
System.out.println("S("+ i + ")");
Thread.sleep(400);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
With the main
public class Main
{
public static void main(String args[])
{
Fast f = new Fast();
Slow s = new Slow();
Thread ft = new Thread(f);
ft.start();
s.start();
}
}
It seems like you want to get Slow to run after Fast? Your output is pretty much what i would expect. Eventually F will finish faster (just 2000ms) and S will still be running (2800ms). I'm not what this assignment has got to do with implementing Runnable or extending Thread since they give you the same end-result.
If you want F to finish completely before S you need to join on F first, like this:
Fast f = new Fast();
Slow s = new Slow();
Thread ft = new Thread(f);
ft.start();
ft.join();
s.start();
That will wait for ft to complete before even starting S giving you the desired output F1, F2,... S1,S2,...

Resources