wpf – suppress a keyboard/mouse event

… standard events like MouseDown, KeyUp.

P682 [[wpf recipes]] presented a surprisingly brief yet complete solution. The sample code takes fewer than 10 lines of xaml and c#,

but it's good to point out the salient features —

– no command, just routed events

– this technique requires a containment hierarchy, which exists in every WPF window

– If you want to suppress an event within a container, then apply the trick at that container level

– Trick is on the Preview tunneling event

Advertisements

wpf topics for IV, Proj

–IV + proj
prism
button
Grid
TextBox
layout?
data templates
triggers

–IV
dprop (dependency property), aprop (attached property)?
styles
routed events
routed commands
logical ^ visual tree

—–proj
items control
resource dict
user controls
debugger
containers – details
event handling – deeper
various common controls
bind to a method

command methods using VM — a few observations

In most of my projects, my commands inevitably need access to the VM. The Execute() and CanExecute() all need to access the VM. (See

other posts why VM is one of the top 3 players in a command set-up.)

Q: how does the command methods get a handle on the VMs? I know more than 1 technique.

A: [[wpf succinctly]] shows that in xaml, we can pass the VM as CommandParameter into the Execute() method

A: ctor injection — VM is constructor-injected in the command instance.

In a way, the command objects and VM objects are inter-dependent.

0) The VM often exposes the command as a CLR property, to be accessed by the xaml “Hollywood”

1) The command methods directly uses the VM object.

To reduce coupling, perhaps we can introduce interfaces. Necessary?

Fwd: dotnet vs jvm performance on Windows

Hi Sunil,

I tend to get into long debates on controversial tech topics, so i hope i don’t do that again here.

You mentioned c# outperforms java on the server side. I find it intriguing.

First off, the truly performance-sensitive systems either use mainframe/supercomputers (large volume, paralell processing) or C ++/assembly (for latency sensitive apps). I assume we have no disagreement on their performance advantages over virtual machines like CLR or JVM.

The Next level of high-performance data server is perhaps represented by (but not exclusively) database and messaging servers. Even the new web 2.0 shops focus (i believe) most of their tuning effort on these data-heavy engines. C/c++ dominate. I also worked with ETL products like Informatica and Ab Initio. These are heavy duty data engines for fairly large volumes. All C/C++. They actually tried java.

Many of the servers used in finance are smaller and somewhat less demanding, but still there’s non-trivial requirement on performance. C++, java and c# compete in this space. Traditionally c++ won. In recent years, I have heard claims that java could outperform c++, probably on unix benchmarks.

On windows, I still think c++ has an edge. Between dotnet and jvm, I won’t be surprised dotnet IL could outperform java bytecode. However, in finance more application servers run unix/linux than windows.

I am no expert on database vendors, but I’d draw a parallel. Oracle is more popular on *nix. It runs on windows too but perhaps not as fast as MS-SQL. Microsoft would not release a database engine if it is beaten by a competitor on microsoft’s own OS. If we were to compare oracle vs mssql, it’s an unfair contest if done on windows — MSSql has home advantage.

A more interesting contest would be java/linux vs c#/windows on the same hardware.

c# multicast event field = newsletter title = M:1 relationship

This is a revisit to the “BB” in the post on two “unrelated” categories of delegate —

   BB) event field Backed by a multicast delegate instance

If a class defines 2 events (let’s assume non-static), we can think of them as 2 newsletter titles both owned by each class Instance. Say Xbox newsletter has 33 subscribers, and WeightWatcher newsletter has 11 subscribers. If we have 10 classes instances, theen 440 subscriptions.

In general, Each newsletter title (i.e. event field) has
* exactly 1 owner/broadcaster i.e. the class instance
* 0 or more subscribers, each a 2-pointer wrapper, as described in other posts on delegates.

You can say each newsletter title (i.e. each event field) defines a M:1 relationship.

Forgive me for repeating the obvious — don’t confuse an event Field vs an event Firing. The Xbox newsletter can have 12 issues (12 event firings) a year, but it’s all under one newsletter title.

a little trick to avoid ViewModel referencing View #tight coupling

In my project a view model’s method VM.RepaintColors() needs to modify a View object DataGrid.

By basic OO principle, we know views “depend” on ViewModels, so ViewModels should not depend on (or directly edit the properties of) Views. When a data change needs to bubble up to view, we use the event infrastructure to notify the binding system to re-query the ViewModel objects.

Therefore my design above was a violation – VM.RepaintColors() directly manipulates DataGrid. I eventually solved the problem using event notification. RepaintColors() was moved into MainPage.xaml.cs i.e. the code behind class (I know this is anti-MVVM but still an improvement). As part of the view, CodeBehind (CB) class has full access to all ViewModel objects and View objects. Therefore if the original VM. RepaintColors() implementation need any field of the VM object, it still has access.

Remember the VM used to call this.RepaintColors() inside its various methods. Now with this change, it must fire the event RepaintColorsNeeded. This would notify the listening  CodeBehind and trigger CB. RepaintColors() method. The hook-up is by event registration —

Right after the CodeBehind instantiates the VM, it registers CB. RepaintColors() with the VM’s RepaintColorsNeeded event.

Note despite the notation in this write-up, RepaintColor() is always a non-static method, and uses the non-static fields.

collection view ^ collection view source, my take

My conclusion — many constructs in this space have limited practical value — CV base type, CVS.

http://www.zagstudio.com/blog/466 is an authoritative comparison.

* CVS (not CV) can be constructed in xaml.
* CV and CVS can both be used in c# cod, but i feel almost *always* we only use a subtype of CV.

CVS is designed to support __simple__ custom sorting/filtering etc directly in xaml. First You inject the collection into your CVS instance, then secondly you retrieve the view from CVS and inject the view into the visual (items control). A CVS instance is a wrapper over 2 objects
– The physical collection (often an ObservableCollection)
– A CV (or subtype) object

I guess a CV baseclass instance isn’t terribly useful if you want any customization — see below. Instead, you either use a CVS or a CV subclass instance
– For __simple__ sorting, use cvs in xaml
– For sophisticated sorting that demands c# coding, cast the CV to one of the 2 subclasses. This is the standard and natural choice.

http://www.zagstudio.com/blog/441 seems to agree with my guess.

As other authors pointed out, we should and could avoid using a view that’s a CollectionView base type — poor performance, no sorting/grouping. A subtype like ListCollectionView is always preferred. This is easy as most of the time, physical collection is some kind of IList. Therefore, whenever we retrieve the view as a CV, we almost always cast it to a subtype.

define a custom attached property

Once we reach a basic understanding of something sophisticated like Attached Property, looking at a custom AProp implementation could bring us to the next level.

http://msdn.microsoft.com/en-us/library/cc903943(v=vs.95).aspx points out

