Saturday, January 7, 2017

InvokeCommandAction passing in EventArgs


using System;
using System.Linq;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Interactivity;

    /// <summary>
    /// For Trigger action Invoke command, Trigger Action will set Invoke Parameter so the foloowing can pass along EventArgs
    ///<i:EventTrigger EventName="MouseLeftButtonDown">
    ///<invokeActions:InvokeDelegateCommandAction>
    ///    <invokeActions:InvokeDelegateCommandAction.CommandParameter>
    ///        <MultiBinding Converter="">
    ///            <Binding/>
    ///            <Binding Path="InvokeParameter" RelativeSource="{RelativeSource Self}" />
    /// </summary>
    public sealed class InvokeDelegateCommandAction : TriggerAction<DependencyObject>
    {
        private string _commandName;

        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter", typeof(object), typeof(InvokeDelegateCommandAction), null);

        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty);}
            set { SetValue(CommandParameterProperty, value);}
        }

        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
            "Command", typeof(ICommand), typeof(InvokeDelegateCommandAction), null);

        public ICommand Command
        {
            get { return (ICommand)this.GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value);}
        }
 
        public static readonly DependencyProperty InvokeParameterProperty = DependencyProperty.Register(
            "InvokeParameter", typeof(object), typeof(InvokeDelegateCommandAction), null);

        public object InvokeParameter
        {
            get { return GetValue(InvokeParameterProperty); }
            set { SetValue(InvokeParameterProperty, value); }
        }

        public string CommandName
        {
            get
            {
                return _commandName;
            }
            set
            {
                if (CommandName != value)
                {
                    _commandName = value;
                }
            }
        }

        protected override void Invoke(object parameter)
        {
            InvokeParameter = parameter;

            if (AssociatedObject == null)
                return;

            var command = ResolveCommand();
            if ((command != null) && command.CanExecute(CommandParameter))
            {
                command.Execute(CommandParameter);
            }
        }

        private ICommand ResolveCommand()
        {
            ICommand command = null;
            if (Command != null)
            {
                return Command;
            }

            var frameworkElement = AssociatedObject as FrameworkElement;
            if (frameworkElement != null)
            {
                var dataContext = frameworkElement.DataContext;
                if (dataContext != null)
                {
                    PropertyInfo commandPropertyInfo = dataContext
                        .GetType()
                        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                        .FirstOrDefault(
                            p =>
                            typeof(ICommand).IsAssignableFrom(p.PropertyType) &&
                            string.Equals(p.Name, CommandName, StringComparison.Ordinal)
                        );

                    if (commandPropertyInfo != null)
                    {
                        command = (ICommand)commandPropertyInfo.GetValue(dataContext, null);
                    }
                }
            }
            return command;
        }
    }
}

Tuesday, December 20, 2016

C++ Unit Test Framework Catch


1. class comparison in REQUIRE need operator == and  toString/template specialization/insertion operator
2. CATCH_TRANSLATE_EXCEPTION customize ex.message

 #define CATCH_CONFIG_MAIN  in stdafx.h

#include "stdafx.h"
#include "c:\__tools\catch.hpp"
#include <ostream>
#include <exception>

 class Book
{
public:
 int Id;
 bool operator==(const Book& b)
 {
  return b.Id == Id;
 }

};

//std::ostream& operator<<(std::ostream& os, Book const& b)
// {
// os << "overloading OS";
// return os;
//};
namespace Catch {
 template<> struct StringMaker<Book> {
  static std::string convert(Book const& value)
  {
   return "String Maker Specialization";
  }
 };

 //std::string toString(Book const& i)
 //{
 // return "to string for Book";
 //}
}
class myException : public std::exception
{
public:
 virtual const char* what() const throw()
 {
  return " my exception";
 }
};

CATCH_TRANSLATE_EXCEPTION(myException& ex)
{
 return ex.what();
}

TEST_CASE("This is a catch test","[Equal][LOG]")
{
 Book b1, b2;
 b1.Id = 90;
 INFO("Start Testing");
 REQUIRE(b1 == b2);
 WARN("One assertion failed");
 REQUIRE_FALSE(1 == 1);

}

TEST_CASE("This is another catch test","[CHK][EXP]")
{
 CHECK_FALSE(1 == 1);
 throw myException();
}



Saturday, December 10, 2016

Compile Time Check IsNullable and IsReferenceType


        public TimeSpan i { get; set; }
        public TimeSpan? j { get; set; }
        public string k { get; set; }
        public Status? Status { get; set; }
        public Data st1 { get; set; }
        public Data? st2 { get; set; }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            
            bool b1 = IsNullable(i);
            bool b2 = IsNullable(j);
            bool b3 = IsNullable(k);
            bool b4 = IsNullable(Status);
            bool b5 = IsNullable(st1);
            bool b6 = IsNullable(st2);
            bool b7 = IsReferenceType(k);
        }
         static bool IsNullable<T>(T t) { return false; }
         static bool IsNullable<T>(T? t) where T : struct { return true; }
         static bool IsReferenceType<T>(T t) where T : class { return true; }
    

    public enum Status
    {
        None,
        Ok,
        Error
    }

    public struct Data
    {

    }

