I have an android java pattern that I would like to convert to something similar in flutter. It's pretty straight forward but I am having difficulty finding a clear example. What this involves is having a utility class that does repetitive string manipulation routines that I can use anywhere in the project.
Here is an example. I use the CapEachWord routine in a lot of source members. See the arrow below.
import com.auto.accident.report.util.utils;
#Override
public void onResults(Bundle results) {
ArrayList<String> result = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
switch (REQ_CODE) {
case REQ_CODE_NOTE_SUBJECT: {
DA_RESULT = utils.capEachWord(DA_RESULT); <-------------------
tieAN_SUBJECT.setText(DA_RESULT);
startNoteInput();
break;
}
}
CapEachWord resides in a source member called utils and looks like this.
public class utils {
public static String capEachWord(String DA_RESULT) {
int splitLength;
int index = 0;
String[] words = DA_RESULT.split(" ");
splitLength = words.length;
StringBuilder DA_RESULTBuilder = new StringBuilder();
while (index < splitLength) {
int DA_SIZE = words[index].length();
words[index] = words[index].substring(0,
1).toUpperCase() +
words[index].substring(1,
DA_SIZE);
DA_RESULTBuilder.append(words[index]);
if (index != splitLength) {
DA_RESULTBuilder.append(" ");
}
index++;
}
DA_RESULT = DA_RESULTBuilder.toString();
return DA_RESULT;
}
}
What I need to know is how to properly include the utils, structure the utils member and
and ask for the conversion result. The actual conversion code I can work out myself.
You can include your utils file with import './utils.dart'; (by relative path) or import 'package:your_package_name:path/to/utils.dart'; (for path from lib folder).
In your case I would make just class Utils or something, with static methods that I could use.
Usage would be simple after proper importing to some source file:
//...
myString = Utils.capEachWord(otherString);
Related
The target class is:
class Example{
public void m(){
System.out.println("Hello" + 1);
}
}
I want to get the full string of MethodInvocation "System.out.println("Hello" + 1)" for some regex check. How to write?
public class Rule extends BaseTreeVisitor implements JavaFileScanner {
#Override
public void visitMethodInvocation(MethodInvocationTree tree) {
//get the string of MethodInvocation
//some regex check
super.visitMethodInvocation(tree);
}
}
I wrote some code inspection rules using eclipse jdt and idea psi whose expression tree node has these attributes. I wonder why sonar's just has first and last token instead.
Thanks!
An old question, but I have a solution.
This works for any sort of tree.
#Override
public void visitMethodInvocation(MethodInvocationTree tree) {
int firstLine = tree.firstToken().line();
int lastLine = tree.lastToken().line();
String rawText = getRelevantLines(firstLine, lastLine);
// do your thing here with rawText
}
private String getRelevantLines(int startLine, int endLine) {
StringBuilder builder = new StringBuilder();
context.getFileLines().subList(startLine, endLine).forEach(builder::append);
return builder.toString();
}
If you want to refine further, you can also use firstToken().column or perhaps use the method name in your regex.
If you want more lines/bigger scope, just use the parent of that tree tree.parent()
This will also handle cases where the expression/params/etc span multiple lines.
There might be a better way... but I don't know of any other way. May update if I figure out something better.
I am developing a slots machine game as part of an assignment.
I have two functions that I need to link together, shown below:
public static void DisplayOnScreen(){
int LeftVal = GenerateNumber();
int MidVal = GenerateNumber();
int RightVal = GenerateNumber();
FruitVal1 = showFruit[LeftVal];
FruitVal2 = showFruit[MidVal];
FruitVal3 = showFruit[RightVal];
System.out.println(" |",FruitVal1, "|", FruitVal2, "|", FruitVal3, "| ");
--
public String showFruit(int inVal) {
String[] strFruitArr = new String[6];
strFruitArr[0] = "Orange";
strFruitArr[1] = "Pear";
strFruitArr[2] = "Banana";
strFruitArr[3] = "Cherry";
strFruitArr[4] = "Lemon";
strFruitArr[5] = "Apple";
strFruitArr[6] = "Bar";
while(inVal > 0){
if(inVal == 0){
return strFruitArr[0];
}
else if (inVal == 7){
return strFruitArr[6];
}
else{
return strFruitArr[inVal];
}
}
}
As you can see, each "FruitVal" is assigned by taking for example "LeftVal" which is a randomly generated number, and applying that to one of the fruits from the "showFruit" function. I'm aware this is done completely wrong however i do not understand the different java functions to do so.
Could someone explain the basic java functions e.g. 'public static void' and try and help implement them in to this code correctly.
If anyone wants to see the full program code then please do ask, I wasn't sure if the full code was necessary, however it is only short.
Learn Java coding standards. Your code will be more readable.
You link them by having one method return the data that the other needs to have passed to it.
public void displayFruitOnScreen(String [] fruit) {
// display here
}
public String [] getFruit() {
// populate the fruit array here
}
Neither of these is static; they are associated with some instance of a Java class.
I've implemented my own custom classifier for Weka, which inherits from Classifier and implements Serializable and also OptionHandler.
At the moment i've been able to run the classifier from the Weka UI perfectly, but without parameters. I know that i need to implement the following methods in order to see the options in the UI:
public void setOptions(String [] options) throws Exception
public String [] getOptions()
public Enumeration listOptions()
I've implemented getOptions with some dummy code and it's being perfectly called by the UI (I used a System.out.println to log this). And I also implemented a dummy code for listOptions but it's never being called.
When I try to select the options for my algorithm by the UI i only see the "Debug" option. Do you have any ideas how to solve this problem and see my options by the UI?
Basically the thing that i want to do is to run my algorithm from Weka but using custom options/parameters.
I've read this document but i think it's not very useful:
http://weka.wikispaces.com/Writing+your+own+Classifier+(post+3.5.2)
Do you have any idea or example to solve this?
I had the same problem.
I realized by chance :) that if I use the get and set methods instead of just accessing the attributes it works!
More clearly, for an attribute named "threshold" represented by "T" as an option:
This code doesn't work:
public String[] getOptions() {
String[] options = new String[3];
int current = 0;
options[current++] = "-T";
options[current++] = "" + threshold;
while (current < options.length) {
options[current++] = "";
}
return options;
}
And this code works:
public String[] getOptions() {
String[] options = new String[3];
int current = 0;
options[current++] = "-T";
options[current++] = "" + getThreshold();
while (current < options.length) {
options[current++] = "";
}
return options;
}
The same for setOptions(String[] options) method.
You only need to use the accessors.
Okay, so this is my first time implementing classes, and everything's going wrong. I'm implimenting a different class, PhraseGenerator, and the method inherited which I wish to define here is getPhrase(). It needs to return theArcha. Instead of working within it, I chose to wrap its braces around my work afterwards, and now, no matter where I put it, a different error arises. Before dealing with any of these, I want to make sure I'm putting it in the right place. To my understanding, it would go within public....FromFile implements PhraseGenerator. Any thoughts on where it should go?
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PhraseGeneratorFromFile implements PhraseGenerator {
private ParserHelperImpl parserHelper;
public String getPhrase() {
public PhraseGeneratorFromFile(String filename) {
// read file
StringBuilder fileContent = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(filename));
try {
String line = br.readLine();
while (line != null) {
fileContent.append(line);
fileContent.append('\n');
line = br.readLine();
}
String everything = fileContent.toString();
} finally {
br.close();
}
parserHelper = new ParserHelperImpl();
List<String> phraseCollection = parserHelper.getPhrases(fileContent,"phrases:");
String archetype = parserHelper.getRandomElement(phraseCollection);
boolean flagga = true;
while(flagga = true){
Pattern ptrn = Pattern.compile("#[^#]+#");
Matcher m = ptrn.matcher(archetype);
String fromMatcher = m.group(0);
String col = ":";
String token = fromMatcher+col;
List<String> pCol = parserHelper.getPhrases(fileContent, token);
String repl = parserHelper.getRandomElement(pCol);
String hash = "#";
String tk2 = hash + token + hash;
archetype = parserHelper.replace(archetype, tk2, repl);
flagga = m.find();
}
String theArcha = archetype;
return theArcha;
}
}
}
A good practice while posting a question here is :
(1). Explain in brief what you expect off your code to do.
(2). If you are experiencing certain errors, copy them here so that it can be understood what is going wrong in your code.
I seriously did not understood what you were trying to achieve but I see a missing closing bracket in
public String getPhrase()
It should be :
public String getPhrase()
{
//logic here
}
Hope this helps
Yes, it is in the right place but you are missing the closing }, which should come directly after the {. You can't put a method inside another method like that.
Because you want to return theArcha, you should instead make it what we call "an instance variable" - you may not have heard of this? If not, look it up.
Your interface is probably like this
interface PhraseGenerator {
String getPhrase();
}
Then the implementing class you wrote will take the form
class PhraseGeneratorImpl implements PhraseGenerator {
private ParserHelperImpl parserHelper;
#Override //Used for an overridden or implemented method
public String getPhrase() {
//Put all the code you want to implement here..
//If you want to make use of a helper Class the clean way is to use an instance of it(You tried it with Helper)
//If you want to make use of a utility method within the same class,
//say reading something from the file system define a private method below this method
String filePhrase = phraseGeneratorFromFile();
//Now use the filePhrase do do other stuff
}
//
private String phraseGeneratorFromFile(){
//Do all the stuff and return phrase/string so declare return type. you havent done it in the code above
}
}
What is the most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff") in Java?
Use CaseFormat from Guava:
import static com.google.common.base.CaseFormat.*;
String result = LOWER_HYPHEN.to(LOWER_CAMEL, "do-some-stuff");
With Java 8 there is finally a one-liner:
Arrays.stream(name.split("\\-"))
.map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase())
.collect(Collectors.joining());
Though it takes splitting over 3 actual lines to be legible ツ
(Note: "\\-" is for kebab-case as per question, for snake_case simply change to "_")
The following method should handle the task quite efficient in O(n). We just iterate over the characters of the xml method name, skip any '-' and capitalize chars if needed.
public static String toJavaMethodName(String xmlmethodName) {
StringBuilder nameBuilder = new StringBuilder(xmlmethodName.length());
boolean capitalizeNextChar = false;
for (char c:xmlMethodName.toCharArray()) {
if (c == '-') {
capitalizeNextChar = true;
continue;
}
if (capitalizeNextChar) {
nameBuilder.append(Character.toUpperCase(c));
} else {
nameBuilder.append(c);
}
capitalizeNextChar = false;
}
return nameBuilder.toString();
}
Why not try this:
split on "-"
uppercase each word, skipping the first
join
EDIT: On second thoughts... While trying to implement this, I found out there is no simple way to join a list of strings in Java. Unless you use StringUtil from apache. So you will need to create a StringBuilder anyway and thus the algorithm is going to get a little ugly :(
CODE: Here is a sample of the above mentioned aproach. Could someone with a Java compiler (sorry, don't have one handy) test this? And benchmark it with other versions found here?
public static String toJavaMethodNameWithSplits(String xmlMethodName)
{
String[] words = xmlMethodName.split("-"); // split on "-"
StringBuilder nameBuilder = new StringBuilder(xmlMethodName.length());
nameBuilder.append(words[0]);
for (int i = 1; i < words.length; i++) // skip first
{
nameBuilder.append(words[i].substring(0, 1).toUpperCase());
nameBuilder.append(words[i].substring(1));
}
return nameBuilder.toString(); // join
}
If you don't like to depend on a library you can use a combination of a regex and String.format. Use a regex to extract the starting characters after the -. Use these as input for String.format. A bit tricky, but works without a (explizit) loop ;).
public class Test {
public static void main(String[] args) {
System.out.println(convert("do-some-stuff"));
}
private static String convert(String input) {
return String.format(input.replaceAll("\\-(.)", "%S"), input.replaceAll("[^-]*-(.)[^-]*", "$1-").split("-"));
}
}
Here is a slight variation of Andreas' answer that does more than the OP asked for:
public static String toJavaMethodName(final String nonJavaMethodName){
final StringBuilder nameBuilder = new StringBuilder();
boolean capitalizeNextChar = false;
boolean first = true;
for(int i = 0; i < nonJavaMethodName.length(); i++){
final char c = nonJavaMethodName.charAt(i);
if(!Character.isLetterOrDigit(c)){
if(!first){
capitalizeNextChar = true;
}
} else{
nameBuilder.append(capitalizeNextChar
? Character.toUpperCase(c)
: Character.toLowerCase(c));
capitalizeNextChar = false;
first = false;
}
}
return nameBuilder.toString();
}
It handles a few special cases:
fUnnY-cASe is converted to funnyCase
--dash-before-and--after- is converted to dashBeforeAndAfter
some.other$funky:chars? is converted to someOtherFunkyChars
For those who has com.fasterxml.jackson library in the project and don't want to add guava you can use the jaskson namingStrategy method:
new PropertyNamingStrategy.SnakeCaseStrategy.translate(String);
get The Apache commons jar for StringUtils. Then you can use the capitalize method
import org.apache.commons.lang.StringUtils;
public class MyClass{
public String myMethod(String str) {
StringBuffer buff = new StringBuffer();
String[] tokens = str.split("-");
for (String i : tokens) {
buff.append(StringUtils.capitalize(i));
}
return buff.toString();
}
}
As I'm not a big fan of adding a library just for one method, I implemented my own solution (from camel case to snake case):
public String toSnakeCase(String name) {
StringBuilder buffer = new StringBuilder();
for(int i = 0; i < name.length(); i++) {
if(Character.isUpperCase(name.charAt(i))) {
if(i > 0) {
buffer.append('_');
}
buffer.append(Character.toLowerCase(name.charAt(i)));
} else {
buffer.append(name.charAt(i));
}
}
return buffer.toString();
}
Needs to be adapted depending of the in / out cases.
In case you use Spring Framework, you can use provided StringUtils.
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.stream.Collectors;
public class NormalizeUtils {
private static final String DELIMITER = "_";
private NormalizeUtils() {
throw new IllegalStateException("Do not init.");
}
/**
* Take name like SOME_SNAKE_ALL and convert it to someSnakeAll
*/
public static String fromSnakeToCamel(final String name) {
if (StringUtils.isEmpty(name)) {
return "";
}
final String allCapitalized = Arrays.stream(name.split(DELIMITER))
.filter(c -> !StringUtils.isEmpty(c))
.map(StringUtils::capitalize)
.collect(Collectors.joining());
return StringUtils.uncapitalize(allCapitalized);
}
}
Iterate through the string. When you find a hypen, remove it, and capitalise the next letter.