Explain SpinLock, SpinWait? vs lock sl.enter/exit while(!flag {sw.Spin(100);} Explain how Memory Barrier works? Thread.MemoryBarrier(), Caching Optimization can move instruction around What is Re-entrant? How Semaphore works? SemaphoreSlimw= new (3);_sm.Wait(); block after 3 entrer; sm.Release(); Explain InterLock.Increment/Decrement for 64-bit on 32-bit environment? need two separate instrument InterLock.Increment(ref i); How to use Cancellaton Token in Task? CancelationTokenSource src. src.Token pass in What are SynchronizationContext? Send/Post, Dispatcher, WF/ASPNet How do you use BlockingCollection? How the exception in Thread handled? WPF/WF App.DispatcherUnhandledExpcetion/ThreadExcetion UI Thread AppDomain.Current.UnhandledException General --Process Shutdown, Calling thread will not see it. How to use TaskCompletionSource? StateMachine, Task workflow, tcs.Task ReadOnly, tcs.SetResult/Cancel/Exception How to use Parallel.For ? Parallel.For(1,100,Action<int>) why Binary search is O(logn)? What is Volatile, [Thread Static] and Thread Local ? access by all thread, not optimize, each static field has its own copy, each thread has its own. Is Lazy thread safe ? set by 1st thread, if IsThreadSafe=true; What is Priority Inversion? L hold up H due to resource lock, M comes in unblocked so M>L, make L temporarity High to exec, release H what is Thread Stavation ? L cannot do much since H occupy. Explain how Monitor.Pulse/Wait work? Pulse signal to get on ReadyQueue, Wait to sit on waitQueue. vs. Enter/Exit How to setup BeginInvoke/EndInvoke for Action? Action a; a.BeginInvoke(new AsyncCallback(cb_f,a)); void (cb_f(IAsyncResult ar) { Action a=ar.AsyncState as Action; a.EndInvoke();} Explain Dinning Philosopher Problem? (Minitor, Executor, Manager) What is Mutex? Mutex.TryOpenExisting("Name", out m); m.WaitOne(); m.ReleaseMutex(); What is Multi-cast Delegate? D d1,d2; MuticastDelegate mcd=D.Combine(d1,d2); How much does it cost to set up a thread? 200K CPU cycle, 1M Stack,64 bit 6 Kernal Pages, 2K cycle for Context Switching. Explain GC and WeakReference Reachable -- strong ref, Unreachable/FinalizerQueue =long/short weakref, 2-phase GC. WeakReference wObj= new(TrackResurrection=true); wObj.Target is strongRef but check null needed. What is an example of a Closure? Func f=delegate { int i=5; i=outside var; return 5;} Explain Syntax for Enumerable.Aggragate ((acc,i)=>acc+i) Explain UML notations of Realization/Inheritance/Aggragation/Composition/Association Explain Design Pattern Visitor/Singleton/ What is Rx CombineLastest?
Tuesday, May 5, 2015
INTQ --Threading, C#
Monday, May 4, 2015
INTQ -WPF
What are dependency properties? How to u used it (binding) What are behavior? Various Layout panel (Stack,Grid, Canvas, Dock, Wrap) Attached Property INPC What is ICommand and how to set it up? how do you use DelegateCommand Dynamic vs. static resources How to specify Grid Column Width 26,26*, auto? What is adorner What are routed events ? type Direct, Bubbling, Turnelling What are automationId? How do u bind bool to visibility? what is multibinding How do u used ConverterParameter Explain Unity vs. MEF. What is dependency injection What is the problem of TextBox binding double? (string.EMpty to null ,TargetNullValue={x:Static sys:String.Empty} } ) Explian Visual vs. logical tree Explain FrameworkElement, UIElement, Visual, DependencyObject, DispatcherObject, Explain these triggers ( Property Trigger, Event Trigger, Data Trigger, Muti Trigger) Explain ItemsControl, ContentPresenter,DataTemplate,ContentControl, ItemTemplate, What is TypeConverter ? Explain Template, ContentTemplate, ControlTempalte and DataTemplate? e.g <ItemsControl Template=CT/P ItemTeplate=DT ItemsPanel=ItemPanelTemp/WrapP /> Explain the syntax <ContentControl binding to datasource and use DataTemplate to display <ContentControl Content={Binding Source={StaticRes} ContentTemplate={StaticRes DT1} /> <DataTemplate x:key=DT1> ...</DT> How do you restyle a button by replace its template? <style targetType=Button><setter prop=OvewrrideDefaultDefaultStyle v=true/> <setting Property="Template><setter.value><ControlTemplate>... What is Theme and how do you use it in your UserControl? <App.Res><ResDict source="1.xaml" Explain two way to use EventTrigger? <Button><i:Interaction.Triggers><t:EventTrigger EventNam=><i:InvokeCommandAction> <TextBox><TB.Triggers><EventTrigger><BeginStoryBoard> <Win.Triggers><EventTrigger RoutedEvent=><StoryBoard> Listing places where you can use DataTemplate? <style><style.triggers><datatemplate binding=><setter> <ContentControl ContentTemplate /> How FrameworkElement.CommandBindings work? How to use DataTrigger in Style? <Style.Triggers><DataTrigger Bidng Value><DataTrigger.EnterActions><BeginStoryBoard> What is TemplateBinding ? <ControlTemplate x;Key=CT><StackPanel><Textblock text={TemplateBinding Content}/> <Button Content=123 Template={StaticRes CT}/> How do you use DataTemplate in a ListBox through style and use a datatrigger? Describe MultiBinding vs. Multi trigger syntax? <TB.Text><MB Converter><Binding/><Binding/> <Style.Triggers><MDT><*.Conditions><Cond bind val/><Cond /><Setter ../> Describe the structure usage of HeaderedItemsControl / .Header .Itemtemp .template <ControlTemp><StackPan><ContentPresenter Content={Templatebinding Header} /> <ItemsPresenter/> Describe ItemsControl templating? <ITC><*.Template><ControlTemp><ItemPresenter/> <*.ItemsPanel><O|ItemPanelTemp> <*.ItemTemplate><DataTemp> <*.TemContainerStyle<Style>
Sunday, April 19, 2015
Simpler test of IList.CombineLatest without Group by
var q0 = Observable.Interval(TimeSpan.FromSeconds(1)).Select(s => new MarketData(0,s)); var q1 = Observable.Interval(TimeSpan.FromSeconds(2)).Select(s => new MarketData(1, s)); var q2 = Observable.Interval(TimeSpan.FromSeconds(1)).Select(s => new MarketData(2, s)); var list012 = new List<IObservable>(); list012.AddRange(new[] { q0.Select(t => t.Qty), q1.Select(t => t.Qty), q2.Select(t => t.Qty) }); list012.CombineLatest().Select(t => t.Sum()).Subscribe(d => Console.WriteLine("sum012="+d+" "+DateTime.Now )); var list12 = new List<IObservable >(); list12.AddRange(new[] { q1.Select(t => t.Qty), q2.Select(t => t.Qty) }); list12.CombineLatest().Select(t => t.Sum()).Subscribe(d => Console.WriteLine("sum12=" + d + " " + DateTime.Now)); Console.ReadLine(); public class MarketData { public int? DepthIndex; public decimal? Qty; public MarketData(int? d, decimal? q) { DepthIndex = d; Qty = q; Console.WriteLine("ctor " +d+" "+ q+" "+DateTime.Now ); } } public static IObservable<IList<TSource>> CombineLatest<TSource>(this IObservable<IObservable<TSource>> sources) { return Observable.Create<IList<TSource>>( observer => { var gate = new object(); var latest = new List<TSource>(); var hasValueFlags = new List<bool>(); var sourceCount = 0; var consecutiveActiveSourcesCount = 0; var outerCompleted = false; var outerSubscription = new SingleAssignmentDisposable(); var disposables = new CompositeDisposable(outerSubscription); outerSubscription.Disposable = sources.Subscribe( source => { int index; lock (gate) { sourceCount++; index = latest.Count; latest.Add(default(TSource)); hasValueFlags.Add(false); } var subscription = new SingleAssignmentDisposable(); disposables.Add(subscription); subscription.Disposable = source.Subscribe( value => { lock (gate) { latest[index] = value; if (consecutiveActiveSourcesCount < hasValueFlags.Count) { hasValueFlags[index] = true; while (consecutiveActiveSourcesCount < hasValueFlags.Count && hasValueFlags[consecutiveActiveSourcesCount]) { consecutiveActiveSourcesCount++; } } if (consecutiveActiveSourcesCount >= 2) { observer.OnNext(latest.Take(consecutiveActiveSourcesCount).ToList().AsReadOnly()); } } }, observer.OnError, () => { bool completeNow; lock (gate) { disposables.Remove(subscription); sourceCount--; completeNow = outerCompleted && sourceCount == 0; } if (completeNow) { observer.OnCompleted(); } }); }, observer.OnError, () => { bool completeNow; lock (gate) { outerCompleted = true; completeNow = sourceCount == 0; } if (completeNow) { observer.OnCompleted(); } }); return disposables; }); }
CombineLastest on Several IObservables
// Source code at http://rxx.codeplex.com/ is the critical part of this solution static void Main(string[] args) { DateTime dtStart = DateTime.Now; var mktData = GenerateObservable<MarketData>(1, dt => new MarketData() { DepthIndex=RandomInt(10),Qty=RandomInt(777) }, 1, dt => dt < dtStart.AddSeconds(30)); var grpByDepthMktData= mktData.GroupBy(k => k.DepthIndex).Select(g => new QtyAt(g.Key, g)); grpByDepthMktData.Select(d => d.Qtys.StartWith(0)).CombineLatest().Select(t => t.Sum()).Subscribe(d=>Console.WriteLine("sum all "+d)); var mktData1 = mktData.Where(m => m.DepthIndex >= 1); var grpByDepthMktData1 = mktData1.GroupBy(k => k.DepthIndex).Select(g => new QtyAt(g.Key, g)); grpByDepthMktData1.Select(d => d.Qtys.StartWith(0)).CombineLatest().Select(t => t.Sum()).Subscribe(d => Console.WriteLine(d)); Console.ReadLine(); } static IObservable<T> GenerateObservable<T>(int seconds4Iteration, Func<DateTime, T> newT, int nextInSeconds, Func<DateTime, bool> continuation) { DateTime dtStart = DateTime.Now; return Observable.Generate(dtStart, continuation, dt => dt.AddSeconds(seconds4Iteration), newT, dt => TimeSpan.FromSeconds(nextInSeconds)); } static int? RandomInt(int max) { Random r=new Random(); return r.Next(max); } public class MarketData { public int? DepthIndex; public decimal? Qty; } public class QtyAt { public int? Depth; public IObservable<decimal?> Qtys; public QtyAt(int? depth, IObservable<MarketData> qtys) { Qtys = qtys.Select(m=>m.Qty); } } public static partial class Observable2 { public static IObservable<Tuple<T1, T2>> CombineLatest<T1, T2>(this IObservable<T1> first, IObservable<T2> second) { return first.CombineLatest(second, Tuple.Create); } public static IObservable<IList<TSource>> CombineLatest<TSource>(this IEnumerable<IObservable<TSource>> sources) { return Observable.Defer(() => { var count = 0; var completed = false; return sources.MarkLast() .Select(tuple => { count++; completed = tuple.Item1; return tuple.Item2; }) .ToObservable() .CombineLatest() .SkipWhile(list => !completed || list.Count < count); }); } internal static IEnumerable<Tuple<bool, TSource>> MarkLast<TSource>(this IEnumerable<TSource> source) { using (var enumerator = source.GetEnumerator()) { if (enumerator.MoveNext()) { bool moveNext; do { var value = enumerator.Current; moveNext = enumerator.MoveNext(); yield return Tuple.Create(!moveNext, value); } while (moveNext); } } } public static IObservable<IList<TSource>> CombineLatest<TSource>(this IObservable<IObservable<TSource>> sources) { return Observable.Create<IList<TSource>>( observer => { var gate = new object(); var latest = new List<TSource>(); var hasValueFlags = new List<bool>(); var sourceCount = 0; var consecutiveActiveSourcesCount = 0; var outerCompleted = false; var outerSubscription = new SingleAssignmentDisposable(); var disposables = new CompositeDisposable(outerSubscription); outerSubscription.Disposable = sources.Subscribe( source => { int index; lock (gate) { sourceCount++; index = latest.Count; latest.Add(default(TSource)); hasValueFlags.Add(false); } var subscription = new SingleAssignmentDisposable(); disposables.Add(subscription); subscription.Disposable = source.Subscribe( value => { lock (gate) { latest[index] = value; if (consecutiveActiveSourcesCount < hasValueFlags.Count) { hasValueFlags[index] = true; while (consecutiveActiveSourcesCount < hasValueFlags.Count && hasValueFlags[consecutiveActiveSourcesCount]) { consecutiveActiveSourcesCount++; } } if (consecutiveActiveSourcesCount >= 2) { observer.OnNext(latest.Take(consecutiveActiveSourcesCount).ToList().AsReadOnly()); } } }, observer.OnError, () => { bool completeNow; lock (gate) { disposables.Remove(subscription); sourceCount--; completeNow = outerCompleted && sourceCount == 0; } if (completeNow) { observer.OnCompleted(); } }); }, observer.OnError, () => { bool completeNow; lock (gate) { outerCompleted = true; completeNow = sourceCount == 0; } if (completeNow) { observer.OnCompleted(); } }); return disposables; }); } }
Thursday, March 5, 2015
Break Gradient Color into Pieces
void GetGradiencePieces() { var lgbHigh = new LinearGradientBrush(Colors.Red, Colors.White, 90.0); var lgbLow = new LinearGradientBrush(Colors.Orange, Colors.White, 90.0); Color clr; for (int i = 1; i < 21; i++) { if (i > 10 && i < 30) { float f = (i - 10)/20.0f; clr = GetColorSampleFromLinearGradientBrush(lgbHigh, f); } } } Color GetColorSampleFromLinearGradientBrush(LinearGradientBrush lgb, float y) { double max = lgb.GradientStops.Max(n => n.Offset); double min = lgb.GradientStops.Min(n => n.Offset); //Find gradient stops that surround the input value GradientStop gs0 = lgb.GradientStops.OrderBy(n => n.Offset).Last(); GradientStop gs1 = lgb.GradientStops.OrderBy(n => n.Offset).First(); Color cx = new Color(); if (lgb.ColorInterpolationMode == ColorInterpolationMode.ScRgbLinearInterpolation) { float aVal = (gs1.Color.ScA - gs0.Color.ScA) * y + gs0.Color.ScA; float rVal = (gs1.Color.ScR - gs0.Color.ScR) * y + gs0.Color.ScR; float gVal = (gs1.Color.ScG - gs0.Color.ScG) * y + gs0.Color.ScG; float bVal = (gs1.Color.ScB - gs0.Color.ScB) * y + gs0.Color.ScB; cx = Color.FromScRgb(aVal, rVal, gVal, bVal); } else { byte aVal = (byte)((gs1.Color.A - gs0.Color.A) * y + gs0.Color.A); byte rVal = (byte)((gs1.Color.R - gs0.Color.R) * y + gs0.Color.R); byte gVal = (byte)((gs1.Color.G - gs0.Color.G) * y + gs0.Color.G); byte bVal = (byte)((gs1.Color.B - gs0.Color.B) * y + gs0.Color.B); cx = Color.FromArgb(aVal, rVal, gVal, bVal); } return cx; }
Saturday, February 28, 2015
INPC with Equality check
public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void SetProperty<T>(ref T field, T value, Expression<Func<T>> exp) { if (EqualityComparer<T>.Default.Equals(field, value)) return; field = value; if (PropertyChanged != null) { MemberExpression me = exp.Body as MemberExpression; if (me != null && me.Member != null) PropertyChanged(this, new PropertyChangedEventArgs(me.Member.Name)); } } }
Saturday, February 7, 2015
Code Snippet to walk Visual Tree for Dev Express GridControl Specifics
private void AssociatedObject_LayoutUpdated(object sender, EventArgs e) { var v = AssociatedObject.View; HierarchyPanel hp = VisualTreeHelpers.FindChild(v); GridRow grs = VisualTreeHelpers.FindChild (hp); var ie = v.FindLogicalChildren (); var ie2 = v.FindVisualChildren (); int i1 = ie.Count(); int i2 = ie2.Count(); int i3 = hp.FindVisualChildren ().Count(); } private GridControl dgc; private bool b; private void AssociatedObject_MasterRowExpanded(object sender, RowEventArgs e) { dgc= AssociatedObject.GetDetail(e.RowHandle) as GridControl; dgc.ItemsSourceChanged+=dgc_ItemsSourceChanged; var i = dgc.ItemsSource; var col = dgc.ItemsSource as ObservableCollection ; col.CollectionChanged += col_CollectionChanged; } private void BlankoutColumns(int rowHandle) { var dgc = AssociatedObject.GetVisibleDetail(rowHandle) as GridControl; var dc = dgc.View.DataControl as GridControl; for (int i = 0; i < dc.VisibleRowCount; i++) { int h = dc.GetRowHandleByVisibleIndex(i); foreach (var c in dc.Columns) { if (c.Name == "ChildName") { var v = dc.GetCellValue(h, c); // c.CellTemplate = new DataTemplate(); // take out data template so next update never shown // dc.SetCellValue(h, c, null); // blank out already rendered text } } } } DependencyPropertyDescriptor propertyDescriptor = DependencyPropertyDescriptor.FromProperty(GridViewBase.VisibleColumnsProperty, typeof(GridViewBase)); propertyDescriptor.AddValueChanged(AssociatedObject.View, VisibleColumnsChanged);
Subscribe to:
Posts (Atom)