“If your class (the Provider class) is defining the attached property strictly for use on other types, then the provider class does not need to derive from DependencyObject. But you do need a DependencyObject as the method parameter in the getter/setter.

Define your attached property as a dependency property by declaring a public static readonly field of type DependencyProperty.”

Simple, clean, pure Multiple Inheritance@@

Update — Google style guide is strict on MI, but has a special exception on Windows.

MI can be safe and clean —

#1) avoid the diamond. Diamond is such a mess. I’d say don’t assume virtual base class is a vaccine

#2) make base classes imitate java interface … This is one proven way to use MI. Rememer Barcalys FI team. All pure virtual methods, No field, No big4 except empty virtual dtor.

#2a) Deviation: java8 added default methods to interfaces

#2b) Deviation: c++ private inheritance from one concrete base class , suggested in [[effC++]]

#3) simple, minimal, low-interference base classes. Say the 2 base classes are completely unrelated, and each has only 1 virtual method. Any real use case? I can’t think of any but when this situation arises i feel we should use MI with confidence and caution. Similarly “goto” could be put to good use once in a blue moon.

Content vs Resource in a WPF build (MSVS)

If your wpf app needs to access a file (like my.jpg, or my.xml or whatever), you can include it with MSVS build-action CONTENT or RESOURCE.

1) RESOURCE (Avoid “EmbededResource” –  irrelevant) – will embed it in the assembly. No more separate file my.jpg in deployment.

2) CONTENT – will not include it in assembly but somehow registers (relative path to) the “loose file”. In the deployment, we usually put the loose file in the same folder as the assembly, so the application can reference this file with the bare name.

3) Sometimes you are lucky to get away without telling the builder about the file . Not recommended. As far as possible, any file needed by the app should be “included” somehow.

4) However, if the file name is known only at run time then it’s technically impossible to “include” it at build time. Must try other tricks.

DProp ^ CLR prop as SOURCE of data binding

See other posts on INPC. This is just another quick learning note.

You need INotifyPropertyChange if you use a regular property as Source of data binding. The host class (usually a VM) need to

implement INPC. Otherwise, changes to the property won't show up.

Is INPC required if the source is a DProp? I don't think so.

If you bind a regular collection (as Source) to an items control, then the collection class must implement INotifyCollecitonChanged,

otherwise add/delete won't show up. ObservableCollection is a subclass.

AttachedProperty – first lesson

AProp is one of the sophisticated features in WPF IMHO. First get a grip on DependencyProp (DProp) — see other blog posts.

–motivation for AProp–
If you want a concrete justification for AProp, look no further than Dock. Many top top WPF experts pick Dock as the showcase of AProp. Don’t read about StackPanel or FontSize. Don’t both with inheritance – we will deal with them much later.

Focus on #1 usage. Don’t bother with the #2 or #3, such as the “inheritance” or the “service” patterns in http://msdn.microsoft.com/en-us/library/ms749011.aspx#howused

Spend enough time and go deep enough to understand the Dock usage, before digging deeper.

Here’s the Dock usage outlined on MSDN. “The DockPanel.Dock property is created as an attached property because it is designed to be set on child controls within a DockPanel, rather than on DockPanel itself. The DockPanel class defines the static AProp named DockProperty, and then provides the GetDock and SetDock *static* accessors for the AProp.

–storage of the AProp values–
Same as ordinary DProp. One hash table per child DependencyObject. Absolutely Irrelevant is the hash table of the dock panel.

[[Pro WPF & Silverlight MVVM]] says “Once a DependencyProperty is registered as an attached property using the DependencyProperty.RegisterAttached method, that property can be set on any DependencyObject subclass.

–how to set/get–
In xaml, the aprop “Dock” looks comfortably like any other property of the child (eg Button), but we know that DockPanel not Button defines this property. Therefore the setter has to be defined in DockPanel. A Xaml declaration would translate to

   DockPanel.SetDock(myButton, Dock.Left); //STATIC method call

Internally, this runs

  buttonArgument.SetValue(DockPanel.DockProperty, Dock.Left); //AP setter

Look at this AP Setter 3 times, 5 times until you clearly understands —

* SetValue() is a NON-static method defined in the base class DependencyObject. Internally this method uses that hash table thing. All DProp and AProp setters goes through this Choke point.
* Note the dock property is unrelated to the host object i.e. the button. This is the funny/magical thing about Attached Property.
* Physically, the button object’s (NOT the panel’s) hash table records key={theButton.type + DockProperty.name}, value=Left. This property is useful to the parent container (the doc panel) during layout. The dock panel will scan all children, querying this button’s dock property, and another button’s doc property …

MSDN said “Attached properties are a XAML concept, whereas dependency properties are a WPF concept“. The way you set a AProp is very natural in xaml but not in code.

–extreme freedom–
The top top experts like to emphasize the extreme flexibility to attach anything to anything, whether meaningful or not.

Bencon said something like “simplest way to explain an attached property is that it allows the place where the property is defined and the place where it is stored to be completely different classes that know nothing about each other. Property value can only be stored on DependencyObject objects (which happens to be the base class for most Avalon things).”

Nick said things like

“You can call panel.SetValue(CheckBox.CheckedProperty, true), and property engine will happily set that attached property to true. Doesn’t matter that nobody is ever going to try to read that property value. Doesn’t matter that the author of CheckBox probably never intended this.”

“From a property engine perspective, it’s irrelevant that Button happens to be inside a DockPanel. You could set DockPanel.Dock even if your parent is a Grid — that property won’t do any good, because Grid doesn’t look at the DockPanel.Dock property, but you can do it.”

–References————–
Bencon – http://blogs.msdn.com/b/bencon/archive/2006/07/26/more-advanced-attached-property-use-the-ramora-pattern.aspx
Nick — http://blogs.msdn.com/b/nickkramer/archive/2005/08/25/456024.aspx
MSDN — http://msdn.microsoft.com/en-us/library/ms749011.aspx#howused

gridbag-container = most versatile layout in swing/wpf

In swing/wpf, there exist 2 most versatile/flexible layout techniques — nested container  vs gridbag. It's also possible to combine the 2 techniques.

“Gridbag container” is a generic term.

* In wpf, the standard grid panel would meet this requirement.

* In Swing, we can use a JPanel with a gridbag layout manager.

* in html, we use a html table. Soon after I started using html, i realized (often nested) table is THE standard way to layout an html page.

However, popularity is different —

* in wpf, grid container is widely used and often the default container.
* in swing, gridbag container is too hard and seldom used.

button click using command ^ events, briefly

