Java 7 closure syntax - java

I download the last Java build b96- Feature Complete for testing the new JDK features
but I can't figure out which syntax using for testing closures!
Can I test it?
Which syntax has been approved in the final release?

I can't be certain, but I think this syntax:
// function expressions
#(int i, String s) {
System.println.out(s);
return i + s.length();
}
// function expressions
#(int i, String s) (i + s.length())
// function types
#int(int, String)
Is going to make it through as per http://docs.google.com/Doc?id=ddhp95vd_0f7mcns

To answer your question, no final syntax has been approved and, despite M8 being listed as the feature-complete milestone, it doesn't have all the proposed features. You can read here about the feature in its current form, but much discussion is going on now and it has quite a ways to go. Additionally, the syntax is going to be revisited and likely changed (at least some) later, once more pressing issues are worked out.
Also, project-lambda code is being worked on in a fork of the main line JDK7 (I believe), so I don't think any of it would be in the build you downloaded.

Related

Removing alphabetical characters from a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am new to java. Trying to create a function to remove a given string "arg" from myString which is previously set and return a new string not affecting myString. I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string. so if arg has a 7 in it that should still be included in the final string. characters being removed are case insensitive as well.
I have edited the previous code and post, i can now run my code but I am not getting the correct results, I am trying to remove all numbers from arg before using it to remove all the characters. myString method is previously defined and working properly to return a string.
For examplecurrent string "my lucky numbers are 6, 8, and 19.", calling remove("ra6") would return "my lucky numbes e 6, 8, nd 19."
or "my lucky numbers are 6, 8, and 19.", calling remove("6,.") would return "my lucky numbers are 6, 8, and 19."
thank you!
public String remove(String arg) {
char[] charArray=arg.toCharArray();
String result="";
String newString="";
for (int i = 0; i < charArray.length; i++) {
if (!Character.isDigit(charArray[i])) {
result = result + charArray[i];
return result;}}
if (myString==null || myString=="") {
this.myString="";}
if (myString!=null) {
newString= myString.replaceAll(result,"");}
return newString;
}
Here is one way using streams. Just create a stream of characters via the chars() method and allow only letters to pass thru. Then each character to a String and join them together. Then remove that result from the original passed string.
String myString = "abcdTLK123efgh";
String arg = "TLK###123";
String result = remove(arg, myString);
System.out.println("Result = " + result);
prints
Result = abcd123efgh
The method
I modified the method to accept two strings.
the one to remove characters(arg).
and the from which to remove modified arg from myString
it works by
streaming all the characters of arg.
filtering out all but letters and digits
joining them as a string.
and then removing that filtered string from the myString.
public static String remove(String arg, String myString) {
if (myString == null || myString.isBlank()) {
return "";
}
return arg.chars().filter(
ch -> Character.isLetter(ch))
.mapToObj(Character::toString)
.collect(Collectors.collectingAndThen(
Collectors.joining(),
str -> myString.replace(str, "")));
}
Note: If myString is null then assigning an empty string to it will contain nothing to change. Nor an initial empty string. So I just returned an empty String if those conditions existed.
I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string.
The good news is that you can solve it yourself.
The bad news is that the code above is in such a mess that it would be difficult for you to fix it by yourself. (Given your current level understand of Java syntax, way of working, etcetera.)
(Also, there is a long more wrong than the "if it were not for ..." ...)
So here is what I advise you to do.
Save a copy of the current version of the (entire) class somewhere safe so that you can look it again if you need to, or revert to it.
Develop a model of what the method needs to do and how it will do it; see below.
Delete all lines of code between the first { and last } shown in the question. Yes. Delete them.
Compose the new version of the code, one line at a time. As follows:
Add a line.
Compile the code (or let the IDE compile it for you).
Read the compilation error(s) that just appeared.
Understand the compilation errors.
Make the necessary changes to fix the compilation errors. Don't rely on your IDE's facility for suggesting corrections. (The IDE doesn't understand your code, what you are going to add next, or what you are trying to achieve. Its suggestions are liable to be unhelpful or even wrong.)
Repeat until you have dealt with all of the compilation errors that were introduced.
Now you are ready to add another line.
Once you have a complete method, you can then try to run it.
You will most likely find that the code doesn't work. But at least it will be valid Java code. And in the process of doing 4. above, you will (hopefully!) have learned enough Java syntax to be able to read and understand the code that you wrote. And 2. will help you understand what the code you are writing should do.
My other observation is that it looks like you have been adding and removing statements to this code with no clear understanding of what they do or what needs to happen. Maybe you started with some code that did something else ... correctly ... but it is hard to tell now.
Changing things randomly to try to make the code work is not a sensible approach. It rarely works. You need to have a model (or plan) in your head or on paper (e.g. as pseudo-code or flowcharts) about how the code ought to work.
Programming is about 1) developing the model, then 2) translating the model into code. The first part is the hard (and interesting) part. But if you skip the first part, the second part is an essentially random process, and unlikely to succeed.
The problem with starting with someone else's code is that you risk not developing a mental model of how that code works. Let alone the model that you are aiming for.
Finally, a professional programmer will use a version control system for their source code, and make relatively frequent commits of their code to their repository. Among other things, that allows them to quickly "roll back" to an earlier version if they need to, or keep track of exactly what they changed.
It is probably too early for you to learn about (say) using Git ... but it would help you solve your problem if you could just "roll back" all of the changes where you were "messing" with the code to get it to work.

Apache Solr - How to index source code files