Thursday, December 8, 2016

Shift Operator, ilog2 and test power of 2

(1) shift left of 1 generate all powers of 2.
(2) ilog2 is template specialization.
(3) shift 1 by ilog2(n) will get back n for power of 2 only
(4) compiler say too complex when using recursion for non-template function is_power_of_2

#include "stdafx.h"
#include <iostream>

using namespace std;

template <size_t X>
struct ilog2
{
 enum {value=(1+ilog2<X/2>::value) };
};

template<>
struct ilog2<1> {enum {value=0}; };

template<size_t N>
bool is_pow_of_2()
{
 return ((size_t)1 << ilog2<N>::value == N);
};

int main() {
 
 cout << (1 << 3) << endl; // 8
 cout << (1 << 9) << endl; // 512=2 power 9
 
 cout << ((size_t)1 << ilog2<9>::value == 9) << endl;
 cout << ((size_t)1 << ilog2<512>::value == 512) << endl;
 
 cout << is_pow_of_2<9>() << endl;
 cout << is_pow_of_2<512>() << endl;
 return 0;
}



Wednesday, December 7, 2016

locking, lock free and wait free

locking --- lock_guard + mutex
lock free --- atomic + CAS
wait free --- atomic +fetch_add
ring buffer-- producer makes progress without any wait, so wait-free.


using namespace std;
typedef unsigned long ulong;

ulong _shared = 123UL;
int main() {
 {
  ulong* p=nullptr;  //locking
  *p = _shared;
  mutex M;
  {
   lock_guard<mutex> l(M);
   ++(*p);
  }
 }
 atomic<ulong>* p=0;  //lock free
 *p = _shared;
 ulong xl = p->load(memory_order_relaxed);
 while (!p->compare_exchange_strong(xl, xl + 1, std::memory_order_relaxed)) {}

 p->fetch_add(1, memory_order_relaxed);  //wait free


 // cache line is 64 bytes, ul is 8 bytes, so thread>8=> sit on separate cache line, no sharing faster.

 

 return 0;
}

lock_guard vs shared_lock is exclusive vs. shared in c++14

(1) C++ 14/17 rare write mostly read is Microsoft  ReaderWriter Lock concept.
(2) lock_guard also aware of how many shared lock in effect before exclude locking so some overhead.
(3) shared_lock can try timed 1 ms to see if writing in progress and give up
(4) both lock_guard and shared_lock construct on the same shared_timed_mutex


std::map<std::string, std::string> _map;
std::shared_timed_mutex m;

std::string find_entry(std::string s)
{
 std::shared_lock<std::shared_timed_mutex> guard(m);
 auto it = _map.find(s);
 if (it == _map.end())
 {
  throw runtime_error("not found");
 }
 return it->second;
}
void add_entry(std::string key,::string s)
{
 std::lock_guard<std::shared_timed_mutex> guard(m);
 _map.insert(make_pair(key,s));
}

void do_work_if_get_lock_in_1sec()
{
 shared_lock<shared_timed_mutex> sl(m, std::chrono::seconds(1));
 if (!sl.owns_lock())
  return;
 //do work after getting lock
}

Saturday, December 3, 2016

JSON Tester


#include "stdafx.h"
#include <iostream>
#include "JSONWrapper.hpp"
#include "render.hpp"

using namespace std;

int main() {

 JSONWrapper jw, jw1, jw2;
 //jw.value = true;
 //jw.value = 123.45;
 //jw.value = std::string{ "test" };
 //jw.value = nullptr;

 
 jw1.value = 678.90;
 jw2.value = true;

 JSONArray a{ jw1,jw2 };
 JSONArray b{ jw1,jw2 };
 //jw.value = a;

 JSONObject obj;
 obj.insert(std::pair<string, JSONArray>("k1", a));
 obj["k2"] = b;
 jw.value = obj;
 
 cout << render_json_value(jw.value) << endl;

 return 0;
}



fold.cpp recursion with compile time constant

(1) boost variant size =20, JSONValue variant=6
(2) v.which() = index
(3) using =typedef and decltype is to get typeinfo
(4) (n,N) recursion, Compile constant N=0, N+1 force n recurs 1 more time to get to n=N  
(5) have not see example Max,Max get called

#pragma once
#include <string>
#include <boost\variant.hpp>
#include "render.hpp"
#include "get2.hpp"

using namespace std;

template<size_t N, size_t Max>
struct apply_at
{
 template<typename R, typename T, typename F, typename...Fs>
 static string apply(T&& t, size_t n, F&& f, Fs&&... fs)
 {
  if (n == N)
  {
    return forward<F>(f)(get2<N>(boost::forward<T>(t)));
  }
  else
  {
   return apply_at<N + 1, Max>::template apply<R, T, Fs...>(
    boost::forward<T>(t),
    n,
    forward<Fs>(fs)...);
  }
 }
};