As illustrated in other blog posts (like http://bigblog.tanbin.com/2013/06/routed-events-learning-notes.html), a button click can be connected to (via xaml) a regular instance method in the xaml class (code behind), provided the method is an event handler. In this implementation, we are using a CLR event, not really routed event.

This simple design draws criticism such as tight coupling etc. There’s an alternative. Using commands, we can refactor to meet the same requirement. [[wpf succinctly]] has a simple example of this refactor.

Another book says — “In WPF and Silverlight, there are two ways to respond to user interaction: with events and with commands. Most controls will support both of these methods of interaction, but it seems more common for events to be exposed.

string member – char array ^ char ptr

I have no practical experienced on this topic. I seldom see people discussing it. Perhaps many didn’t know the char-array option or dare to try it.

Good use case for char-array — Suppose you know you will have a million instances of the struct, and all of them have an Address string about the same length. Then the char-array is a viable option.

Our /Cast of characters/ — lets say we have a Person struct (or class) with an Address field of a 99-char string.

[[headfirstC]] P286/220 point out (arguably) the most fundamental difference — the entire 99 bytes of char-array is allocated on-site, whereas in the char-ptr design only the 4-byte pointer [1] is stored on-site.

[1] pointer object, not pointer variable or pure-address

When you duplicate the struct, the char-array case is simpler. The char-ptr solution may require strdup(), malloc() and free().

With char-arrayh, you can get redundant copies of the same data.

The char-ptr solution allows 2 instances to share the same string in memory. Looks efficient and neat but could be tricky later on. Might hit dangling pointers.

Now suppose there’s a Resume field of maximum length 10KB. Char array option would waste memory since some Persons (kids and house wives) have an empty string.

Verdict — I feel in many real projects the char-array works fine and is easier to code and maintain.

## xaml’s job duties in a GUI app (in broad-strokes)

#1) lay out – the controls within a “container”. Lay out each sub-panel and sub-sub-pane. Lay out each leaf-node control in each panel.
** This is also html’s main job.
** strictly a Containment hierarchy, or “object tree”, good for xml
** containment hierarchy is needed for routed command and data context

# binding – command (+event handlers) to input controls
# binding – data binding to VM, with updates in both directions
# implicitly create instance fields (aka data members) of the code behind class
# style triggers

Which of these can be replaced with c# code? See other blog posts.

wpf tree-grid (like swing tree table)

I feel treegrid is the most useful variation of a grid

http://blogs.msdn.com/b/delay/archive/2009/09/23/if-it-walks-like-a-duck-and-talks-like-a-duck-it-must-be-a-treegrid-a-simple-xaml-only-treegrid-ui-for-wpf.aspx
is a xaml-only clever solution, without third-party tools.

http://www.codeproject.com/Articles/30721/WPF-TreeListView-Control is a different xaml-only solution.

http://dotnetlearning.wordpress.com/2010/09/19/treelistview-in-wpf-containing-heterogeneous-hierarchical-data/ is another xaml-only
solution.

## most useful xaml keywords, briefly

[[WPF unleashed]] has a one-pager on xaml keywords. I trimmed the list further to just 3 —

– x:Name specifies a name for a xaml element, which would become an instance field in the code-behind class. This is mostly to make it accessible programmatically. Handy!

– x:FieldModifier defines the visibility of that field, which is internal by default. Can be public, private etc. You can specify a field modifier for each x:name

– x:Code – embeds c# code in a cdata block

– x:XData? Took me a while to find a usage example. http://learnwpf.com/post/2006/03/20/How-do-I-bind-to-XML-data-in-WPF.aspx embeds an “island” of static data in xdata, and uses it “locally” in subsequent xaml. It’s kind of nice to collocate data + visual next to each other.

xaml – declarative ^ programmatic

[[Dynamic .net 4.0 applications]] P155 claims that

“Xaml is completely optional. Anything you can accomplish in xaml, you can accomplish in source code”

If you do that your c# code will be like swing. Verbose, with large number of objects — every aspect of the visual is usually some property, represented by some object.

Biggest Power feature — you can write code to “set up” what is usually declared in xaml. Programmatic set-up is dynamic, flexible, based on user input, not hardcoded in xaml. Xaml is declarative, representing a major advancement over the traditional programmatic approach. Here we reverse the trend.

There are many more xaml techniques when we combine the programmatic + declarative. One example http://www.codeproject.com/Articles/19112/Dynamic-User-Interfaces-in-WPF

You can easily write code to access the object tree (a type of object graph), whether it’s in xaml or created by code. This access is so easy that I feel xaml format was designed for programmatic access.

Make ViewModel get key events only when its host tab is on top

In a tabbed GUI, I have a distinct ViewModel object for each tab. For e.g., tab3 is backed by vm3 object. In it I have a keyboard event handler to manipulate a lot of private data in the vm3 object (and update screen). This handler should fire when Tab 3 is on top. However, vm3 object has no way to tell if Tab3 is on top. MVVM in action.

My Solution: the “code-behind” Mainpage.xaml.cs ctor to register a private this.Handle3 to the this.KeyUp event, where this.Handle3 has access to the Tab3 object, so long as Mainpage.xaml exposes the Tab3 as a field via x:Name.

Handle3() checks if Tab3 is on top and then directly calls vm3.handler. Feasible because Mainpage.xaml.cs has a reference to vm3.

This relies on the code-behind as the melting pot. A quick and dirty solution.

wpf dock panel ^ swing border layout

I don't remember the details of swing border layout. Dock panel is similar and fairly flexible.

Based on http://www.codeproject.com/Articles/30904/WPF-Layouts-A-Visual-Quick-Start

Red 1



Green 1

Pink

Blue 2

Yellow 1



Orange 1

Green 2

Note it matters which region is declared first.

– Left is declared before Bottom, so Left region swallows all real estate. The later-declared Bottom region is “constrained”.

– If we move the Bottom declaration ahead of Left, then Bottom region swallows all real estate, and Left region would be constrained.

swing box layout – hearsay

To overcome the first Box layout confusions, Let’s start with Y-axis layout – top-down insertion of JComponents.  (X-axis alignment would mean left-to-right insertion).

Each JComponent calls myComponent.setAlignmentX() in Y-axis layout. Note the X vs Y. They must be that way. This is a bit confusing. Here’s my explanation — Top-down insertion means inserting a new component underneath the last component, but if new component is tiny shall we push it to the left or to the right? The new component must specify “Put me to left” or “Put me to the right”.

setAlignmentX(Component.RIGHT_ALIGNMENT) actually uses a float constant == 1.0. In fact, all setAlignmentX/Y methods take a float input. 0.5 always means center. LEFT_ALIGNMENT (== 0.0) means “push me to far Left”.

(Now hold your breath — in X-axis layout, 0.0 means “push me to the top”. This confused the hell out of me initially.)

The above is the box layout behavior when all components in the layout share the Same alignment number (be it 0.5, 1.0 or whatever). The behavior is completely different when the alignment numbers are non-uniform.

Popular combinations —
— right-justified:
new BoxLayout(…, Y_AXIS);
everyJComp.setAlignmentX(1.0)

— centered:
new BoxLayout(…, Y_AXIS);
everyJComp.setAlignmentX(0.5)

layout in wpf vs swing, a few pointers

Layout is one of the most important tasks of a GUI coder (as well as the artist). I get layout questions in my GUI job interviews. Despite all the advancement, veterans would probably agree layout is non-trivial. Both WPF and swing have tons of features on layout.

Swing layout is sometimes challenging/painful, esp. with window resizing. There are various advanced layout managers created to address the pains – gridbag etc.

http://killertilapia.blogspot.sg/2012/11/making-sense-of-wpf-layouts.html has some good pointers on wpf with references of swing –

* By default, WPF apps have a base Grid layout. Get rid of it and use “Dock Panel” as your base.  Dock Panels are the same as swing Border layout. The idea is to place the menu on top (DockPanel.Dock=”Top”), status bar bottom (DockPanel.Dock=”Bottom”) and put a Grid at the center. Now you have a well-behaved desktop app that reacts well to window re-sizes. 
* The Grid control is like Swing’s GridBagLayout only easier to use.
* Positioning — Use the AM (Alignment/Margin) to position elements in a container.
* Spacing — Use the margin + padding for spacing. If 2 buttons are side by side, don’t put a blank label in-between them to create space.
** In contrast, swing uses glue — http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#filler

http://wpftutorial.net/LayoutProperties.html has good pointers too —

– height/width — All controls provide a Height and Width but don’t fixed sizing.
** Set the Width and Height of elements to Auto whenever possible.
** For precise control, use the MinHeight, MaxHeight, MinWidth and MaxWidth properties to define a acceptable range.

reentrant/recursive lock always uses acquire-count, across languages

I have seen c++ (boost) and c# documentations. Now I believe across languages all reentrant locks need to keep count of repeated “acquires” by the same thread. Lock is released only when count hits zero.

P273 [[concur programming on windows]] confirms that CLR monitors support reentrance by counting.

One Java reentrant lock (reentrant readwriteLock) has a max acquire count of 65535.

an event inherited from interface->abstract class->concrete class

In this class hierarchy, the event is declared in interface ICommand, then declared abstract in the abstract class, finally implemented in the concrete classes.
Note the abstract must declare it.
    abstract public class TanBinRelayCommand: ICommand{
        private Action methodToExecute;
        private Func<bool> isEnabled;
        public TanBinRelayCommand(Action methodToExecute, Func<bool> isEnabled)
        {
            this.methodToExecute = methodToExecute;
            this.isEnabled = isEnabled;
        }
        #region ICommand members
        ///

        /// who subscribes to this event? I think the command binding (or other objects in the xaml)
        ///

        bool ICommand.CanExecute(object obj) {
            if (this.isEnabled == null) return true;
           
            return this.isEnabled.Invoke();
        }
        void ICommand.Execute(object obj)
        {
            if (this.methodToExecute != null)
                this.methodToExecute.Invoke();
        }
        abstract public event EventHandler CanExecuteChanged;
       

a simple c# SaxParser – NamespaceTolerant

Note: like an istream, the reader has an internal position pointer. reader.Name can return the name of either an element or an attribute, depending on the position.
Note: one common iteration idiom uses Read(), which advances the pointer to the next start/end tag??.  Like a subway express train, it won’t stop at the attributes – local stops.
        ///

        /// It’s not easy to find a SAX parser in c#
        /// It’s not easy to find a xml parser that tolerates undeclared namespaces
        ///
        /// Here’s a solution
        ///

        ///
        private static void SaxParser_NamespaceTolerant(string arg_xmlFullStr)
        {
            using (XmlTextReader reader = new XmlTextReader(
                                         new StringReader(arg_xmlFullStr)))
            {
                reader.Namespaces = false; //ignore undeclared namespaces
                while (reader.Read())
                {
                    if (string.IsNullOrWhiteSpace(reader.Name)) continue;
                    if (reader.IsStartElement())
                    {
                        Dump(reader.Name);
                        if (reader.HasAttributes)
                            while (reader.MoveToNextAttribute())
                                Dump(“\t” + reader.Name + “=” + reader.Value);
                    }
                }
            }
        }

smart ptr = a class instance; raw ptr = holder of an address

(perhaps merge with another post on raw ptr vs smart ptr)

A raw pointer is exactly 32 bit (assuming a 32bit machine). To be precise, we mean a “pointer object”. Given the monolithic nature of this /construct/, its behavior is transparent and well-understood.

A smart ptr acts like a raw pointer but is a class instance, a more sophisticated /construct/. Each standard raw-ptr “operation” is carefully emulated.

One of the operations is “copying a ptr”. A smart ptr is designed for pass by value (pbclone). Designed for cheap copy.

topics in c# interviews

protobuf!
serialize? presumably
xml? presumably
generics
dynamic type?
auto-boxing
task library?
linq? yes
ado.net? perhaps too simple for many jobs
web service? yes
async web service?
wcf? prominent
GC
COM?
unmanaged code?
p/invoke?
assembly, app domain
GAC
win services? ever asked?
algo with standard data structures (c# version). This tends to be a favorite at high-end jobs. This requires
** no threading,
** no generics,
** no linq,
** no wpf,
** no wcf

java generic Container<? extends Number>use case

Jargon warning — it’s rather abstract to talk about “super-types .. sub-types”, so I will use Number (a real super-type), Integer etc in this post.

Given

ArrayList<Number> liNum = new …;
ArrayList<Integer> liInt = new ..;

Rule 0 —- The method myCollection.add() is tolerant, lenient and easy. Wildcard never needed for add().

liNum.add(100); // fine
liNum.add(0.0001); //fine

Rule 1 —- cast/assignment/param-passing is stricter than add()
Rule 1a —- A List-of-subtype can’t be cast to List-of-SUPERtype.
Rule 1b —- A List-of-SUPERtype can’t be cast to List-of-subtype.

As a result, a method parameter declared as type A will not accept an argument of the type B, and vice-versa. Parameter passing is assignment.

There’s no “subsumption” between types A and B. See P16[[java generics]] for the (simple) reasons. STL has similar restrictions[4]

ArrayList<Integr> tmp5 = liNum; // wont’ compile
ArrayList<Number> tmp3 = liInt; // won’t compile

[4] See P662 [[Programming]] by Stroustrup. Given a vector of ptr2shapes, producer can insert ptr2square but consumer may expect a ptr2Circle!

Now, what if my method wants to accept any list of number, or list of int, or list of float etc?  (In other words, i want to accept a List-of-SUPERtype or a List-of-any-subtype?)

Rule 2 —- use wildcard to accept list-of-Number-OR-list-of-Integer

In other words, ArrayList<? extends Number> is a SUPERtype of ArrayList<Integer>. P18 [[java generics]].

ArrayList liWild6 = liNum; //ok
ArrayList liWild1 = liInt; //ok

I feel this is about the only common usage of wildcard.

c# DYNAMIC – TryCall_method1 on an Unidentified object#src

With dynamic type, we can try-call an arbitrary method m1(), which need not exist in any public interface. Behaviour — If the underlying type exposes m1, it is invoked. If unavailable you get a run time error, not a compile time error.

One usage idea — Instead of calling the standard ToString() on the unknown object, we want to try-call ToStringXml(), and pray the underlying type supports it. Traditionally, If we have a few types to add ToStringXml(), we would prefer compile-time type check by introducing an interface IXmlDumper. However, if you have 55 types that could pass into TryCall() and 33 of them exposes ToStringXml(), you may need to cast to IXmlDumper then call ToStringXml(). Worse, you would need to edit source code for the 33 types!

With dynamnic type, basically the compile-time type check is postponed to run time. Compile time type check would need m1() declared in the type C, like —

C c = new C(); c.m1();

But if we use dynamic, and type-check at run time, then we don’t need m1() exposed on any public interface —

dotnet thread pool, tips from Pravin

http://www.howdoicode.net/2013/04/net-thread-pool.html has some good tips

Pool threads are always background. Un-Configurable.

Consider creating your own thread if Synchronization needed — If we rely on synchronization to start, wait and stop the work done by the thread, then it is very likely that the task duration will increase and could lead to starvation very soon. If we have to use WaitHandles, locks or other synchronization techniques – then creating our own threads would be a better option.

Consider creating your own thread if Longer duration of work — Thread pool is to be used only when the work is of short duration. The faster the thread completes its work and goes back to the pool, the better performance. If threads are assigned to work for something very long, after some time starvation could occur. New threads are not created in the pool after a limit is reached, and if all threads are busy – the work may not be performed at all.

Stoch Lesson 19 N@T is !! a TVRV

See Lesson 05 about norm().
See Lesson 15 about TVRV.

If we say some measurable value x ~ norm(m,v), then this x shows a normal distribution with mean m and variance v. I feel it’s safe to say x is from a particular noisegen, which is /characterized/ by the pair m and v.

Now, this x is NOT always a TVRV. Instead, when we say something follows some distribution, we are looking at the crystal ball:

– This x could be the future value of a TVRV at a specific target date, or
– This x could be the _increment_ in a TVRV over a future interval.

In both cases above, x is a Noisegen Output @ a Future Time — N@T. It’s rather useful to pin down whether some item (in a big formula) is a N@T or a TVRV. Not always obvious. Need a bit of clear thinking.

Stoch lesson 05 – Level^Stepsize ..

A3: stepsize_i. The Level_i value may or may not be normally distributed if we plot the 9999 realizations, but that depends on some factors. For example, if the noisegen is identical and independent on every query then we can rely on Central Limit Theorem. For stock prices that’s not the case.
———-
In this series of lessons, I will create a set of “local jargon” used in later blog posts. First, Imagine the “Level” [Note 1] of a time-varying random variable W is a random walker taking up or down steps at regular intervals. At step_i, the stepsize_i [Note 2] is generated from a (Gaussian or otherwise) noisegen such as a computer. Level_i is the sum of all previous steps, positive or negative, i.e.

    Level_i = stepsize_1 + stepsize_2 + ….stepsize_i

It’s important to differentiate Level_i vs stepsize_i. Q3: which one of them has a normal distribution? Answer is hidden somewhere.

Notation is important here. It’s extremely useful to develop ascii-friendly symbols, with optional font sizing. These notations will be used in subsequent “lessons”. Here are a few more notations and jargon —

Let’s divide the total timespan T — from last-observation to Expiry — into n equal intervals. Denote a particular step as Step “i”, so first step has i=1. Let’s denote interval length as h=T/n = t_i+1 – t_i

I will use norm(a,b) to denote a Gaussian noisegen with mean=a and variance=b, so stdev=sqrt(b).

[1] The word “value” is too vague compared to Level.
[2] a.k.a. increment_i but less precise.

Stoch Lesson 15 – paths and time-varying random variables

See Lesson 05 for a backgrounder on the n steps of random walk…

RVRV is my own jargon, related to a stoch process. Before I’m confident to use the process jargon, I’ll use my own jargon.

Every time-varying-random-variable has a “Level” [1] at a given time, and therefore the variable has paths. The concept of path and the concept of time-varying-random-variable are intertwined.

For the random walker to go though the n steps one round, we query the noisegen n times. That’s a single realization of the random Process. If the walk is on a conveyer belt, then we see a “path”. One realization maps to one path. 9999 realizations would show 9999 paths and produce a good histogram.

Not everything we see in the formulas is a TVRV. The “h” isn’t; deltaAnything isn’t; drift rate isn’t … W is, though deltaW (ΔW)  isn’t. S is, though deltaS (ΔS) isn’t.

A note on randomness assumed in a stoch process — the future is usually assumed uncertain, but I won’t conclude that anything and everything in the future is random. The maturity value of a 12M time deposit is known, since default risk is assumed zero.

[1] actually not a single Level but multiple possible Levels. At a given time on each possible path, there’s a single Level.

java calling win32 tibrvsend.exe

            /**
            * daemon and the arg must be distinct strings
            *
             * quotes aren’t necessary
            */
            String[] strArrayWithoutQuote = new String[] {
                        “C:\\tibrv\\8.3\\bin\\tibrvsend”, “-daemon”,
                        “localhost:7500”, “-service”, “9013”, “-network”,
                        “;239.193.224.50,239.193.224.51;239.193.224.50”,
                        “GENERIC.g.TO_MTS_TRADE_REQUEST”, xml };
            System.out.println(Arrays.asList(strArrayWithoutQuote));
            execAndWait(strArrayWithoutQuote);
      }
      /**
      * http://www.rgagnon.com/javadetails/java-0014.html says If you need to
      * pass arguments, it’s safer to a String array especially if they contain
      * spaces.
      */
      static private void execAndWait(String[] command)
            try {
                  Runtime runtime = Runtime.getRuntime();
                  Process p = runtime.exec(command);
                  BufferedReader stdInput = new BufferedReader(new InputStreamReader(p
                              .getInputStream()));
                  String s = null;
                  while ((s = stdInput.readLine()) != null) {
                        System.out.println(s);
                  }
                  BufferedReader stdError = new BufferedReader(new InputStreamReader(p
                              .getErrorStream()));
                  while ((s = stdError.readLine()) != null) {
                        System.err.println(s);
                  }
                  p.waitFor(); // advised to do this after streams
            } catch (IOException e) {
                  throw new RuntimeException(e);
            } catch (InterruptedException e) {
                  throw new RuntimeException(e);
            }
      }

3 types of system services ] linux

