Sunday, April 22, 2012

Visitor Design Pattern


(1) IAccept will Accept any IVisitor, which include all object types in signature.
(2) All participating object types implement IAccept with boiler template code visit(this)
(3) Visitors are responsible to implement how to visit a type.

Benefit: Ensure new visitor must know how to visit all types, and these types does not
need to change to allow new visitors.






 

    #region IAccept Universal Visitor

    public interface IVisitor
    {
        // List the universe of objects
        void Visit(Swap sw);
        void Visit(Option o);
        void Visit(Bond b);
    }

    public interface IAccept
    {
        void Accept(IVisitor visitor);
    }

    #endregion

    #region Universal objects  Accept any Visitor(this) --boiler template code

    public class Swap : IAccept
    {
        public void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }
    public class Option : IAccept
    {
        public void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }
    public class Bond : IAccept
    {
        public void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    #endregion

#region Risk Visitor -- must know how to visitor any objects

    public class RiskVisitor : IVisitor 
    {
        public void Visit(Swap sw)
        {
            Console.WriteLine("Special works related to Risk of SWAP");
        }

        public void Visit(Option o)
        {
            Console.WriteLine("Special works related to Risk of Option");  
        }

        public void Visit(Bond b)
        {
            Console.WriteLine("Special works related to Risk of Bond");
        }
    }

    #endregion

    #region Pricing Visitor -- must know how to visitor any objects

    public class PricingVisitor : IVisitor
    {
        public void Visit(Swap sw)
        {
            Console.WriteLine("Special works related to Pricing of SWAP");
        }

        public void Visit(Option o)
        {
            Console.WriteLine("Special works related to Pricing of Option");
        }

        public void Visit(Bond b)
        {
            Console.WriteLine("Special works related to Pricing of Bond");
        }
    }

   #endregion


            // (1)  each visitor visit object
            RiskVisitor rv = new RiskVisitor();
            rv.Visit(new Swap());
            rv.Visit(new Option());

            PricingVisitor pv = new PricingVisitor();
            pv.Visit(new Swap());
            pv.Visit(new Option());


            // (2) each object accept any visitor
            Swap sw = new Swap();
            sw.Accept(new RiskVisitor());
            Console.ReadLine();

Saturday, April 21, 2012

WPF Breadcrumb markup


                            <ListBox  Padding="0" DockPanel.Dock="Left"  VerticalAlignment="Center" x:Name="lbBreadCrumb" MinWidth="300" Background="Transparent" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Hidden" SelectionChanged="ListBox_SelectionChanged">
                                <ListBox.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <StackPanel Margin="8,0,0,0" Orientation="Horizontal"></StackPanel>
                                    </ItemsPanelTemplate>
                                </ListBox.ItemsPanel>
                                <ListBox.ItemContainerStyle>
                                    <Style TargetType="{x:Type ListBoxItem}">
                                        <Setter Property="Background" Value="LightGray"/>
                                        <Setter Property="BorderBrush" Value="LightGray"/>
                                        <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
                                        <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
                                        <Setter Property="Padding" Value="0"/>
                                        <Setter Property="SnapsToDevicePixels" Value="true"/>
                                        <Setter Property="Template">
                                            <Setter.Value>
                                                <ControlTemplate TargetType="ListBoxItem">
                                                    <DockPanel LastChildFill="True" Margin="-8,0,0,0">
                                                        <Path x:Name="ArrowTip" DockPanel.Dock="Left" Stroke="LightGray" Fill="LightGray" Data="F1 M 112,144L 104,144L 112,160L 104,176L 112,176" Stretch="Fill" Height="32" Width="12"  />
                                                        <Path x:Name="Arrow" DockPanel.Dock="Right" Stroke="LightGray" Fill="LightGray" Data="F1 M 168,144L 176,160L 168,176" Stretch="Fill" Height="32" Width="12"  />
                                                        <Border Name="Border" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Background="{TemplateBinding Background}" BorderBrush="LightGray" Padding="{TemplateBinding Padding}" BorderThickness="0,1,0,1" VerticalAlignment="Center" Margin="-1,0,-1,0" >
                                                            <ContentPresenter />
                                                        </Border>
                                                    </DockPanel>
                                                    <ControlTemplate.Triggers>
                                                        <Trigger Property="IsSelected" Value="true">
                                                            <Setter TargetName="Border" Property="Background" Value="Gray"/>
                                                            <Setter TargetName="Arrow" Property="Fill" Value="Gray"/>
                                                            <Setter TargetName="ArrowTip" Property="Fill" Value="Gray"/>
                                                        </Trigger>
                                                        <Trigger Property="IsEnabled" Value="false">
                                                            <Setter Property="Foreground" Value="Red"/>
                                                        </Trigger>
                                                    </ControlTemplate.Triggers>
                                                </ControlTemplate>
                                            </Setter.Value>
                                        </Setter>
                                    </Style>
                                </ListBox.ItemContainerStyle>
                                <ListBox.ItemTemplate>
                                    <DataTemplate>
                                        <DataTemplate.Resources>
                                                <local:ContentToVisibilityConverter x:Key="c2vConverter" />
                                        </DataTemplate.Resources>
                                        <DockPanel VerticalAlignment="Center" Height="30">
                                            <Label DockPanel.Dock="Left" FontSize="8" Content="{Binding Name, FallbackValue=Tagname NA}" VerticalAlignment="Center" Name="lb"/>
                                            <Button  Width="20" Height="20" Background="#FF1D5BBA"  Margin="0" Style="{StaticResource GlassButton}" Visibility="{Binding ElementName=lb, Path=Content., Converter={StaticResource c2vConverter}}">
                                                <Image Width="15" Height="15" Source="images\refresh.png" ToolTip="Refresh Dashboard" MouseLeftButtonDown="RefreshImage_MouseLeftButtonDown" />
                                            </Button>
                                        </DockPanel>
                                    </DataTemplate>
                                </ListBox.ItemTemplate>
                            </ListBox>

Show WPF Form considering taskbar


     // Considering space for Taskbar at the bottom.
            MONITORINFO monitorInfo = new MONITORINFO();
            int MONITOR_DEFAULTTONEAREST = 0x00000001;
            System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
            System.IntPtr monitor = MonitorFromWindow(handle, MONITOR_DEFAULTTONEAREST);
            GetMonitorInfo(monitor, monitorInfo);
            RECT rcWorkArea = monitorInfo.rcWork;
            RECT rcMonitorArea = monitorInfo.rcMonitor;

            M.Height = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);// SystemParameters.MaximizedPrimaryScreenHeight - 20;
            M.Width = SystemParameters.MaximizedPrimaryScreenWidth - 15;

            M.Top = 0; M.Left = 0;

        #region Win32 API

        [DllImport("user32")]
        internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);

        /// 
        /// 
        /// 
        [DllImport("User32")]
        internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

        #endregion

