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"
Related
I am new to Flink CEP and have been playing around with the patterns for better understanding of them.
I have a simple case of a "begin" & a followedBy".
I notice that in the case of followedBy, the same event is looping through it multiple times.
What am I missing here?
Pattern match_win = Pattern.begin("first").where(new SimpleCondition() {
public boolean filter(HitDTO hitDTO) throws Exception {
boolean result = false;
if (hitDTO.getHitScore() == 4)
{
System.out.println("First:" + hitDTO + ": " + hitDTO.getHitScore());
result = true;
}
return result;
}
}).followedBy("next").where(new SimpleCondition<HitDTO>(){
public boolean filter(HitDTO hitDTO) throws Exception
{
boolean result = false;
if (hitDTO.getHitScore() == 6)
{
System.out.println("Next:" + hitDTO+ ": " + hitDTO.getHitScore());
result = true;
}
return result;
}
});
I am passing in 4,4,6
Parallelism is set at 1.
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
However, this is what I see in the logs for the printout within the patterns, where 6 is looping 4 times when it was passed in only once.
First:com.rs.dto.HitDTO#17619295: 4
First:com.rs.dto.HitDTO#c108f70: 4
Next:com.rs.dto.HitDTO#5d13aab8: 6
Next:com.rs.dto.HitDTO#5d13aab8: 6
Next:com.rs.dto.HitDTO#5d13aab8: 6
Next:com.rs.dto.HitDTO#5d13aab8: 6
Just wondering why the same event is looping through multiple times but the outcome is correct.
Thanks for your answer.
It is normal that the process of attempting to match a pattern to an input sequence will involve multiple evaluations of various components of the pattern. That's how pattern matching works: the pattern is compiled to a finite state machine, and all possible paths the input might take through that FSM are considered, looking for paths that lead to the terminal, matching state. If you're not careful in how you define your pattern, this can lead to a combinatorial explosion of effort.
String color1 = moreColors.get(0);
String color2 = moreColors[0];
System.assertEquals(color1, color2);
// Iterate over a list to read elements
for(Integer i=0;i<colors.size();i++) {
// Write value to the debug log
System.debug(colors[i]);
}
I am learning Apex and just started what is meaning of line System.assertEquals(color1, color2); and what is mean by debug log here?
System.assert, System.assertEquals, System.assertNotEquals. I argue these are three of the most important method calls in Apex.
These are assert statements. They are used in testing to validate that the data you have matches your expectations.
System.assert tests an logical statement. If the statement evaluates to True, the code keeps running. If the statement evaluates to False, the code throws an exception.
System.assertEquals tests that two values are equal. If the two are equal, the code keeps running. If they are not equal, the code throws an exception.
System.assertNotEqual tests that two values are not equal. If the two are not equal, the code keeps running. If they are equal, the code throws an exception.
These are critical for completing system testing. In Apex Code, you must have 75% line test coverage. Many people do this by generating test code that simply covers 75% of their lines of code. However, this is an incomplete test. A good test class actually tests that the code does what you expect. This is really great to ensure that your code actually works. This makes debugging and regression testing far easier. For example. Lets create a method called square(Integer i) that squares the integer returned.
public static Integer square( Integer i ) {
return i * i;
}
A poor test method would simply be:
#isTest
public static void test_squar() {
square( 1 );
}
A good test method could be:
#isTest
public static void test_square() {
Integer i;
Integer ret_square;
i = 3;
ret_square = square( i );
System.assertEquals( i * i; ret_square );
}
How I would probably write it is like this:
#isTest
public static void test_square() {
for( Integer i = 0; i < MAX_TEST_RUNS; i++ ) {
System.assertEquals( i*i, square( i ) );
}
}
Good testing practices are integral to being a good developer. Look up more on Testing-Driven Development. https://en.wikipedia.org/wiki/Test-driven_development
Line by Line ...
//Get color in position 0 of moreColors list using the list get method store in string color1
String color1 = moreColors.get(0);
//Get color in position 0 of moreColors list using array notation store in string color2,
//basically getting the same value in a different way
String color2 = moreColors[0];
//Assert that the values are the same, throws exception if false
System.assertEquals(color1, color2);
// Iterate over a list to read elements
for(Integer i=0;i<colors.size();i++) {
// Write value to the debug log
System.debug(colors[i]);//Writes the value of color list ith position to the debug log
}
If you are running this code anonymously via the Developer console you can look for lines prefixed with DEBUG| to find the statements, for e.g.
16:09:32:001 USER_DEBUG 1|DEBUG| blue
More about system methods can be found at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_system.htm#apex_System_System_methods
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.
The other day, a colleague noticed the common pattern he was doing of:
if (someBooleanFlag)
{
someBooleanFlag = FALSE;
...do some more stuff...
}
basically, a clear-on-read latch. And asked if I knew of a clever way to test the flag and clear it as a one-liner, so he could get rid of the boilerplate someBooleanFlag = FALSE; bit. Questions about whether this is good style or not aside, I found the best I could do for him was a something like
#define TESTANDCLEAR(var) (var ? var-- : 0)
This makes the assumption that ONLY 1 and 0 are being used, and it doesn't work on bitmasks either. I figured I'd turn to the Wizards of the Stack, to see if there was some better way and other technique that could be used.
(Again, no need to discuss whether the style of doing a TESTANDCLEAR() expression is bad or good, it was more of the academic exercise if we actually could do it, and how generally)
I don't think you need to make the 0/1 assumption, even with the approach you already have. Assignments are expressions that return a value, so you could define that macro as:
(var ? !(var = false) : false)
Or, you could use the comma operator:
(var ? ((var = false), true) : false)
Which would help if you wanted this to work with a bitfield testing for the Nth bit:
(((var & (1 << N)) ? ((var = var & ~(1 << N)), true) : false)
Ugly, but I think this should work:
if (someBooleanFlag && !(someBooleanFlag = !someBooleanFlag))
For the love of God never do this in production code.
I have a method DoCleanUp(), which will ask user to proceed and then clear current workspace. It will return if user choose to cancel this process.
My question is, which signature is best to indicate a "cancel"?
bool DoCleanUp(); // return false to indicate canceled.
bool DoCleanUp(); // return true to indicate this method should be canceled.
void DoCleanUp(bool& cancel); // check parameter 'cancel' to see if this method was canceled.
UPDATE: As for the language, it's C++\CLI or C#.
UPDATE2: Now suppose I have to save a file in the DoCleanUp method. I'll prompt a dialog ask user whether to save/not save/cancel the file. Based on the answers, here is what I came up:
void DoCleanUp();
DialogResult AskToSaveFile(); // return yes/no/cancel
void DoCleanUp( bool saveFile );
Usage:
void DoCleanUp()
{
DialogResult result = AskToSaveFile();
if( result == DialogResult::Cancel ) return;
bool saveFile = (result == DialogResult::Yes) ? true : false;
DoCleanUp( saveFile );
}
Then by calling DoCleanUp(), you know user will have the opportunity to cancel;
By calling DoCleanUp(bool saveFile), you can control whether to save file without asking user.
Is that looks better?
This is a classic single responsibility problem.
The reason that you are unsure about the signature is that the method is doing 2 things.
I would create 2 methods:
bool CheckIfTheUserWantsToCancel()
void DoCleanUp()
EDIT
Based on the comments and edits to the question I would create a 3rd method:
void SaveFile()
The DoCleanUp would then first call CheckIfTheUserWantsToCancel, and then if not cancelled would call SaveFile.
IMHO this is much better than trying to remember that DoCleanUp with parameter false will save the file without asking the user, or was it the other way around?
Without more details I would say answer 1 is the best IMHO. Third is rather ugly since it requires more code for calling.
But maybe consider rewriting code to this
void CleanUp() {
switch (AskUser()) {
case ButtonOk: CleanUpDesk(); break;
case ButtonNo: break;
default:
case ButtonCancel: CancelCleanUpDesk(); break;
}
}
This seems to in the spirit of single responsibility. My code somehow breaks your problem into two steps: asking user and performing action.
I would use your 1 version.
bool DoCleanUp(); // return false to indicate canceled.
The assumption is, that it returns true when the cleanup is done. Returning false would indicate a 'Error' state. It might even make sense to return an int. In this case the convention usually is that 0 represents success and everything else is an error code.
Regardless of what you decide, document what your return values mean!
The confusing bit is the calling it DoSomething(), when it might not do anything. How about
if (QueryCleanup()) // boolean
DoCleanup(); // void
More verbose but clearer, even without seeing the declaration.
You should not use a boolean for statuses (or status messages). Create an Enum:
public Enum CleanupStatus
{
Ok = 0,
Cancel
}
This way it is more clear what the return value is ... and if you need to add more statuses, you can.
(This is all from Code Complete 2, you should read it if you haven't yet.)
You have two requests basically. The outer request is to create a new workspace. The inner request is to save the current workspace. You want to return true if the outer request continues and false if the outer request is aborted. The action of the inner request is not important to the outer request and so should be some kind of delegate/functor/closure.
Make a class to genericize this:
class YesNoCancel {
string question; // question to ask the user about the inner state
delegate doit; // function to call to
delegate dontdoit;
public:
YesNoCancel(string question, delegate doit, delegate dontdoit = null) {...}
bool run() {
switch (AskUser(question)) {
case ANSWER_YES: doit(); return true;
case ANSWER_NO: return true;
case ANSWER_CANCEL: if (dontdoit) dontdoit(); return false;
};
//usage
void NewWorkspace() {
if (m_workspace) {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (!ync.run()) return;
}
// new workspace code
}
void CloseApp() {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (ync.run()) ExitApplication();
}
I believe option three gives the most clarity. When you have the bool as a return type it is not immediately clear what it is used for.
I usually go with
bool DoCleanUp(); // Returns true if cancel
but mostly it depends on whether the calling code looks like this:
if (DoCleanUp()) {
// Do cancel up code
}
or:
if (DoCleanUp()) {
// Do non-cancel post clean up code
}
Basically I try to make my tests not have to use a ! or language equivilent as I find it hard to see.
I definitely would not do number 3.
I prefer the third signature, only because by looking at it (without any extra documentation), I can tell more about what the method does. I would call the argument something more explicit, like processCancelled, though.