I am trying to create a method in dart but have run into a wall. I was looking at how .toUpperCase(); and .toLowerCase(); were done. The method that I am trying to create is .capitalize();
I would like to call this method like this
String hello = "WORLD".capitalize(); //World
Here is the code I have so far
String capitalize() {
return this.codeUnitAt(0).toUpperCase() + this.substring(1).toLowerCase();
}
When running String hello = "WORLD".capitalize(); I get the following error
[38;5;124m[2015-6-4 11:37:13.011] Class 'String' has no instance method 'capitalize'.
NoSuchMethodError: method not found: 'capitalize'
Receiver: "WORLD"
Arguments: [][0m
I know i can call a function like String capitalize(String s) => s[0].toUpperCase() + s.substring(1);
But would much rather keep string Manipulation calls the same.
Thanks and I appreciate any help:)
You cannot extend the String class like you want. Just use it like this:
capitalize("WORLD");
Yes, not like JS, you can't just change any class in Dart. You can extend it only. E.g. you can create MyString class with capitalize method. But I don't think you want it. Just make some StringUtils.dart library with method capitalize
Since dart is more common now, there are a lot more packages available at pub.dartlang.org.
I found a nice dart package for different operation on strings. It also contains a capitalize method.
https://pub.dartlang.org/packages/basic_utils
Simply add the dependency :
dependencies:
basic_utils: ^1.0.3
Usage :
StringUtils.capitalize("helloworld"); // helloworld => Helloworld
It also contains other usefull methods :
camelCaseToUpperUnderscore
camelCaseToLowerUnderscore
isAscii
isNullOrEmpty ...
if this is still a problem, you can simple use this dependecy:
dependencies:
text_tools: ^0.0.2
Is simple to use, here is an example:
//This will put the first letter in UpperCase, will print 'Name'
print(TextTools.toUppercaseFirstLetter(text: 'name'));
Related
I want to be able to use a method from a Jenkins plugin via its java class
Just to point out I'm not a developer or a groovy/java expert - happy to learn!
The java class that my method is part of is com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator
From this I would like to use the method getRepoOwner()
What I've done is set my import and defined a new call to the class:
import com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator
def bbSCMNav = new BitbucketSCMNavigator()
When I run this I get the error below:
org.codehaus.groovy.runtime.metaclass.MethodSelectionException: Could not find which method <init>() to invoke from this list:
public com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator#<init>(java.lang.String)
public com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator#<init>(java.lang.String, java.lang.String, java.lang.String)
I've searched for the error above Could not find which method <init>() to invoke from this list
And I came across this ticket Could not find which method <init>() to invoke from this list on newInstance in groovy closure
Can't say that I entirerly understand the reply if it's helpful to me or not as I say I'm not a developer and groovy and java are relatively new to me but happy to understand if anyone can point me in the right direction with this
The goal of this exercise is to use the method during the run-time of a build to get the output of getRepoOwner() and use that in a variable to construct a URI
This question also seems similar to mine - Calling internal methods of Jenkins plugin (thinBackup)
But I'm not using maven or a pom.xml here
Cheers
Quick Answer
This error Could not find which method < init >() is related to a missing constructor.
Almost all internal jenkins class are ready to use in groovy.
In your case, BitbucketSCMNavigator does not have a default constructor. It have a constructor with one String argument. Check this line
Explanation
I could replicate your error with another internal class org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory:
node {
stage('internal') {
org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory obj =
new org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory();
}
}
hudson.remoting.ProxyException: org.codehaus.groovy.runtime.metaclass.MethodSelectionException: Could not find which method <init>() to invoke from this list:
private org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory#<init>(org.jenkinsci.plugins.workflow.cps.CpsFlowExecution, boolean, java.lang.ClassLoader, java.util.List)
But, reviewing this class CpsFlowExecution I could see that CpsGroovyShellFactory does not have a default constructor. It have a constructor with one argument : CpsGroovyShellFactory(this)
So, If I instance the constructor with one argument, no errors appear.
node {
stage('internal') {
org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory obj =
new org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory(null);
}
}
I'm learning to use the new Dart extension methods.
I'm doing this:
extension StringInsersion on StringBuffer {
void insertCharCodeAtStart(int codeUnit) {
final end = this.toString();
this.clear();
this.writeCharCode(codeUnit);
this.write(end);
}
int codeUnitAt(int index) {
return this.toString().codeUnitAt(index);
}
}
So that I can do something like this:
myStringBuffer.insertCharCodeAtStart(0x0020);
int value = myStringBuffer.codeUnitAt(2);
However, I get the following lint warning:
Don't access members with this unless avoiding shadowing.
Should I be doing something different?
The warning you received means the following:
There is no need to reference the current instance using keyword this. Everything will work without reference to the current instance because the static extension method itself acts as an instance method of extensible type.
Simply put, just remove the reference to the current instance from your code.
From this:
final end = this.toString();
To this:
final end = toString();
It's a style thing, based on Dart's guide. There are examples in https://dart-lang.github.io/linter/lints/unnecessary_this.html.
You can find more about style in https://dart.dev/guides/language/effective-dart/style.
I turn off this rule globally by changing "analysis_options.yaml"
include: package:flutter_lints/flutter.yaml
linter:
rules:
unnecessary_this: false
I wish to have the sub-classes of a super-class "registered" by an arbitrary name - whenever I declare a sub-class I wish to also have it entered into the super-class.sub Map.
Is there any way to accomplish this outside of main()?
// base class
class Mineral{
final String formula;
static Map<String,Mineral> sub = {}
Mineral( this.formula );
}
// sub class - declare and register
class Mica extends Mineral{
Mica( String formula ) : super( formula );
}
Mineral.sub['mica'] = Mica; // oops!
when I run this, I get
Error: line 10 pos 1: unexpected token 'Mineral' Mineral.sub['mica'] = Mica;
assuming that executable code is not allowed outside main().
cannot put within the super-class since other sub-classes may declared later, outside the library.
Dart has no way to run code as part of a library being loaded.
Executable code can only be put inside methods, or in field initializers, and static field initializers are lazy so they won't execute any code until you try to read them.
This is done to ensure quick startup - a Dart program doesn't have to execute any code before starting the main library's "main" method.
So, no, there is no way to initialize something that isn't constant before main is called.
Either
Mineral.sub['mica'] = new Mica();
or
static Map<String,Type> sub = {};
When you assign Mica you assign the Type Mica. new Mica() is an instance of Mica that is of the kind Mineral and can be assigned to the map you declared.
edit
Maybe you want to initialize the sub map:
static Map<String,Mineral> sub = {'mica': new Mica()};
hint: the semicolon is missing in this line in your question.
In Module.php I have a some code (simplified version):
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module{
public $somevariable = 'test';
public function onBootstrap( MvcEvent $e ) {
$this->somevariable = 'test2';
}
public function getValue(){
return $this->somevariable;
}
}
Next, I want to get value from variable "somevariable" in template layout.phtml. I do this as follows:
echo Application\Module::getValue();
but this doesn't work. What is wrong with that?
P.S. I never programmed much in PHP, so maybe I missed something :-(
you can use
$e->getViewModel()->setVariable('somevariable', 'somethingvalue');
and in the view :
echo $this->layout()->somevariable;
for detail, see this article : http://samsonasik.wordpress.com/2012/07/27/zend-framework-2-mvcevent-layout-view-get-namespace/
If a variable is just a string it doesn't make much sense to go with that approach. And please don't take this offensively, but if you don't have much experience in PHP (you tried to call a static function that is not static), then i wonder why you would start learning PHP with such a high class framework.
And if still you insist on doing that, please follow the official Documentation and read yourself through the whole QuickStart again and again. Check out some of the Modules out there and see how they do stuff.
Try to do the easy stuff first until you hit those points where you really need such functionality.
I'm trying to call a method on a grails service from a controller, but it looks like execution is just skipping the method call.
I've tried debugging the application with a breakpoint inside the method but it is never hit.
My service (generated with grails create-service) is:
class FormatterService {
static transactional = false
def formatList (List<Host>, String fmt) {
OutputObject somePOGO = new OutputObject();
(snip)
return somePOGO
}
}
Then on my controller I have:
class HostController {
def formatterService
def getHostsByLabels = {
(snip)
OutputObject o = formatterService.formatList(someHosts,params.format)
(snip)
}
}
When the formatterService.formatList method should be called in the controller, execution simply skips to the next line, no output is printed to the console and breakpoints within the method are not hit. The OutputObject o reference is null afterward.
What is wrong here? It could be a really basic mistake from my part, but I just can't put my finger on it...
To Me it seems a MetaProgramming Disaster..
Well there are 3 Tests to Debug:
_1) first try to do
println formatterService
println formatterService.getClass()
just to check if its injected bean is the desired one, some plugins sometimes inject beans which overrides the default.
_2) Make sure that the method with a name "formatList" is not injected in your services through metaprogramming by any plugin or core code.
How to test this is simple: Just change the name of the method to some Unrealistic One, ex: "formatListabcdewdw" and then call that one. If it works then its method overriden issue.
and if you are more enthusiastic you can see the metaMethods by
println formatterService.metaClass.methods
_3) just try to do "params.format as String" as the last argument in the method call.\
.
Hope any of these helps, please Do let me know of the findings, i am curious to know.. :)
I found the issue. It has to do with the method signature.
Printing out the thrown exception's message, it says:
No signature of method: hms.FormatterService.formatList() is applicable for argument types: (java.util.TreeSet, java.lang.String) values: (...)
Possible solutions: formatList(java.util.List, java.lang.String)
So, a rookie mistake (wanting to pass a TreeSet for a List) aided by weak typing in Groovy... :P
I've changed the method signature to
def formatList ( items, String fmt) {
and call it as
def activeHosts = ...
OutputObject o = formatterService.formatList(activeHosts, params.format as String)
and now it works.