I want to write a program which is able to search in source code files for specific patterns ... in other words: the input is a piece of code for example:
int fib (int i) {
int pred, result, temp;
pred = 1;
result = 0;
while (i > 0) {
temp = pred + result;
result = pred;
pred = temp;
i = i-1;
}
return(result);
}
The output are files that contain this piece of code or similar code.
In the Open Source World code is reused in other projects. Especially libraries are often copied into projects. To make bug fixing easier I need to be able to know in which projects specific libraries or code is used.
Therefore I want to try to use apache solr. I don't know if its a good idea (I am would be happy about everything that could help me)
My plan is to index my source code files ... therefore I need some tools? to tokenize source code files. Like give me all names of functions, variables etc. The output I can use to feed the solr index. But I am not sure maybe there are already tokenizer or dataimporthandler in apache solr that do the trick?
I am not sure if this can be done using solr, since different projects may use different naming conventions.
Have a look at the link below if it helps:
Tools for Code Seacrh
Apache Solr is probably not the best option here. You have more like tree/graph comparison problem than string comparison here. I'd recommend using specialized tools for that.
If you do want to do it by hand, you basically need a parser with tree traversal API or some other way to get the stream/tree of tokens. This would very much depend on the language you are parsing. Something like ANTLR might be one way to go if it has the grammar for your language.
Alternatively, you could extract the information from the compiled code, if it is structured enough. For Java, something like ASM may do the job.
But you would still have to figure out the representation. Answering - to yourself - the question of how do I know these two pieces of code are similar should be the right first step.

Byte alignment problem using Preon

Hello everybody :)
I am currently using preon for a spare time project, and I have encountered the following problem: I am trying to read a fixed length String with the following code:
#Bound int string_size;
#ByteAlign #BoundString(size = "string_size") my_string;
The file specification expects a variable padding, so that the next block's offset is a multiple of 4.
For example, if string_size = 5, then 3 null bytes will be added, and so on. I initially thought that the #ByteAlign annotation did exactly this, however, looking into the source code, I realized that it wasn't the case.
I tried to make this quick fix:
#If ("string_size % 4 == 2") #BoundList(size = "2", type = Byte.class) byte[] padding;
Sadly, Limbo doesn't seem to support the "%" operator. Is there a way around this?
(Also, where/how can I get the latest version?)
Thanks in advance.
Preon currently doesn't have a solution for your issue built-in. As you said, it's expression language doesn't have a modulo operator, and it looks like you could use one. You can however implement your own CodecDecorator, which is probably the thing you want to do. You could implement a CodecDecorator that inserts a Codec reading a couple of extrac bytes after it decoded the value.
The latest version of Preon is at Codehaus:
git://git.codehaus.org/preon.git
You could checkout the head, but there's also a separate branch called PREON-35 that has the bits for doing what is discussed over here.

Is the Google Annotations Gallery useful in production code?

I could actually see a use for the Google Annotations Gallery in real code:
Stumble across code that somehow works
beyond all reason? Life's short. Mark
it with #Magic and move on:
#Magic
public static int negate(int n) {
return new Byte((byte) 0xFF).hashCode()
/ (int) (short) '\uFFFF' * ~0
* Character.digit ('0', 0) * n
* (Integer.MAX_VALUE * 2 + 1)
/ (Byte.MIN_VALUE >> 7) * (~1 | 1);
}
This is a serious question. Could this be used in an actual code review?
Quite. Well, not all of them, but many could be substitutes for longer comments.
That holds true for not too many of these annotations, but some (as in your example) could be handy.
It may be said that these annotations present the most common comments in a shorter and perhaps more readable way.
You can later process them, and add tresholds for, say, the number of #Magic annotations. If a project becomes too "magic", measures should be taken.
It would be easier to use comments with a key such as "MAGIC", then work with those. Hudson and Eclipse and other tools can count or mark those occurrences.
I can definitely see how the #CarbonFootprint would fit into several client's CSR policies, and the #WTF("comment") annotation would be really handy when you're working on a new project where you're not sure whether a certain piece of code actually is needed to work around some crazy bug/corner-condition or if it's just random, left-over crap that no one knew how to write better at the time.
FYI, Sonar seems to now include a better revision plugin.
Anyway, were you not to guess, i think the short project name is clear enough about this project's intentions : gag the annotations for what they can become when left free : an equivalent to the oh-so-y2k XML hell.
I guess some people may have missed the acronym and the date of the that Google Annotation Gallery (GAG) on April 1st... or maybe in some countries it's not a national day for jokes, or gags...

Automatically catching the use of =+ rather than += in Java

I have this horrible habit of typing the below and not catching it until well into testing:
int i = 1;
int j = 2;
i =+ j; //i equals 2, not 3 as intended; assign only, + is unary and works on the j
The correct version, of course, would be
int i = 1;
int j = 2;
i += j; //i equals 3, as intended with additive & assignment compound operator
I have made this mistake a zillion times. It would not surprise me of there is some code out there with a bug in it that escaped a test case. There has just got to be a way to prevent this systematically. Any ideas?
Regularly use tools like PMD and/or Checkstyle. Ideally as part of your build process/continuous integration.
You might have to define a custom rule for this, because I don't know if any of those tools recognizes this as a problem by default.
This will not only catch this problem, but also hint at a lot of other potential problems as well.
Depending on what IDE you use, if it does syntax highlighting, I would modify the highlighting so that it looks for the pattern =+ and makes it some awful-to-look-at color.
Use standard text utilities, such as
find . -name \*.java -exec grep -H "=+" {} \;
As balpha commented, an easy way to find this would be to grep for the "=+" in code. It is probably never intentional.
I think you have to be rigorous in your unit testing. At the moment you're worried about one particular issue, but good unit tests will capture most issues (ignoring threading/loading etc.).
You have to decompose your classes/methods such that you can test each chunk of functionality and ensure complete (or as near as you can) coverage.
Clover (commercial) or Emma (open source) will manage code coverage for you.

Categories