I have a question about naming SharedSizeGroups in WPF grids mostly out of curiosity. I noticed on MSDN that they list restrictions for the group's string name:
The SharedSizeGroup property value must satisfy the following rules:
Must not be empty.
Must only consist of letters, digits, and underscore characters.
Must not start with a numeric value.
I have some groups that I named numerically ("1", "2", "3", etc.) and have never had a problem with them. Just for kicks I renamed some groups to something like ",-[]" and they still worked too. So these rules are not enforced and seemingly not necessary. Does anybody know the reason for the rules in the documentation? Is it possible for the names to conflict with something that WPF is doing internally?
Edit: Okay, so WPF does enforce it after all, validation just doesn't fire in my non-compiled templates.
Interesting, I took a look at the DefinitionBase class in reflector and the SharedSizeGroup property.
It creates a dependency property with a validation callback defined as the following:
SharedSizeGroupProperty = DependencyProperty.Register("SharedSizeGroup", typeof(string), typeof(DefinitionBase), new FrameworkPropertyMetadata(new PropertyChangedCallback(DefinitionBase.OnSharedSizeGroupPropertyChanged)), new ValidateValueCallback(DefinitionBase.SharedSizeGroupPropertyValueValid));
private static bool SharedSizeGroupPropertyValueValid(object value)
{
if (value == null)
{
return true;
}
string str = (string)value;
if (str != string.Empty)
{
int num = -1;
while (++num < str.Length)
{
bool flag = char.IsDigit(str[num]);
if (((num == 0) && flag) || ((!flag && !char.IsLetter(str[num])) && ('_' != str[num])))
{
break;
}
}
if (num == str.Length)
{
return true;
}
}
return false;
}
I tested this, and it does in fact return false for anything containing non-numeric, non-alpha, non-underscore characters. It also returns false for any group starting with a number. So it seems to follow general variable name rules..
My guess is this would most likely throw some sort of exception, but perhaps it is being handled. Have you checked the output window?
I tried an invalid name, and I got an XAMLParseException.
Related
In the following code, the RegexConstraint doesn't work, because the phone number results always incorrect. What's wrong? I need to check a mobile phone number (without the country code). For example, the input 3652312453 should be correct, but in the following code it's evaluated as incorrect.
I copied the regex from the discussion linked in the comment: my only requirement is a valid phone number.
(Note: this question is not for generic Java, but only for Codename One. The class "CountryCodePicker" extends the class "Button": I reported it to make it clear that the phone number and the country code are separated)
TextModeLayout tl = new TextModeLayout(1, 1);
Container loginContainer = new Container(tl);
TextComponent phone = new TextComponent().label("PHONE").errorMessage("INVALID-PHONE");
CountryCodePicker countryCode = new CountryCodePicker();
phone.getField().setConstraint(TextArea.PHONENUMBER);
loginContainer.add(phone);
Container loginContainerWithCodePicker = new Container(new BoxLayout(BoxLayout.X_AXIS_NO_GROW));
loginContainerWithCodePicker.add(countryCode).add(loginContainer);
// https://stackoverflow.com/questions/8634139/phone-validation-regex
String phoneRegEx = "/\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})/";
val.addConstraint(phone, new RegexConstraint(phoneRegEx, "NOT-VALID-NUMBER"));
Button loginButton = new Button("LOG-IN");
val.addSubmitButtons(loginButton);
[rant]
Personally I really hate regex as I find it damn unreadable for anything other than trivial validation.
[/rant]
So I would prefer this:
val.addConstraint(phone, new Constraint() {
public boolean isValid(Object value) {
String v = (String)value;
for(int i = 0 ; i < v.length() ; i++) {
char c = v.charAt(i);
if(c >= '0' && c <= '9' || c == '+' || c == '-') {
continue;
}
return false;
}
return true;
}
public String getDefaultFailMessage() {
return "Must be valid phone number";
}
});
However, I'm guessing the reason the regex failed for you is related to the syntax with the slashes:
String phoneRegEx = "^\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})";
The following resource on Oracle's Java 8 Lessons helps me always define the RegEx I need. Take the time to study it and you will be successful, especially since the problem seems to be in the initialization of the Constraint object. I had an issue the day before my post here, and managed to solve it elegantly which is the goal, always.
Use this link
https://docs.oracle.com/javase/tutorial/essential/regex/
Oracle Tutorials: "Lesson: Regular Expressions".
I have the following code, meant to prevent user from writing new-lines in a memo text editor:
private void m_commentMemoEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData.HasFlag(Keys.Enter))
{
e.SuppressKeyPress = true;
}
}
It really does prevent Enter from being inserted, but strangely enough it prevents other keys from being inserted as well. So far we've discovered that the keys: 'O', 'M', '/' and '-' are also being "caught".
Update: The following code does what I need:
private void m_commentMemoEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == (int)Keys.Return)
{
e.SuppressKeyPress = true;
}
}
But I still don't understand the former code does not work and this does.
I've looked at the System.Windows.Forms.Keys enum but didn't find any clues (though I must say this is one weirdly constructed enum). Can anyone explain why is this happening?
HasFlags() is inherited from Enum.HasFlags(). It is useful on enums that are declared with the [Flags] attribute. It uses the & operator to do a test on bit values. Trouble is, Keys.Enter is not a flag value. Its value is 0x0d, 3 bits are set. So any key that has a value with bits 0, 2 or 3 turned on is going to return true. Like Keys.O, it has value 0x4f. 0x4f & 0x0d = 0x0d so HasFlags() returns true.
You should only use it with Keys values that actually represent flag values. They are Keys.Alt, Keys.Control and Keys.Shift. Note that these are modifier keys. So you can use HasFlags to see the difference between, say, F and Ctrl+F.
To detect Keys.Enter you should do a simple comparison. As you found out. Note that your if() statement is also true for Alt+Enter, etcetera, this might not be what you want. Instead use
if (e.KeyData == Keys.Return) e.SuppressKeyPress = true;
Which suppresses the Enter key only if none of the modifier keys are pressed.
I suspect it has something to do with the underlying values of the System.Windows.Forms.Keys enum being mapped directly to the keyboard codes, which are not always mutually exclusive. The documentation says that you should not use any kind of bitwise operation on them, and gives an example of why not (Beware the FlagsAttribute on the enum!).
MSDN also says that the HasFlag function returns the result of this: thisInstance And flag = flag, so you could potentially set a breakpoint and look at the actual binary codes coming in and see if that operation would give you a true for the set of keys you listed.
In the end, your updated code is the right way to do what you want to do.
HasFlag is for Flags - which means if a bit is set or not
the keyvalue is an ordinal value, so completely different from flags
use the comparison operator and everything should be fine.
some enum fields are defined like flags, e.g.
enum SomeFlag
{
BitOne = 1,
BitTwo = 2,
Bitthree = 4
};
here it makes sense to use "HasFlag"
I am trying to write a spell corrector using the lucene spellchecker. I would want to give it a single text file with blog text content. The problem is that it works only when I give it one sentence/word per line in my dictionary file. Also the suggest API returns results without giving any weightage to number of occurences. Following is the source code
public class SpellCorrector {
SpellChecker spellChecker = null;
public SpellCorrector() {
try {
File file = new File("/home/ubuntu/spellCheckIndex");
Directory directory = FSDirectory.open(file);
spellChecker = new SpellChecker(directory);
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
spellChecker.indexDictionary(
new PlainTextDictionary(new File("/home/ubuntu/main.dictionary")), config, true);
//Should I format this file with one sentence/word per line?
} catch (IOException e) {
}
}
public String correct(String query) {
if (spellChecker != null) {
try {
String[] suggestions = spellChecker.suggestSimilar(query, 5);
// This returns the suggestion not based on occurence but based on when it occured
if (suggestions != null) {
if (suggestions.length != 0) {
return suggestions[0];
}
}
} catch (IOException e) {
return null;
}
}
return null;
}
}
Do I need to make some changes?
Regarding your first issue, sounds like the expected, documented dictionary format, here in the PlainTextDictionary API. If you want to pass arbitrary text in, you might want to index it and use a LuceneDictionary instead, or possibly a HighFrequencyDictionary, depending on your needs.
The Spellchecker suggests replacements based on the similarity between the words (based on Levenstein Distance), before any other concern. If you want it to only recommend more popular terms as suggestions, you should pass a SuggestMode to SpellChecker.suggestSimilar. This ensures that matches suggested are at least as strong, popularity-wise, as the word they are intended to replace.
If you must override how Lucene decides on best matches, you can do that with SpellChecker.setComparator, creating your own Comparator on SuggestWords. Since SuggestWord exposes freq to you, it should be easy to arrange found matches by popularity.
have the following function on my collection:
getFiltered: function (status, city) {
return this.filter(function (trainer) {
return ((status === null) ? trainer : trainer.get("TrainerStatusName") === status) &&
((city === null) ? trainer : trainer.get('City') === city);
});
}
What is is best way to deal with nullable params passed in i.e. if city it null then ignore filter/fetch all and if status is null then ignore filter/fetch all
The code above works, but curious about alternatives
Ok, first off, I'm a little confused by your question; the title says its about handling "nullable" parameters, but your code looks like it is dealing with "special case" parameters (specifically "all") ... except for the case of trainer being null, but I don't think that is even possible when iterating through a Backbone collection.
* * Edit * *
OP updated the question, so the above is no longer relevant. I've also updated my answer accordingly.
In any case, there's nothing at all wrong or unusual about your code; ternary operators are a standard way of handling one-off special cases. If you're looking for alternative ideas though, here's one that uses an extra function to DRY out (eliminate the duplication of) your code:
function matchesOrAll(expected, actual) {
return expected === null || expected === actual;
}
getFiltered: function (status, city) {
return this.filter(function (trainer) {
return matchesOrAll(status, trainer.get("TrainerStatusName") &&
matchesOrAll(city, trainer.get("City"));
}
* * Edit * *
Now that we're talking about null and not "all", it's worth pointing out that there is a better pattern for simpler cases of nulls/undefined. If you were just filtering cities, for instance, the code could just be:
getFiltered: function (expectedCity) {
return this.filter(function (currentCity) {
return expectedCity === (currentCity || expectedCity);
}
In other words, you could take advantage of Javascript's "truthiness", and the fact that disjunctive (ie. ||) booleans expressions return the first truthy value. This eliminates the need for a ternary, and many libraries use this pattern to fill in un-provided arguments; for instance, here's a line from jQuery that sets the "target" argument to a new object if none is provided:
target = arguments[1] || {};
Unfortunately though, when you're dealing with properties/attributes of things (eg. trainer.get('foo')) instead of just objects directly (eg. trainer), there's no good shortcut you can use (other than making a function).
I just had a problem in one of my projects. Maybe I got the wrong concept about encapsulation.
Encapsulation protects member variables from classes, by defining getters and setters methods, now, i was reading that setters must be void, but in that case, how can I know if the function really set the value passed by argument. For example
void setArea(int a) {
if(a>0)
Area = a;
}
How can I be sure that argument "a" was a correct value, wouldnt be better defining the function like this
bool setArea(int a) {
if(a>0) {
Area = a;
return true;
}
return false;
}
Is that ok? that way i can know if a change really happened.
I think what you're looking for is a guard clause that throws an exception if invalid values are set:
void setArea(int a) {
if (a <= 0) throw new InvalidArgumentException(...);
Area = a;
}
But if you want client code to test for invalid values before setting them, you could have this:
bool isAreaValid(int a) {
return a > 0;
}
void setArea(int a) {
if (!isAreaValid(a)) throw new InvalidArgumentException(...);
Area = a;
}
Clients could be coded like this:
if (obj.isAreaValid(myArea)) {
obj.setArea(myArea);
}
But don't stop there. If the concept of area is important, spring it into existence into its own value object to make your design clearer.