Hi Pravin,

You asked about services written in c++. I googled and found that “service” has a specific meaning in linux/unix. http://www.comptechdoc.org/os/linux/howlinuxworks/linux_hlservices.html describes 3 types of services —

  • A one time only program run at boot-up to provide a function to the system such as kudzu, or keytable.
  • A program run as a local daemon upon startup that provides system services such as gpm, autofs, cron, and atd.
  • A program run as a network-daemon upon startup that provides networking services such as dhcpd, bootparamd, arpwatch, gated, and httpd.

The way I see it (no expert here), the standard *nix network daemons provide a Generic functionality at the System level – like DHCP, DNS, http, FTP, mail etc.

In contrast, a custom c++ engine used in finance has site-specific business logic. It often binds to a standard network port. Alternatively it may use database, RPC, (Corba?), MOM, or some proprietary protocol for network communication. In some cases the communication is entirely inter-process — no networking. Just IPC like shared memory, named pipes or unix domain sockets. I don’t know which communication mode is dominant. I guess shared memory and MOM are popular.

c++ no-arg ctor Call, without "new" (confusing)

(Any QQ value? Yes some crazy interviewers may ask.)

With “new” or with ctor arguments, the confusion is lower. Note since no “new” in this entire article, all the instances are constructed on stack or global area.