template<size_t Max>
struct apply_at<Max, Max>
{
 template<typename R, typename T, typename...Fs>
 static string apply(T, size_t, Fs...)
 {
  return R();
 }
};

template<typename T,typename F, typename...Fs>
static string fold_at(T&& t, size_t n, F&& f, Fs&&... fs)
{
  using R = decltype(f(get2<0>(t)));
  return apply_at<0, sizeof...(Fs)+1>::template apply<R,T, F, Fs...>(
   boost::forward<T>(t),
   n,
   forward<F>(f),
   forward<Fs>(fs)...
   );
};

template <typename... Ts, typename... Fs>
string fold(const boost::variant<Ts...>& v, Fs&&... fs)
{
 // size boost::variant=60, JSONValue=6, so assert fail
 //static_assert(sizeof...(Ts) == sizeof...(Fs), "# of fun and variant not matching.");
 return fold_at(
  v, v.which(), forward<Fs>(fs)...
 );
};

6 function of JSON render matching 6 type in JSON variant


#pragma once
#include <string>
#include <sstream>
#include "JSONWrapper.hpp"
#include "join.hpp"
#include "fold.hpp"
#include <iomanip>

using namespace std;

string render_bool(bool b) { return b ? "true" : "false"; }
string render_double(double d) { return to_string(d); }
string render_null(nullptr_t) { return "null"; }
string render_string(const string& s)
{
 stringstream ss;
 ss << std::quoted(s);
 return ss.str();
}

string render_json_value(const JSONValue& jsv);

string render_object(const JSONObject& obj)
{
 return string{ "[" }+
  join(obj.begin(), obj.end(), string{ "." },
   [](const JSONObject::value_type& jsv) {
  return render_string(jsv.first) + ":" + render_json_value(jsv.second);
 }) + "]";
}

string render_array(const JSONArray& a)
{
 return string{ "[" }+
  join(a.begin(), a.end(), string{ "," },
   [](const JSONValue& jsv) {
  return render_json_value(jsv);
 }) + "]";
}

string render_json_value(const JSONValue& jsv)
{
 return fold(jsv,
  render_bool, render_double, render_string,
  render_null, render_array, render_object);
}

join.cpp on iterator though vector and map


#pragma once
#include "JSONWrapper.hpp"
#include <functional>

#include <string>

using namespace std;

string join(JSONObject::const_iterator first, JSONObject::const_iterator last, string delimitor,
 std::function<string(const JSONObject::value_type&)> func)
{
 string ret = "";
 for (;first!= last; first++)
 {
  ret += func(*first) + delimitor;
 }
 return ret;
}

string join(JSONArray::const_iterator first, JSONArray::const_iterator last, string delimitor,
 std::function<string(const JSONValue&)> func)
{
 string ret = "";
 for (;first!= last; first++)
 {
  ret += func(*first) + delimitor;
 }
 return ret;
}


Friday, December 2, 2016

get boost variant value using template specialization on literal value

It seems C++17 will have get<0> and get<N> but boost does not have that yet.
boost only have get<type> and which=0,1,2,3,4,5
The following specialization can hack get<N> for now

#pragma once
#include <boost\variant\get.hpp>
#include "JSONWrapper.hpp"
#include <string>

template<int N>
auto get2(JSONValue jsv);

template<>
auto get2<0>(JSONValue jsv)
{
 return boost::get<bool>(jsv);
}

template<>
auto get2<1>(JSONValue jsv)
{
 return boost::get<double>(jsv);
}

template<>
auto get2<2>(JSONValue jsv)
{
 return boost::get<std::string>(jsv);
}

template<>
auto get2<3>(JSONValue jsv)
{
 return boost::get<nullptr_t>(jsv);
}

template<>
auto get2<4>(JSONValue jsv)
{
 return boost::get<JSONArray>(jsv);
}

template<>
auto get2<5>(JSONValue jsv)
{
 return boost::get<JSONObject>(jsv);
}

boost variant defines JSON Wrapper


Note operator JSONValue&() const meant  jw.operator const JSONValue&() the same as jw as in
cout<<render_json_value(jw)<<endl;

#include <vector>
#include <map>
#include <boost\variant.hpp>

typedef decltype(nullptr) nullptr_t;
struct JSONWrapper;
using JSONArray = std::vector<JSONWrapper>;
typedef std::map<std::string, JSONArray> JSONObject;
using JSONValue = boost::variant<bool, double, std::string, nullptr_t, JSONArray, JSONObject>;

struct JSONWrapper {
 JSONValue value;
 operator JSONValue&() { return value; }
 operator const JSONValue&() const { return value; }
};

Tuesday, November 22, 2016

Validate Two properties

to make sure one property change trigger the other property run validation logic,
must call OnVilidate Code into IDataErrorInfo type of logic in its property Setter

<TextBox Grid.Column="1" Text="{Binding ...,ValidatesOnDataErrors=True,NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TextBoxWithValidationStyle}">


