http://developers.itextpdf.com/question/how-change-spacing-between-words-and-characters
Like this in C#,How to do it work?
Instead of this line:
writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
You need this line:
writer.SpaceCharRatio = PdfWriter.NO_SPACE_CHAR_RATIO;
There are two different mechanisms when converting Java code to C# code:
Sometimes you need to change lower-case into upper-case. For instance: document.add(p); needs to be changed into document.Add(p);
Setters in Java are implemented as properties in C#, as is the case with setSpaceCharRatio which is used as SpaceCharRatio.
Related
This is my code and I got comment said " can I use the predefined string format?", what is predefined string format, how can I do that?
val uri = new URI(baseUrl + "?provider=" + provider + "&format=" + format)
This is a clean "Scala" way to do this:
val uri = new URI(s"$baseUrl?provider=$provider&format=$format")
A decent editor like IntelliJ IDEA will highlight this so that it is clear which parts are code and which parts are plain text.
This is not a proper way of constructing a URI, and neither is using a string interpolator such as s"..." as suggested in the other answer or by your coworker. The reason is that it is going to break as soon as provider or format contain “weird” characters such as # or &. That can lead to all kinds of bugs, including security vulnerabilities.
Unfortunately, Scala doesn't come with an easy built-in way to construct URI query strings. You should use some URI abstraction from a library such as akka http or http4s.
For instance, with http4s you can write
val uri = uri"https://stackoverflow.com".withQueryParam("provider", provider)
That will take care of all the necessary escape sequences and the like.
I just found some scala code which has a strange class name:
class `This is a cool class` {}
and method name:
def `cool method` = {}
We can use a sentence for a class or method name!
It's very cool and useful for unit-testing:
class UserTest {
def `user can be saved to db` {
// testing
}
}
But why we can do this? How to understand it?
This feature exists for the sake of interoperability. If Scala has a reserved word (with, for example), then you can still refer to code from other languages which use it as a method or variable or whatever, by using backticks.
Since there was no reason to forbid nearly arbitrary strings, you can use nearly arbitrary strings.
As #Rex Kerr answered, this feature is for interoperablility. For example,
To call a java method,
Thread.yield()
you need to write
Thread.`yield`()
since yield is a keyword in scala.
The Scala Language Specification:
There are three ways to form an identifier. First, an identifier can
start with a letter which can be followed by an arbitrary sequence of
letters and digits. This may be followed by underscore ‘_’ characters
and another string composed of either letters and digits or of
operator characters. Second, an identifier can start with an operator
character followed by an arbitrary sequence of operator characters.
The preceding two forms are called plain identifiers. Finally, an
identifier may also be formed by an arbitrary string between
back-quotes (host systems may impose some restrictions on which
strings are legal for identifiers). The identifier then is composed of
all characters excluding the backquotes themselves.
Strings wrapped in ` are valid identifiers in Scala, not only to class names and methods but to functions and variables, too.
To me it is just that the parser and the compiler were built in a way that enables that, so the Scala team implemented it.
I think that it can be cool for a coder to be able to give real names to functions instead of getThisIncredibleItem or get_this_other_item.
Thanks for your questions which learnt me something new in Scala!
`where client.name.ToLower().Contains(name.ToLower())
Now it's clearer. It's a (badly done) case insensitive search for the name in the client.name. True if name is contained in client.name. Badly done because using international letters (clearly "international letters" don't exist. I mean letters from a culture different from you own. The classical example is the Turkish culture. Read this: http://www.i18nguy.com/unicode/turkish-i18n.html , the part titled Turkish Has An Important Difference), you can break it. The "right" way to do it is: client.name.IndexOf(name, StringComparison.CurrentCultureIgnoreCase) != -1. Instead of StringComparison.CurrentCultureIgnoreCase you can use StringComparison.InvariantCultureIgnoreCase. If you have to use tricks like the ToLower, it has been suggested that it's better to ToUpper both sides of the comparison (but it's MUCH better to use StringComparison.*)
Looks like LINQ to me.
I'm not really up-to-date on .NET these days, but I'd read that as looking for client objects whose name property is a case-insensitive match with the ToString property of the client variable, while allowing additional characters before or after, much like WHERE foo is like '%:some_value%' in SQL. If I'm right, btw, client is a terrible variable name in this instance.
This is a strange piece of code. It would be good to know a bit more about the client object. Essentially it is checking if the case insensitive name value on the client object contains the case insensitive value of the client object (as a string). So if the client name contains the string name of the class itself essentially.
.ToLower() returns the same string you call it on in all lowercase letters. Basically, this statement returns true if name.ToLower() is embedded anywhere within client.name.ToLower().
//If:<br/>
client.name = "nick, bob, jason";
name = "nick";
//Then:<br/>
client.name.ToLower().Contains(name.ToLower());
//would return true
I've scripted a MsSqlServer databases tables,views and stored procedures into a directory structure that I am then indexing with Lucene.net. Most of my table, view and procedure names contain underscores.
I use the StandardAnalyzer. If I query for a table named tIr_InvoiceBtnWtn01, for example, I recieve hits back for tIr and for InvoiceBtnWtn01, rather than for just tIr_InvoiceBtnWtn01.
I think the issue is the tokenizer is splitting on _ (underscore) since it is punctuation.
Is there a (simple) way to remove underscores from the punctuation list or is there another analyzer that I should be using for sql and programming languages?
Yes, the StandardAnalyzer splits on underscore. WhitespaceAnalyzer does not. Note that you can use a PerFieldAnalyzerWrapper to use different analyzers for each field - you might want to keep some of the standard analyzer's functionality for everything except table/column name.
WhitespaceAnalyzer only does whitespace splitting though. It won't lowercase your tokens, for example. So you might want to make your own analyzer which combines WhitespaceTokenizer and LowercaseFilter, or look into LowercaseTokenizer.
EDIT: Simple custom analyzer (in C#, but you can translate it to Java pretty easily):
// Chains together standard tokenizer, standard filter, and lowercase filter
class MyAnalyzer : Analyzer
{
public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
{
StandardTokenizer baseTokenizer = new StandardTokenizer(Lucene.Net.Util.Version.LUCENE_29, reader);
StandardFilter standardFilter = new StandardFilter(baseTokenizer);
LowerCaseFilter lcFilter = new LowerCaseFilter(standardFilter);
return lcFilter;
}
}
ADDENDUM EDIT:
Have not accepted an answer to this as
there has not been any feedback from
experienced Spring Framework
developers.
I've been working on a replacement DSL to use for Spring-Framework applicationContext.xml files (where bean initialization and dependency relationships are described for loading up into the Spring bean factory).
My motivation is that I just flat out don't like Spring's use of XML for this purpose nor do I really like any of the alternatives that have been devised so far. For various reasons that I won't go into, I want to stay with a declarative language and not some imperative scripting language such as Groovy.
So I grabbed the ANTLR parser tool and have been devising a new bean factory DSL that I've dubbed SFig. Here's a link that talks more about that:
SFig™ - alternative metadata config language for Spring-Framework
And here is the source code repository site:
http://code.google.com/p/sfig/
I'm interested to know how I'm doing on the language syntax so far. Do you think SFig is both efficient and clear to understand? (I'm particularly concerned right now with the mulit-line text string):
properties_include "classpath:application.properties";
org.apache.commons.dbcp.BasicDataSource dataSource {
#scope = singleton;
#destroy-method = close;
driverClassName = "${jdbc.driverClassName}";
url = "${jdbc.url}";
username = "${jdbc.username}";
password = "${jdbc.password}";
defaultAutoCommit = true;
}
org.springframework.orm.ibatis.SqlMapClientFactoryBean sqlMapClient {
#scope = singleton;
#init-method = afterPropertiesSet;
#factory-method = getObject;
configLocation = "classpath:sqlmap-config.xml";
dataSource = $dataSource;
}
/* this string will have Java unescape encoding applied */
STRING str = "\tA test\u0020string with \\ escaped character encodings\r\n";
/* this string will remain literal - with escape characters remaining in place */
STRING regexp = #"(\$\{([a-zA-Z][a-zA-Z0-9._]*)\})";
/* multi-line text block - equates to a java.lang.String instance */
TEXT my_multi_line_text = ///
Here is a line of text.
This is yet another. Here is a blank line:
Now picks up again.
///;
/* forward use of 'props' bean */
java.util.HashMap map {
this( $props );
}
/* equates to a java.util.Propertis instance */
PROPERTIES props {
"James Ward" = "Adobe Flex evangelist";
"Stu Stern" = "Gorilla Logic - Flex Monkey test automation";
Dilbert = "character in popular comic strip of same title";
"App Title Display" = "Application: ${app.name}";
"${app.desc}" = "JFig processes text-format Java configuration data";
}
/* equates to a java.util.ArrayList instance */
LIST list {
this( ["dusty", "moldy", "${app.version}", $str] );
[234, 9798.76, -98, .05, "numbers", $props, ["red", "green", "blue"]];
}
I'll provide a bit of background on Spring and it's applicationContext.xml file - that will lend clarity to some of the things going on in SFig syntax.
The applicationContext.xml file is used to express bean initialization for beans that will be managed by the Spring bean factory. So given the example of beans seen in my SFig version of this file, in Java application code one might request the bean factory to make an instance of a bean like so:
SqlMapClient sqlMapClient = getBean("sqlMapClient");
The bean factory takes care of any instantiation and initialization that the bean requires - even to the point of injecting dependencies. In this case, a SqlMapClient bean needs an instance of a dataSource bean (which is also described and referenced in the SFig example).
A bean descriptor relays the following information to the bean factory:
the bean's Java class name
a bean ID by which to request or reference it
bean definition meta attributes (optional)
constructor initialization arguments (optional)
and/or property initializers
The '#' prefixes bean definition meta attributes. These are attributes that are used by the bean factory to manage the bean. For instance, #scope = singleton, would inform the bean factory to make a single instance of the bean, cache it, and hand out references to it when it is requested. The ones that can be set are the same ones defined by the Spring-Framework.
If a bean is to be initialized via a constructor, then that is expressed in SFig by a syntax that appears to be invoking this with arguments in parenthesis.
Or a bean can be initialized by setting its properties. Identifiers that are assigned to and not prefixed by '#' are bean properties.
When referencing a bean that is a required dependency, then it can be referred to by prefixing it's bean ID with '$'. Several examples of this appear in the SFig example.
The ${foo.bar} syle of variable appearing in string literals will be replaced by a Java property value. In this case, properties are loaded from the file application.properties via this line:
properties_include "classpath:application.properties";
Java System properties will be looked to next if not found in any included properties. This is a widely followed practices in many Java frameworks. The current XML-based applicationContext.xml file has a way of permitting this usage too.
Because java.util.Properties are often used to initialize beans, SFig provides the PROPERTIES as a special convenient syntax for declaring a Properties object. Likewise for java.util.List, which has the corresponding SFig LIST. Also, arrays of values can be declared within square brackets [...].
Additionally there is TEXT for declaring blocks of multi-line text. The '#' prefixing a string literal means to turn off escape encoding - a language syntax borrowed from C#.
One of the primary design objectives of the SFig DSL is to remain declarative in nature. I purposely am refraining from adding any imperative scripting features. The complexity of programming logic embedded in a text configuration file will imply possibility of having to debug it. Don't want to open yet another dimension of code debugging.
I haven't much experience with the Spring XML you refer, so you should take the following feedback with a pinch of salt.
As a second and third caveat:
providing a snippet of code will give a flavour of what the language and its semantics are. It is difficult to completely understand some of the choices you have already made (and with good reason), so any feedback here may be completely contradictory or impossible in the light of those choices.
language design is as much an art as a science, and so at this stage, any feedback you may get is likely to be quite subjective.
A larger, meta-, question: as a DSL are you trying to do configuration of Spring, or as a more general class of frameworks?
There: caveat emptor. Now my subjective and incomplete feedback ;)
I'm not sure I understand the reason why you have the # prefix for scope and destroy-method, but not driverClassName. Also the mix of both xml-case and camelCase isn't completely apparent to start with. Is the # prefix a type modifier, or are these keywords in the language?
I'm not completely sure of your intentions about the block header format. You have class name, then a function of that class; is the intention to specify what class your are going to use for a particular function?
e.g.
sqlMapClient: org.springframework.orm.ibatis.SqlMapClientFactoryBean {
# body.
}
or even:
sqlMapClient {
#class = org.springframework.orm.ibatis.SqlMapClientFactoryBean;
# is there a sensible (perhaps built-in) default if this is missing?
}
I like the variable substitution; I presume the values will come from System properties?
I like being able to specify string literals (without escaping), especially for the regular expressions you've shown. However, having multi-character quote or quote modifier seems a little alien. I guess you considered the single-quote (shell and Perl use single-quotes for literal strings).
On the other hand, I think the triple forward slash for multi-line TEXT is the right approach, but two reminiscent of comments in C-style languages. Python uses a triple " for this purpose. Some shell idioms have a multi-line text convention I would not copy.
I very much like the look of properties and config location, using what looks like a URI notion of addressing. If this is a URI, classpath://file.xml may be clearer. I may have the wrong end of the stick here, however.
I also very much like the notion of list and map literals you have, though I'm not sure where:
this comes into it (I guess a call to a Java constructor)
why some types are capitalized, and others are not. Do I take it that there is a default MAP type, which you can be more specific type if you wish to?
is Dilbert an unquoted string literal?
Finally, I'd point you to another configuration DSL, though perhaps more for sysadmin usage: Puppet.
Go well.