Compare to java, the c++ default construction syntax looks confusing even inconsistent —

   Account* addr = &Account() //instantiates temp.. and saves its address. Not sure if this is meaningful.

Note  Account() is parsed differently by compiler, depending on context. In each case below, Account() looks like a function call returning an Account on stack–
   Account() ; // on a line by itself this expression simply creates a local temp instance on stack then …DISCARDED.
 
Account().print(); // instantiates temp, then invokes a method

Account myAcct = Account(); //(tested) unpopular but rather consistent with new(), and consistent with other languages. Arguably Recommended to beginners though inefficient. http://stackoverflow.com/questions/11480545/explicit-copy-constructor explains what it does – 

{create a temporary Account on the rhs; Implicitly call the copy constructor to copy from that temporary into myAcct.Marking the copy ctor “explicit” would break this code, which is recommended by many authors.

    ifstream in = ifstream(“aaa.txt”); //broken – due to deleted copy ctor
    ifstream in(“aaa.txt”); //tested. P96[[essentialC++]]

    Account arr[] = {Account(),Account()}; //2 ctor calls. Actually, You can even pass args to initialize the two array elements.

   func1( Account() ); //creates a temp and pass it to func1(). Trailing parens are necessary. I feel this is practical and common, but I seldom notice it.
   throw Account(); //creates a temp and.. See P1035 [[c++Primer]]
   count_if(it1,it2,MyPredicateFunctor()); //creates a temp … See P107 [[DanielDuffy]] + P86[[essentialC++]]
———

std::string const var; // no parentheses … allocates a const instance
class MyClass{/*empty class*/};
MyClass var3; // ok allocates the object behind the variable without initializing it
MyClass const var2; // can’t compile but why?
Answer — You need to add empty no-arg ctor into MyClass to avoid a POD class.
————- 
(See the code below.) I personally prefer the Account(…) syntax above, and avoid #5/#6 below, but #5/#6 are popular. We just have to memorize the inconsistent syntax about them. #6 is clear and unambiguous. #9 seems to follow the #6 syntax “pattern” but alas! The correct way to achieve the purpose is #5.

    Account myAcct; // #5 declares a variable and allocates an Account object. Popular idiom, but somewhat inconsistent with other syntax constructs like the (123) caseTrailing parens are problematic and will lead to #9:
    Account myAcct(); // #9 NOT a ctor call; declares a function! Anything parseable as a func declaration is parsed that way. See P34 [[effSTL]]

     Account myAcct(123); // #6 initialize the myAcct variable with a stack object,  not  discarded.


c# enum is more like c++ or java@@

I told a c++ veteran that c# enum is more like c++ and less like java enum (singleton-based). He felt the other way. He points out that each c# enum has rich metadata, attributes, reflection, and even a few methods (from System.Object). Also, each enum type is a distinct type in the type system, which is important to reflection. You can use extension methods to add functionality specific to a particular enum type.

I now feel here’s the root of the issue — c# added lots of convenience features to simple value types like integer and float. A c# enum is fundamentally a special integer type. Passed by value, it behaves like a simple integer.

So my soundbyte is, if c++ enum is a plain integer, then c# enum is an integer enriched with convenience features.

Compared to java — java enums have real OO features, but c# enums get the features by other means.

g++ frontends ^ JVM/CLR bytecode

Have you ever wondered how gcc can compile so many languages. We know various dotnet languages all compile to the same IL code; JVM similar. Now I know that gcc uses a similar technique —

gcc has a frontend for java
gcc has a frontend for ObjectiveC
gcc has a frontend for c++
gcc has a frontend for Fortran

All of them produce the same intermediate code that feeds the true compiler, which produces assembly code.

c++mem mgmt: MSDN overview

http://msdn.microsoft.com/en-us/library/vstudio/hh438473.aspx is a brief but decent overview, illustrated with code snippets. I re-read in Nov 2017.

  • nonref variables as data members ! Default dtor is good enough 🙂
  • vector as data member ! Default dtor is good enough 🙂
  • (MSDN didn’t mention) shared_ptr and unique_ptr as data member. Default dtor is good enough 🙂
  • Heap-based vs stack-based — different techniques
  • c++ mem mgmt — “designed” for stack-based, so prefer stack as far as possible.
  • “observing” vs “owning” a heap object. An observing raw ptr can dangle but will never leak.

remote debugging MSVS@winxp; app@win2008 or 2003

http://www.atalasoft.com/cs/blogs/danbarvitsky/archive/2009/01/15/once-again-about-remote-debugging.aspx is the best guide I have found. Some comments —

Firewall – I didn’t need to change anything

— I ran the msvsmon.exe from a share. Just double click to run the exe
** msvsmon.exe need not run-as admin
** msvsmon.exe.config needs no change
** MUST add my name under msvsmon->tool->permission. Repeat in every msvsmon.exe session — Not saved.

— Attach to process
** transport = default
** qualifier = eqdpr@uwsamapos01, where eqdpr is the msvsmon.exe user on the remote
** refresh

Should see every process — Connected:) Once connected, before attach, msvsmon window will show who connected when.