[MustBeGreaterLessThanAllowSuffix("TheOther", false, true, ErrorMessage = "Please specify ..")]

using System;

using System.ComponentModel.DataAnnotations;

using System.Linq;

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]

public class MustBeGreaterLessThanAllowSuffixAttribute : ValidationAttribute

{

public string CompareToPropertyName { get; private set; }

public bool Greater { get; private set; }

public bool IncludeEqual { get; private set; }

public object[] Values { get; private set; }

private static readonly char[] SUFFIXES = new char[4] { 'M', 'm', 'K', 'k' };

public MustBeGreaterLessThanAllowSuffixAttribute(string compareToPropertyName,bool greater,bool includeEqual, params object[] values)

{

CompareToPropertyName = compareToPropertyName;

Greater = greater;

IncludeEqual = includeEqual;

Values = values;

}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)

{

var compToProperty = validationContext.ObjectType.GetProperty(CompareToPropertyName);

var compToValue = compToProperty.GetValue(validationContext.ObjectInstance, null);

return VerifyValidGreaterThanCondition(value, compToValue) ? ValidationResult.Success : new ValidationResult(ErrorMessage);

}

private bool VerifyValidGreaterThanCondition(object value, object compToValue)

{

if (value == null || compToValue == null)

{

return true;

}

string valueNoSuffix = value.ToString().TrimEnd(SUFFIXES);

string compToValueNoSuffix = compToValue.ToString().TrimEnd(SUFFIXES);

double dValue, dCompToValue;

if (!double.TryParse(valueNoSuffix, out dValue) || !double.TryParse(compToValueNoSuffix, out dCompToValue))

{

return true;

}

var dValueMutiplied = dValue * GetMultiplier(value);

var dCompToValueMutiplied = dCompToValue * GetMultiplier(compToValue);

if (Greater)

{

return IncludeEqual ? dValueMutiplied >= dCompToValueMutiplied : dValueMutiplied > dCompToValueMutiplied;

}

return IncludeEqual ? dValueMutiplied <= dCompToValueMutiplied : dValueMutiplied < dCompToValueMutiplied;

}

private double GetMultiplier(object value)

{

if(value==null)

return 1.0;

char suffix = value.ToString().LastOrDefault();

switch (suffix)

{

case 'M':

case 'm':

return 1E6;

case 'K':

case 'k':

return 1E3;

}

return 1.0;

}



[CustomValidation(typeof(VegaTraderSettingValidator), "Check")]

using System.ComponentModel.DataAnnotations;

public class VegaTraderSettingValidator

{

public static ValidationResult Check(string s)

{

return ValidationResult.Success;

}

}



[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]

public class MutualExclusiveDataEntryAttribute : ValidationAttribute

{

public string MutualExclusivePropertyName { get; private set; }

public MutualExclusiveDataEntryAttribute(string mutualExclusivePropertyName)

{

MutualExclusivePropertyName = mutualExclusivePropertyName;

}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)

{

var mutProperty = validationContext.ObjectType.GetProperty(MutualExclusivePropertyName);

if (mutProperty == null)

return ValidationResult.Success;

var mutValue = mutProperty.GetValue(validationContext.ObjectInstance, null);

return VerifyMutualExclsivity(value, mutValue) ? ValidationResult.Success : new ValidationResult(ErrorMessage);

}

private bool VerifyMutualExclsivity(object value, object mutValue)

{

if (value == null || mutValue == null)

return true;

if (!value.IsDefault() && !mutValue.IsDefault())

return false;

return true;

}

}




Saturday, November 19, 2016

Attached Property based TextBox RegEx mask



                {
                    var localTxt = lastValidText;
                    var proposedText = GetProposedText(tbInstance, e1.Text);
                    if (!maskRegEx.IsMatch(proposedText))
                    {
                        e1.Handled = true;
                    }
                };
                
                tbInstance.Loaded += (s, e1) =>
                {
                    if (maskRegEx.IsMatch(tbInstance.Text))
                    {
                        lastValidText = tbInstance.Text;
                        SetHasRegExMisMatch(tbInstance,false);
                    }
                    else
                    {
                        SetHasRegExMisMatch(tbInstance, true);
                    }
                };

                tbInstance.TextChanged += (s, e1) =>
                {
                    if (maskRegEx.IsMatch(tbInstance.Text))
                    {
                        lastValidText = tbInstance.Text;
                        SetHasRegExMisMatch(tbInstance, false);
                    }
                    else
                    {
                        SetHasRegExMisMatch(tbInstance, true);
                    }
                };

                tbInstance.PreviewLostKeyboardFocus += (s, e1) =>
                {
                    var localTxt = lastValidText;
                    if (!maskRegEx.IsMatch(tbInstance.Text))
                    {
                        SetHasRegExMisMatch(tbInstance, true);
                        e1.Handled = true;
                        tbInstance.Text = localTxt;
                        tbInstance.CaretIndex = 99;
                    }
                    else
                    {
                        SetHasRegExMisMatch(tbInstance, false);
                    }
                };            
        }

        private static string GetProposedText(TextBox textBox, string newText)
        {
            var text = textBox.Text;

            if (textBox.SelectionStart != -1)
            {
                text = text.Remove(textBox.SelectionStart, textBox.SelectionLength);
            }

            text = text.Insert(textBox.CaretIndex, newText);

            return text;
        }
    }