Saturday, March 24, 2012

Dynamic Programming Tree in MATLAB


function [x]=dynamicProgTree()
% states --oil reserve
x(1).rsrv=[600000];
x(2).rsrv=[500000 400000];
x(3).rsrv=[400000 300000 200000];
x(4).rsrv=[300000 200000 100000 0];

% Normal and Enhanced Pumping
% Value Onward at t=4 is 0 due to lease expiration
x(4).Vn=[0 0 0 0];
x(4).Ve=[0 0 0 0];
x(4).V=max(x(4).Vn,x(4).Ve);

% Value
% Onward=oilPrice*policy-multiplier*policy^1/reserve+discountedValueOnward
for i=1:3
   x(3).Vn(i)=40*100000- 1*100000^2/x(3).rsrv(i)+0.9*x(4).V(i);
   x(3).Ve(i)=40*200000- 20*200000^2/x(3).rsrv(i)+0.9*x(4).V(i+1);
end
% ValueOnward= Max (Norma, Enahnced)
x(3).V=max(x(3).Vn,x(3).Ve);

for i=1:2
   x(2).Vn(i)=30*100000- 1*100000^2/x(2).rsrv(i)+0.9*x(3).V(i);
   x(2).Ve(i)=30*200000- 20*200000^2/x(2).rsrv(i)+0.9*x(3).V(i+1);