You can start the remote app before or after Attach.

buffer overflow #trivial example

Quiz: give a simple example of buffer overflow

I feel this is a common error condition. As a serious techie (and job candidate), it’s good to have a concrete idea.

When you access a C array beyond the limit, I don’t know the exact error (perhaps platform dependent), but the generic condition is known as buffer overflow. See [[headfirstC]].

Not sure if there are other types of BOF, but this is one common example. Confirmed.

In general, a buffer is a pre-allocated chunk of memory with a fixed capacity. A low-level construct, it can’t relocate or expand — those features would require special data structures like vector. An array in C is such a buffer. I feel in C the other major data structure is an object graph with pointers. It follows that in C, buffer usually means an array.

An array in java is not expandable either.

RAII – heap alloc/deleted in separate functions

I think the standard pattern of RAII smart ptr is via a local variable. When it goes out-of-scope RAII kicks in. (P199 [[Essential C++]] is authoritative…)

Q: Now suppose a function is designed to new up an object on the heap, and pass (by several means) it out of the function. The pointee object on heap needs to be cleaned up in another method such as mymain(). So the smart ptr is not local variable. How can we use RAII smart ptr for this?

1) A tested technique – in some outer function such as mymain(), declare/create the smart ptr local variable and pass it (by ref NOT by value — tested in MSVS) into the factory function, which puts the heap ptr into the smart ptr. After using it in some other function, eventually we reach the end of mymain() and the local variable goes out of scope. Exception-safe.