C# implicit operator for conversion

implicit operator is conversion operator. 
  //Tuple with Parameter-Less Ctor to enable serialization
    [Serializable]
    public class Tuple2<T1, T2>
    {
        public Tuple2() { }

        public T1 Item1 { get; set; }
        public T2 Item2 { get; set; }

        public static implicit operator Tuple2<T1, T2>(Tuple<T1, T2> t)
        {
            return new Tuple2<T1, T2>()
            {
                Item1 = t.Item1,
                Item2 = t.Item2
            };
        }

        public static implicit operator Tuple<T1, T2>(Tuple2<T1, T2> t)
        {
            return Tuple.Create(t.Item1, t.Item2);
        }
    }

Tuesday, November 15, 2016

Using Pixel shader to highlight data grid row

/// <summary>
    /// Dev Express GridControl does not support multi selection when Master-Detail rows are involved. This behavior highlights multiple rows
    /// and persist onto ViewModel. So it has the effect of multiple selection.
    /// </summary>
    public class MultiRowHighlightBehavior : Behavior<GridControl>
    {

        #region properties

        public int MaxNumberOfRowsHighlighted
        {
            get { return (int)this.GetValue(MaxNumberOfRowsHighlightedProperty); }
            set { this.SetValue(MaxNumberOfRowsHighlightedProperty, value); }
        }
        public static readonly DependencyProperty MaxNumberOfRowsHighlightedProperty = DependencyProperty.Register(
          "MaxNumberOfRowsHighlighted", typeof(int), typeof(MultiRowHighlightBehavior), new PropertyMetadata(int.MaxValue));

        // use IList, INotifyCollectionChanged to avoid generic in DP def e.g. ObservableCollection<T>

        // Pass highlighted Data Rows to VM
        public IList ViewModelHighlightedRows
        {
            get { return (IList)this.GetValue(ViewModelHighlightedRowsProperty); }
            set { this.SetValue(ViewModelHighlightedRowsProperty, value); }
        }
        public static readonly DependencyProperty ViewModelHighlightedRowsProperty = DependencyProperty.Register(
          "ViewModelHighlightedRows", typeof(IList), typeof(MultiRowHighlightBehavior), new PropertyMetadata(null));

        // need to pass in Data Rows for the GridControl, so any removal triggers highlighting updates due to row position changes.
        public INotifyCollectionChanged ViewModelDataRows
        {
            get { return (INotifyCollectionChanged)this.GetValue(ViewModelDataRowsProperty); }
            set { this.SetValue(ViewModelDataRowsProperty, value); }
        }
        public static readonly DependencyProperty ViewModelDataRowsProperty = DependencyProperty.Register(
          "ViewModelDataRows", typeof(INotifyCollectionChanged), typeof(MultiRowHighlightBehavior), new PropertyMetadata(null));


        public string HighLightingColorHex
        {
            get { return (string)this.GetValue(HighLightingColorHexProperty); }
            set { this.SetValue(HighLightingColorHexProperty, value); }
        }
        public static readonly DependencyProperty HighLightingColorHexProperty = DependencyProperty.Register(
          "HighLightingColorHex", typeof(string), typeof(MultiRowHighlightBehavior), new PropertyMetadata(DefaultColorHex));


        public TableViewHitTest HighlightingClickArea
        {
            get { return (TableViewHitTest)this.GetValue(HighlightingClickAreaProperty); }
            set { this.SetValue(HighlightingClickAreaProperty, value); }
        }
        public static readonly DependencyProperty HighlightingClickAreaProperty = DependencyProperty.Register(
          "HighlightingClickArea", typeof(TableViewHitTest), typeof(MultiRowHighlightBehavior), new PropertyMetadata(TableViewHitTest.RowIndicator));


        public bool AllowHighLightingMasterRow
        {
            get { return (bool)this.GetValue(AllowHighLightingMasterRowProperty); }
            set { this.SetValue(AllowHighLightingMasterRowProperty, value); }
        }
        public static readonly DependencyProperty AllowHighLightingMasterRowProperty = DependencyProperty.Register(
          "AllowHighLightingMasterRow", typeof(bool), typeof(MultiRowHighlightBehavior), new PropertyMetadata(false));


        public bool UseShaderEffect
        {
            get { return (bool)this.GetValue(UseShaderEffectProperty); }
            set { this.SetValue(UseShaderEffectProperty, value); }
        }
        public static readonly DependencyProperty UseShaderEffectProperty = DependencyProperty.Register(
          "UseShaderEffect", typeof(bool), typeof(MultiRowHighlightBehavior), new PropertyMetadata(true));

        private const string DefaultColorHex = "#FF3D3D3D";
        private SolidColorBrush _highLightingBrush;


        private enum HighlightingState
        {
            On,
            Off
        }

        #endregion

        #region event

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            AssociatedObject.Loaded += AssociatedObject_Loaded;




            TrySetHighlightingBrush();
        }

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            var sv = VisualTreeHelpers.FindChild<ScrollViewer>(AssociatedObject);
            if (sv != null)
            {
                sv.ScrollChanged += (s, _) => { if (ViewModelHighlightedRows.Count > 0) RedoHilighting(); };
            }
        }

        protected override void OnChanged()
        {
            base.OnChanged();
            if (ViewModelDataRows != null)
            {
                ViewModelDataRows.CollectionChanged += ViewModelDataRows_CollectionChanged;
            }
            if (ViewModelHighlightedRows is INotifyCollectionChanged)  // e.g ObservableCollection<T> is IList and INotifyCollectionChanged
            {
                (ViewModelHighlightedRows as INotifyCollectionChanged).CollectionChanged += ViewModelHighlightedRows_CollectionChanged;
            }
        }

        void ViewModelHighlightedRows_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (ViewModelHighlightedRows.Count == 0) RedoHilighting(); // clear all highlights if collection cleared by outside caller.
        }

        // Rows removed by VM will be removed from highlighted rows if present
        void ViewModelDataRows_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (var i in e.OldItems)
                {
                    if (ViewModelHighlightedRows != null) ViewModelHighlightedRows.Remove(i);
                }
                RedoHilighting();
            }
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                RedoHilighting();
            }
        }

        void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (AssociatedObject.View == null) return;
            var view = AssociatedObject.View as TableView;
            if (view == null) return;

            TableViewHitInfo hitInfo = view.CalcHitInfo(e.OriginalSource as DependencyObject);

            if (hitInfo == null) return;

            // Highlighting happens if user click on Row Header. So highlighting will not interfare with Row/Cell/Expander selection/expanding functionality
            if (hitInfo.HitTest == HighlightingClickArea)
            {
                var row = view.GetRowElementByMouseEventArgs(e) as GridRow;
                if (row == null || row.RowDataContent == null) return;
                var rowData = row.RowDataContent.DataContext as RowData;
                if (rowData == null || ViewModelHighlightedRows == null) return;

                if (!AllowHighLightingMasterRow && IsMasterRow(row) && !HasMarketDepth(rowData.Row)) return;  // use visual tree to check if row =master row, no API found

                if (ViewModelHighlightedRows.Contains(rowData.Row))
                {
                    ToggleHighlighting(row, HighlightingState.Off);
                    ViewModelHighlightedRows.Remove(rowData.Row);
                }
                else
                {
                    if (ViewModelHighlightedRows.Count >= MaxNumberOfRowsHighlighted) return;
                    ToggleHighlighting(row, HighlightingState.On);
                    ViewModelHighlightedRows.Add(rowData.Row);
                }
            }
        }

        private bool HasMarketDepth(object rowDataObject)
        {
            try
            {
                PropertyInfo propInfo = rowDataObject.GetType().GetProperty("HasMarketDepth", BindingFlags.Instance | BindingFlags.Public);

                if (propInfo != null)
                {
                    var val = propInfo.GetValue(rowDataObject, null);
                    return (bool)val;
                }
            }
            catch (Exception)
            {


            }
            return false;
        }

        #endregion

        #region change View and VM, etc.

        // change view only, not ViewModel
        private void ToggleHighlighting(GridRow row, HighlightingState hState)
        {
            try
            {
                var rowIndControl = VisualTreeHelpers.FindChild<RowIndicatorControl>(row);
                var ricBorder = VisualTreeHelpers.FindChild<Border>(rowIndControl);

                SolidColorBrush toggleBrush;
                Effect toggleEff;
                double toggleThickness;
                if (hState == HighlightingState.On)
                {
                    toggleBrush = _highLightingBrush;
                    toggleThickness = 1;
                    toggleEff = new ColorToneEffect() { DarkColor = Colors.Transparent, LightColor = Colors.LightBlue, ToneAmount = 0.1 };
                }
                else
                {
                    toggleBrush = new SolidColorBrush(Colors.Transparent);
                    toggleThickness = 0;
                    toggleEff = null;
                }

                var rowContentBorder = VisualTreeHelpers.FindChild<Border>(row, "RowContentBorder");
                var fixNoneCellstBorder = VisualTreeHelpers.FindChild<Border>(row, "PART_FixedNoneCellsBorder");
                var detailButtonBorder = VisualTreeHelpers.FindChild<Border>(row, "PART_DetailButtonBorder");

                if (UseShaderEffect)  // Shader effect will highlighting on top of all colors across a row
                {
                    ricBorder.Effect = toggleEff;
                    rowContentBorder.Effect = toggleEff;
                    fixNoneCellstBorder.Effect = toggleEff;
                    detailButtonBorder.Effect = toggleEff;
                }
                else
                {
                    ricBorder.Background = toggleBrush;
                    ricBorder.BorderThickness = new Thickness(toggleThickness, toggleThickness, 0, toggleThickness);
                    ricBorder.BorderBrush = toggleBrush;

                    rowContentBorder.BorderBrush = toggleBrush;
                    rowContentBorder.BorderThickness = new Thickness(0, toggleThickness, 0, toggleThickness < 0.5 ? 0.0 : 1.0);

                    fixNoneCellstBorder.BorderBrush = toggleBrush;
                    fixNoneCellstBorder.BorderThickness = new Thickness(0, toggleThickness, 0,
                        toggleThickness < 0.5 ? 0.0 : 1.0);

                    detailButtonBorder.BorderBrush = toggleBrush;
                    detailButtonBorder.BorderThickness = new Thickness(0, toggleThickness, 0, toggleThickness);
                }

            }
            catch (Exception)
            {


            }
        }

        private static bool IsMasterRow(GridRow row)
        {
            try
            {
                var masterRowExpandBorder = VisualTreeHelpers.FindChild<Border>(row, "PART_DetailButtonBorder");
                if (masterRowExpandBorder == null) return false;
                var isMasterRow = VisualTreeHelpers.FindChild<Grid>(masterRowExpandBorder) != null;
                return isMasterRow;
            }
            catch (Exception)
            {
                return false;  // if not sure, let user highlight and un-highlight
            }

        }

        void RedoHilighting()
        {
            if (AssociatedObject == null || AssociatedObject.View == null) return;
            var view = AssociatedObject.View as TableView;
            if (view == null) return;

            var hp = VisualTreeHelpers.FindChild<HierarchyPanel>(view);
            if (hp == null) return;

            AssociatedObject.RefreshData();
            foreach (var c in hp.Children)
            {
                var row = c as GridRow;
                if (row == null || row.RowDataContent == null) continue;
                var rowData = row.RowDataContent.DataContext as RowData;
                if (rowData == null) continue;

                if (ViewModelHighlightedRows.Contains(rowData.Row))
                {
                    ToggleHighlighting(row, HighlightingState.On);
                }
                else
                {
                    ToggleHighlighting(row, HighlightingState.Off);
                }
            }
        }

        private void TrySetHighlightingBrush()
        {
            try
            {
                _highLightingBrush = (new BrushConverter().ConvertFrom(HighLightingColorHex)) as SolidColorBrush;
            }
            catch (Exception)
            {
                _highLightingBrush = (new BrushConverter().ConvertFrom(DefaultColorHex)) as SolidColorBrush;

            }

            if (_highLightingBrush != null) _highLightingBrush.Freeze();
        }

        #endregion

    }