end
x(2).V=max(x(2).Vn,x(2).Ve);

for i=1:1
   x(1).Vn(i)=45*100000- 1*100000^2/x(1).rsrv(i)+0.9*x(2).V(i);
   x(1).Ve(i)=45*200000- 20*200000^2/x(1).rsrv(i)+0.9*x(2).V(i+1);
end
x(1).V=max(x(1).Vn,x(1).Ve);
end


Wednesday, February 29, 2012

Deep Copy Helper


       public static T DeepCopy<T>(T obj)
        {
            if (obj == null)
                throw new ArgumentNullException("Object cannot be null");
            return (T)Process(obj);
        }

        static object Process(object obj)
        {
            if (obj == null)
                return null;
            Type type = obj.GetType();
            if (type.IsValueType || type == typeof(string))
            {
                return obj;
            }
            else if (type.IsArray)
            {
                Type elementType = Type.GetType(
                     type.FullName.Replace("[]", string.Empty));
                var array = obj as Array;
                Array copied = Array.CreateInstance(elementType, array.Length);
                for (int i = 0; i < array.Length; i++)
                {
                    copied.SetValue(Process(array.GetValue(i)), i);
                }
                return Convert.ChangeType(copied, obj.GetType());
            }
            else if (type.IsClass)
            {
                object toret = Activator.CreateInstance(obj.GetType());
                //FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                //            BindingFlags.NonPublic | BindingFlags.Instance);
                FieldInfo[] fields = GetAllFields(type).ToArray();
                foreach (FieldInfo field in fields)
                {
                    object fieldValue = field.GetValue(obj);
                    if (fieldValue == null)
                        continue;
                    field.SetValue(toret, Process(fieldValue));
                }
                return toret;
            }
            else
            {
                return null;
                //throw new ArgumentException("Unknown type");
            }
        }

        public static IEnumerable<FieldInfo> GetAllFields(Type t) { 
            if (t == null)         return Enumerable.Empty<FieldInfo>();
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance
                | BindingFlags.DeclaredOnly; 

            return t.GetFields(flags).Union(GetAllFields(t.BaseType)); 
        } 

Note that If we restrict to Serializable then using Memory Stream can deep copy

   class Program
    {
        static void Main(string[] args)
        {
            Outside o = new Outside() { Data = new Inside() { Name = "n1", Price = 199 } };

            Outside o_sc = o.ShadowCopy;
            o_sc.Data.Name = "Changed"; // change o as well since Shadow copy reference
            Outside o_dc = o.DeepCopy;
            o_dc.Data.Name = "Reset"; // not affect o
        }
    }

    [Serializable]
    public class Outside
    {
        public Inside Data { get; set; }
        public Outside ShadowCopy { get { return  MemberwiseClone() as Outside ; } }
        public Outside DeepCopy
        {
            get
            {
                MemoryStream m = new MemoryStream();
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(m, this);
                m.Position = 0;
                return b.Deserialize(m) as Outside;
            }
        }
        
    }

    [Serializable]
    public class Inside
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }

Sunday, February 19, 2012

HTML5 Canvas API


<canvas w h id="cv"/>

var ctx=document.getElementById("cv").getContext('2d');

Path Drawing:
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x1,y1);
ctx.closePath();

Fill
ctx.fillRec();
ctx.fillStyle='rgba(0,0,0,0.2)'; alpha 0.2 for black.

Mouse move vs. Touch move
cv.onMouseMove= function Draw(e) {..}
document.addEventListener('touchmove', function (e) { });

e.preventDefault(); not allow Ipad Giggle.
e.targetTouches[0].pageX;
ctx.transform (matrix+d);
cx.scale(60%);




Tuesday, January 31, 2012

Correlated Action ComboBox Behavior