2) A tested technique – a global vector holding a bunch of smart pointers. From anywhere we can save a “resource pointer” into the vector. From anywhere we can also clear the vector, and those pointee objects will receive the delete call. However, there’s no automatic, fool proof clean-up because a careless developer could forget to call clear(). Also, no exception-safety.

WPF Commanding components – fluff^barebones

Q: Key players in a typical commanding set-up?

The 4 key players identified in the MSDN article is the perspective from the builtin commands (RoutedCommand). I’d rather /unlearn/ the whole thing because I prefer a minimalist perspective.

1) ICommand (#1) is the single most important component. Together with the ViewModel (#2) and the xaml, it can meet many simple commanding requirements, without the CommandSource, CommandTarget, CommandBinding crap.

2) For a slightly more complex requirement, I feel these are the key players —
– ICommand instance
– command source instance
– ViewModel instance
– xaml (and code behind it)
? routed command? LG2. This is more advanced. A lot of xaml commands are much simpler
? command binding? LG2 See other posts.
? command target? LG2. Needed in RoutedCommand cases.
? CanExecuteChanged? not always needed
? CanExecute() can simply return true always.
? Execute() can simply hold the business logic rather than delegating to something else

CanExecute and CanExecuteChanged provide lots of flexibility, which is often unneeded in simple requirements.

ViewModel is relevant because there’s good reason to move logic out of the code behind, into … usually into the VM. Therefore the real command logic lives in the VM classes. Specifically, the Execute() logic often involves the VM. Ditto CanExecute()

http://relentlessdevelopment.wordpress.com/2010/03/30/simplified-mvvm-commanding-with-delegatecommand/ has a simple example. It illustrates xaml, view model, delegate command… It deliberately defines CanExecute and CanExecuteChanged, but never uses them!

##java inter-thread communication – practical designs

— Practical solutions–
– producer/consumer — best eg is invokeLater()
– wait/notify with the lock holding the “message” data
– a callable thread returning result or exception to the submitter thread via future task.
– global variables
– gemfire
– database, file — much slower
– (actually fairly practical in MOM designs) one thread sending a tibrv/jms message out of the host process to the MOM, another thread in the host process receiving it

— other designs —
join()
env var
parent passing data when creating a child thread

machine-wide msg queue + per-GUI-thread msg queue

(Backgrounder — Windows GUI are event-driven. Most events, including mouse/keyboard events, come through the message pump.)

http://msdn.microsoft.com/en-us/library/ms644927(v=vs.85).aspx shows that MSWin message queues come in 2 flavours —

1) a machine-wide msg queue

2) per-thread msg queue for each GUI thread, i.e. for each thread that creates visual window(s).

The system removes the user-generated messages, one at a time, from the machine-wide message queue, examines them to determine the destination (visual) window, and then posts them to the message queue of the thread that created the window. (Your own code on) the thread removes [1] messages from its queue and sends[2] them to the appropriate window procedure.

You usually write your own message loop to remove and send messages to window procedures. Applications with multiple threads can include a message loop in each thread that creates a window.

Only one message loop is needed for a message queue, even if an application contains many windows. DispatchMessage() always dispatches the message to the window procedure of the proper (visual) window.

[1] GetMessage() — An application can remove a message from the per-thread queue by using the GetMessage() function.

[2] DispatchMessage() — Application (your code) can use DispatchMessage()to send the message to a window procedure.

append _v2 to methods and classes

Relax — It’s fairly painless to use IDE to rename back and forth any
method or class.
When I feel one class is fairly complete among 20 incomplete or
“volatile” classes, I mark it someClass_v9, signifying it’s version 0.9.
When I create a mockup class I often mark it MyClass_v1. Useful when
putting together a paper aircraft so as to build out a prototype
architecture.
It helps to see these little information-radiators when so many things
are in a flux.

dynamic programming problems – my first look

The concept was well defined by the inventor but is now a bit vague. http://www.cs.berkeley.edu/~vazirani/algorithms/chap6.pdf is the best I have seen, but also check out http://mat.gsia.cmu.edu/classes/dynamic/dynamic.html . Below are some hallmarks of DP —

[M=math]
[C=comp science]

* solve sub-problems before solving the bigger problem. This approach/strategy is quite general
* [M] Principle of optimality
* [C] optimal substructure
* [M] stochastic dynamic programming
* [M] tail problems
* [C] DAGs

A major category of DP problems involve decision-making at discrete-time stages. Without stochastic elements, all the “contingent” decision-making could be (brought forward and) optimized upfront with clinical precision, like a robot analyzing a maze. In that case the stages are artificial, even unnecessary.

Therefore I now feel _ u n c e r t a i n t y _ is the major differentiator among DP problems. With uncertainty at each stage, we have no choice but break up the problem into periods. Without uncertainty, we can break up the problem artificially by period, or by segment…

Therefore, here are my classification of 3 categories of common DP problems (commonly found in tutorials) —
1) with uncertainty
2) with time periods without uncertainty
3) without time period. You create artificial stages. Often the simplest DP illustrations.

small c# trick to log the current value of a field

Suppose you want to log (“StaticOrNonStaticField_AgeInConfig = ” + StaticOrNonStaticField_AgeInConfig), but you anticipate renaming on this field. When anyone uses any IDE to renames it next month, you want the log message to change automatically. Here’s a trick

public static string GetMemberName(Expression<Func> expr){
var body = ((MemberExpression)expr.Body);
return body.Member.Name;
}

Log.Info(GetMemberName(() => StaticOrNonStaticField_AgeInConfig) + ” == ” + StaticOrNonStaticField_AgeInConfig);

delegate command with(out) CommandManager

Now I feel you can implement a basic delegate command with or without CommandManager. (My sample wpf application description is in another blog post.)

A) The original RelayCommand by Josh Smith uses CommandManager. With CommandManager, we developers don’t need to add InvalidateRequerySuggested() after some VM state change, since CommandManager will take care of that.