setup Eclipse CDT and optional in c++ 17

(1) create an empty project, cygwin gcc, all the include will be cygwin x86_64, no need to set include path in proj props
(2) set misc flag to have -std=c++17 (lower case)
(3) make sure tool chain editor set CDT internal builder
(4) ignore red squiggles and may rebuild C++ indexes.
(5) how to find C++ header file http://en.cppreference.com/w/cpp/header
(6) sometimes, include file still see "unresolved" error, e.g std::function in . This is caused by preprocessor
    proj->props->C++ general->Preprocessor..etc.->CDT gcc build-in Compiler Settings->uncheck use global, add -std=c++14

 #include <experimental\optional>

using namespace std;
using namespace std::experimental;

optional<pair<string,int>> to_roman(int n)
{
 if(n>10) return {{"X",n-20}};
 if(n>9) return {{"IX",n-9}};
 if(n>5) return {{"V",n-5}};
 if(n>4) return {{"IV",n-4}};
 if(n>1) return {{"I",n-1}};
 return nullopt;  // constexpr inside experimental\optional
}

Saturday, November 12, 2016

MSVC Cuda

(1) cuda is nvidia GPU heterogeneous parallel API integrated in vs 2015
(2) must turn on .net 3.5 window 10 features to compile
(3) search msvc cuda to download nvidia toolkit and vs integration
(4) Control panel, device manager, display adapter shows nvida 5200m for me and cuda capable
(5) must set Cuda/C++ device to Compute_20,sm_20 for NVS 5200M, my labtop cannot do CC=35.
(6) https://en.wikipedia.org/wiki/CUDA#Supported_GPUs list CC=compute capability
(7) can search Cuda.8.0.props file to change CodeGeneration tag to compute=35,sm=35 for all projects.
e.g.C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\BuildCustomizations
(8) <<<blockSz,WarpSz>>> host to device call with blkSz and Hardware thread size.
(9) __global__ kernel function run on device. __ldg __shfl_down needs 35 so my labtop too old
(10) grid + Block +warp, segments GPU hardware thread into 3-dim cubes. 

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>