<UserControl xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             xmlns:loc="clr-namespace:TestCorrTextBoxCustBehavior">

       <ComboBox Height="23" HorizontalAlignment="Left" Margin="12,48,0,0" Name="cb1" VerticalAlignment="Top" Width="120" >
            <i:Interaction.Behaviors>
                <loc:CorrelatedActionComboBoxBehavior SourceRegularExpression="['Basket Swap'|'CDS']" SourceTriggerType="RegExpression"  TargetControlId="lb1" TargetActionType="SetValue" TargetValue="2"/>
            </i:Interaction.Behaviors>
            <ComboBoxItem>1</ComboBoxItem>
            <ComboBoxItem>Basket Swap</ComboBoxItem>
            <ComboBoxItem>CDS</ComboBoxItem>
        </ComboBox>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="268,48,0,0" Name="textBox2"  VerticalAlignment="Top" Width="120" />
        <ListBox Name="lb1" Width="100" Height="200" Margin="355,91,48,20">
            <ListBoxItem>1</ListBoxItem>
            <ListBoxItem>2</ListBoxItem>
            <ListBoxItem>3</ListBoxItem>
        </ListBox>



   public class CorrelatedActionComboBoxBehavior : Behavior</ComboBox>
    {

        public SourceTriggerType SourceTriggerType { get; set; }
        public string SourceRegularExpression { get; set; }
        public string TargetControlId { get; set; }
        public TargetActionType TargetActionType { get; set; }
        public string TargetValue { get; set; }
       
        protected override void OnAttached()
        {
            if (!(AssociatedObject is ComboBox)) return;
            object obj = AssociatedObject.Parent;
            Control mw = ((System.Windows.Controls.Panel)(obj)).Parent as Window;
            if (mw==null)
             mw = ((System.Windows.Controls.Panel)(obj)).Parent as Control;
            if (mw == null) return;

            AssociatedObject.DropDownClosed += (sender, e) =>
                { 
                    ComboBox cb = AssociatedObject as ComboBox;
                    if (SourceTriggerType == SourceTriggerType.RegExpression)
                    {
                        Regex r = new Regex(SourceRegularExpression);

                        Control c = FindChild(mw, TargetControlId);
                        c.IsEnabled = true;
                        if (r.IsMatch(cb.Text) )
                        {
                           if ( TargetActionType== TargetActionType.Disable ) c.IsEnabled = false;
                           if (TargetActionType == TargetActionType.SetValue)
                           {
                               ListBox lb = c as ListBox;
                               if (lb != null && TargetValue!="") SetListBoxValue(lb, TargetValue);
                           }

                        }
                    }
                };
        }

        private void SetListBoxValue(ListBox lb, string p)
        {
            for(int i=0;i< lb.Items.Count;i++)
            {
                if ((lb.Items[i] as ListBoxItem).Content.ToString()  == p) lb.SelectedIndex = i;
            }
        }

        public static T FindChild(DependencyObject parent, string childName)    where T : DependencyObject {      
            // Confirm parent and childName are valid.   
            if (parent == null) return null;    
            T foundChild = null;    
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);  
            for (int i = 0; i < childrenCount; i++)   {   
                var child = VisualTreeHelper.GetChild(parent, i);    
                // If the child is not of the request child type child   
                T childType = child as T;    
                if (childType == null)     {     
                    // recursively drill down the tree    
                    foundChild = FindChild(child, childName);     
                    // If the child is found, break so we do not overwrite the found child.     
                    if (foundChild != null) break;     }    
                else if (!string.IsNullOrEmpty(childName))     {   
                    var frameworkElement = child as FrameworkElement;     
                    // If the child's name is set for search     
                    if (frameworkElement != null && frameworkElement.Name == childName)       {    
                        // if the child's name is of the request name       
                        foundChild = (T)child;         break;       }     }  
                else     {       
                    // child element found.      
                    foundChild = (T)child;       break;     }   }  
            return foundChild; } 

     }

    public enum SourceTriggerType
    {
        RegExpression
    }

    public enum TargetActionType
    {
        Disable,
        SetValue
    }