One consequence is, the CommandManager fires a hell lot of activity via (static) event CommandManager.RequerySuggested. Since our custom CanExecuteMyCommand() callback is in the inv list, it gets called every time.

B) Some prefer a home-grown delegate command without CommandManager. Event firing is better understood and less opaque than with CommandManager. However, we do need to remember to add something like MyCommand.RecheckStatus() in many places.

Here’s my guess — Since the inv list is no longer provided by CommandManager, we must provide it in our delegate command class. There’s one inv list per command instance. By contrast, the CommandManager has one application-wide inv list for all the command instances. The inv list is behind the application-wide static event.

invoking a delegate instance – explict Invoke()

Most c# folks take the shortcut by writing “this.myDelegateInstance();”. But this sugar-coated syntax masks off the distinction between a method and a delegate. C# syntax sugar coating trivializes this distinction because c# “wants” you to treat delegate instances as if it’s a method defined nearby. However, sometimes I want the distinction highlighted.

When the morphing hurts (in high-complexity codebase), I prefer the long-winded syntax myDelegateInstance.Invoke()

This kinda small tweaks can add up to a more readable codebase.

who subscribes to the ICommand.CanExecuteChanged event?

I put a breakpoint on the event add{} and found out exactly which object is subscribing to the ICommand.CanExecuteChanged event.

 

————— wpf_proj_readme.txt —————–

This entire wpf app has a single VM. Among other things it defines a bool method vm.CanExecuteSave(). Note VM isn’t subclass of ICommand; TanBinRelayCommand is. It’s just a generic relay command class.

 

Xaml has a textbox and a Save button. Textbox is data-bound to a string property in VM; button to an ICommand property in VM – consistency. Entire xaml uses the VM as the only data context, so all data bindings are between the xaml (visuals) and the VM (properties) – consistency.

 

This vm.CanExecuteSave() method (wrapped in a delegate) is passed in when instantiating TanBinRelayCommand, the Command object behind the button. Therefore button “dimmer” is connected to vm.CanExecuteSave() method. Later at runtime the button is dimmed when CanExecuteSave becomes false.

———————————————————–

 

Question is how does the runtime know when to requery CanExecuteSave(). The solution, as a standard pattern, is event subscription. Specifically, the button adds this.OnCanExecuteChanged() method into the inv list of the ICommand.CanExecuteChanged event.   But when is this method added into the inv list? At xaml initialization, HookCommand() performs this registration.

 

    abstract public class TanBinRelayCommand: ICommand{

        private Action methodToExecute;

        private Func<bool> isEnabled;

 

        public TanBinRelayCommand(Action methodToExecute, Func<bool> isEnabled)

        {

            this.methodToExecute = methodToExecute;

            this.isEnabled = isEnabled;

        }

        #region ICommand members

        ///

        /// who subscribes to this event? I think the command binding (or other objects in the xaml)

        ///

        bool ICommand.CanExecute(object obj) {

            if (this.isEnabled == null) return true;

           

            return this.isEnabled.Invoke();

        }

        void ICommand.Execute(object obj)

        {

            if (this.methodToExecute != null)

                this.methodToExecute.Invoke();

        }

        abstract public event EventHandler CanExecuteChanged;

       

GBM random walk – again

Mostly this write-up will cover the discrete-time process. In continuous, it’s no longer a walk [1]. Binomial tree, Monte Carlo and matlab are discrete.

Let’s divide the total timespan T — from last-observed to Expiry — into n equal intervals. At each step, look at ln(S_new/S_old), denoted r. (Notation is important in this field. It’s extremely useful to develop ascii-friendly symbols…) It’s good to denote the current step as Step “i”, so first step has i=1 i.e. r_1=ln(S_1/S_0). Let’s denote interval length as h=T/n.

To keep things simple let’s ignore the up/down and talk about the step size only. Here’s the key point —

Each step size such as our r_i is ~norm(0, h). r_i is non-deterministic, as if controlled by a computer. If we generate 1000 “realizations” of this one-step stoch process, we get 1000 r_i values. We would see a bell-shaped histogram.

What’s the “h” in the norm()? Well, this bell has a stdev, whose value depends on h. Given this is a Wiener process, sigma = sqrt(h). In other words, at each step the change is an independent random sample from a normal bell “generator” whose stdev = sqrt(step interval)

[1] more like a victim of incessant disturbance/jolt/bombardment. The magnitude of each movement would be smaller if the observation interval shortens so the path is continuous (– an invariant result independent of which realization we pick). However, the same path isn’t smooth or differentiable. On the surface, if we take one particular “realization” with interval=1microsec, we see many knee joints, but still a section (a sub-interval) may appear smooth. However, that’s the end-to-end aggregate movement over that interval. Zooming into one such smooth-looking section of the path, now with a new interval=1nanosec, we are likely to see knees, virtually guaranteed given the Wiener definition. If not in every interval then in most intervals. If not in this realization then in other realizations. Note a knee joint is not always zigzag . If 2 consecutive intervals see identical increments then the path is smooth, otherwise the 2-interval section may look like a reversal or a broken stick.

DelegateCommand – various sample implementations

http://wpftutorial.net/DelegateCommand.html is a simple and clean DelegateCommand class, very similar to my own. No complete WPF sample app included.

http://blog.rdeverett.com/post/812093504/wpf-delegatecommand is similar but a bit old-fashioned

http://relentlessdevelopment.wordpress.com/2010/03/30/simplified-mvvm-commanding-with-delegatecommand/ is similar

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx (MSDN) has a similar simple class named RelayCommand

Brownian random walk -> sqrt(t)

A longer title would be “from random walk model to a stdev proportional to sqrt(t)”

Ignore the lognormal;
Ignore the rate of return;
Ignore stock prices. Just imagine a Weiner process. I find it more intuitive to consider the discrete time random walk. Assuming no drift, at each step the size and direction of the step is from a computer that generates a random number from a normal distribution like MSExcel normsinv(rand()), I’d like to explain/derive the important observation that t units of time into the Future, the UNKNOWN value of x has a Probability distribution that’s normal with mean 0 and stdev √t.

Now, time is customarily measured in years, but here we change the unit of time to picosecond, and assume that for such a short period, the future value of x has a ProbDist “b * ϵ(0,1)”, whose variance is b*b. I think we can also use the notatinon n(0,b*b).

Next, for 2 consecutive periods into the Future, x takes 2 random steps, so the sum (x_0to1 + x_1to2) also has a normal distribution with variance 2b*b. For 3 steps, variance is 3b*b…. All because the steps are independent — Markov property.

Now if we measure t in picosecond, then t means t picosecond, so the Future value after t random steps has a normal distribution with variance t b*b. So stdev is b*√t

For example, 12 days into the future vs 3 days into the future, the PD of the unknown value would have 2 normal distributions. stdev_12 = 2 * stdev_3.