cudaError_t full_Reduce(int *out, const int *in, size_t n);

__global__ void full_reduce_kernel(int *out, const int *in,size_t n)
{
 int sum = 0; // in hardware,it is a vector<int> width=32,init 0

 // a thread coming choose a block to start, only consider dim-x, y=z=1
 // 4= each thread process 4 elements
 size_t start = (threadIdx.x + blockIdx.x*blockDim.x) * 4; 

 for (size_t i = start; i < start+4 && i < n; i++)
 {
  sum += in[i]; //again i is vector of 32 addresses
  //sum += __ldg(in + i); //_ldg supported in 35, not 20 but NVS 5200M Compute Capability=2.1
 } 
 // shift of SIMD registers, 32 threads move data half by half to front, invalidate back half
 // __shfl_down support in 35, not 20
 /*sum += __shfl_down(sum, 16);
 sum += __shfl_down(sum, 8);
 sum += __shfl_down(sum, 4);
 sum += __shfl_down(sum, 2);
 sum += __shfl_down(sum, 1);*/
 __shared__ int shared_sum; //not vector
 shared_sum = 0;
 __syncthreads(); // only sync warp in a block
 if (threadIdx.x % 32 == 0)
  atomicAdd(&shared_sum, sum);
 __syncthreads();
 if (threadIdx.x == 0) // shfl_down will make only idx=0 valid
  atomicAdd(out, shared_sum);
}

int main()
{
 const int n = 5;
 const int in[n] = { 1,2,3,4,5 };
 int out[n] = { 0 };
 cudaError_t cudaStatus1 = full_Reduce(out, in, n);
 if (cudaStatus1 != cudaSuccess) {
  fprintf(stderr, "full reduce failed!");
  return 1;
 }

 printf("%d %d %d %d %d\n",out[0],out[1],out[2],out[3],out[4]);
 cudaStatus1 = cudaDeviceReset();
 return 0;
}

cudaError_t full_Reduce(int *out, const int *in, size_t n)
{
 int *dev_in = 0;
 int *dev_out = 0;
 int sz = n * sizeof(int);
 cudaError_t cudaStatus;

 cudaStatus = cudaSetDevice(0);

 cudaStatus = cudaMalloc((void**)&dev_out, sz);
 cudaStatus = cudaMalloc((void**)&dev_in, sz);

 cudaStatus = cudaMemcpy(dev_in, in, sz, cudaMemcpyHostToDevice);
 full_reduce_kernel<<<1,n>>>(dev_out, dev_in,n);  // call dev not int
 cudaStatus = cudaGetLastError();
 if (cudaStatus != cudaSuccess) {
  fprintf(stderr, "full redu kernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
  goto FreeDev;
 }

 cudaStatus = cudaDeviceSynchronize();
 cudaStatus = cudaMemcpy(out, dev_out, sz, cudaMemcpyDeviceToHost);

FreeDev:
 cudaFree(dev_out);
 cudaFree(dev_in);

 return cudaStatus;
}

Thursday, November 10, 2016

C++ threading Primitives:mutex, lock_guard, thread, async,future



#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <future>

using namespace std;

inline int f() { return 42; };
mutex m;

void access_shared_res()
{
 cout << " 1 thread in, endl cannot catch up" << endl;

 lock_guard<mutex> g(m);
 cout << " 1 thread passed " <<this_thread::get_id()<< endl;
 this_thread::sleep_for(chrono::seconds(5));
}

int main()
{
 cout << " main thread " << this_thread::get_id() << endl;
 thread  t1(access_shared_res);
 thread  t2(access_shared_res);
 t1.join();
 t2.join();

 std::future<int> f1 = std::async(std::launch::async, []() {return 8; });
 cout << f1.get() << endl;
 std::future<int> promise = std::async(std::launch::async, &f);
 cout << promise.get() << endl;

 std::string s;
 getline(cin, s);
    return 0;
}


Monday, November 7, 2016

Setup Behavior event of its dependency property and connect to the instance not static

Dependency Prop inside a behavior is static. So its event fires into a static event handler.
But the dependencyObject in the param is the hehavior instance and can call instance method.

       public static readonly DependencyProperty TradingLevelProperty = DependencyProperty.Register(
        "TradingLevel", typeof(TradingLevelTypes), typeof(NumericTextBoxCustomParamBehavior), new PropertyMetadata(TradingLevelTypes.Low, TradingLevelrPropertyChanged));

        public TradingLevelTypes TradingLevel
        {
            get { return (TradingLevelTypes)GetValue(TradingLevelProperty); }
            set { SetValue(TradingLevelProperty, value); }
        }



        private static void TradingLevelrPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var behaviorInstance = dependencyObject as NumericTextBoxCustomParamBehavior;
            if (behaviorInstance != null)
            {
                behaviorInstance.EnsureNonNullableDataVisibility();
            }
        }

        void EnsureNonNullableDataVisibility()
        {
            var scrollContentPresenter = AssociatedObject.FindChild("PART_ScrollContentPresenter");
            if (scrollContentPresenter != null)
            {
                scrollContentPresenter.Visibility=TradingLevel== TradingLevelTypes.ServerDefault? Visibility.Hidden: Visibility.Visible;
            }
        }