(1) Build a bio Transistor.
(2) Quantum bit based computer to simulate Bio System evolution and behavior
Monday, May 27, 2013
C# code to stress Memory (Copy from MSDN)
this code is very usefull to bump up resource usage and run your code for exposing bugs class Test { static void Main() { unsafe { byte* buffer = (byte*)Memory.Alloc(256); try { for (int i = 0; i < 256; i++) buffer[i] = (byte)i; byte[] array = new byte[256]; fixed (byte* p = array) Memory.Copy(buffer, p, 256); } finally { Memory.Free(buffer); } for (int i = 0; i < 256; i++) Console.WriteLine(array[i]); } } } using System; using System.Runtime.InteropServices; public unsafe class Memory { // Handle for the process heap. This handle is used in all calls to the // HeapXXX APIs in the methods below. static int ph = GetProcessHeap(); // Private instance constructor to prevent instantiation. private Memory() {} // Allocates a memory block of the given size. The allocated memory is // automatically initialized to zero. public static void* Alloc(int size) { void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if (result == null) throw new OutOfMemoryException(); return result; } // Copies count bytes from src to dst. The source and destination // blocks are permitted to overlap. public static void Copy(void* src, void* dst, int count) { byte* ps = (byte*)src; byte* pd = (byte*)dst; if (ps > pd) { for (; count != 0; count--) *pd++ = *ps++; } else if (ps < pd) { for (ps += count, pd += count; count != 0; count--) *--pd = *--ps; } } // Frees a memory block. public static void Free(void* block) { if (!HeapFree(ph, 0, block)) throw new InvalidOperationException(); } // Re-allocates a memory block. If the reallocation request is for a // larger size, the additional region of memory is automatically // initialized to zero. public static void* ReAlloc(void* block, int size) { void* result = HeapReAlloc(ph, HEAP_ZERO_MEMORY, block, size); if (result == null) throw new OutOfMemoryException(); return result; } // Returns the size of a memory block. public static int SizeOf(void* block) { int result = HeapSize(ph, 0, block); if (result == -1) throw new InvalidOperationException(); return result; } // Heap API flags const int HEAP_ZERO_MEMORY = 0x00000008; // Heap API functions [DllImport("kernel32")] static extern int GetProcessHeap(); [DllImport("kernel32")] static extern void* HeapAlloc(int hHeap, int flags, int size); [DllImport("kernel32")] static extern bool HeapFree(int hHeap, int flags, void* block); [DllImport("kernel32")] static extern void* HeapReAlloc(int hHeap, int flags, void* block, int size); [DllImport("kernel32")] static extern int HeapSize(int hHeap, int flags, void* block); }
Wednesday, April 10, 2013
Detect WPF Window out of bound for multiple monitor
Point p =new Point(left, top); bool outOfBoundHorizontal = p.X < SystemParameters.VirtualScreenLeft || p.X > SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth; bool outOfBoundVertical = p.Y < SystemParameters.VirtualScreenTop || p.Y > SystemParameters.VirtualScreenTop + SystemParameters.VirtualScreenHeight; Note that VirtualScreenHeight/Width considered Multiple Monitor with various Display Positioning, It can start at negative and to position 1/3, use 1/0/3.0*(SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth), not just width. TO reposition find Primary Monitor if (outOfBoundHorizontal || outOfBoundVertical) { var primaryMonitor = Screen.AllScreens.FirstOrDefault(s => s.Primary); if (primaryMonitor == null) { wnd.Left = 0; wnd.Top = 0; } else { // Fit into Primary Monitor if possible. Note Primary Monitor start @ (0,0) wnd.Left = primaryMonitor.Bounds.Left + Math.Max(primaryMonitor.Bounds.Width- wnd.Width, 0); wnd.Top = primaryMonitor.Bounds.Height + Math.Max(primaryMonitor.Bounds.Height - wnd.Height, 0); } } Update--- the above code does not work property due to measurement issues , flip monitor, Landscape/Portrait, L shapes. 1 point = 1/72 inch, 1 px = 1/96 inch. The size could use either px or point per Graphics.PageUnit Rectangle hitTestRec= new System.Drawing.Rectange(left,top, new size(2,2)) var hitTestMonitor= System.Windows.Form.Screen.AllScreens.FirstOrDefault(s => s.Bounds.Contains(hitTestRect)); bool outOfBound = hitTestMonitor ==null;
Sunday, September 9, 2012
Hit Test Toolbar to find button
Toolbar is an ItemsControl and does not have click event handler to indicate which button is clicked. Here Hit Testing is used to figure that out: Note that we need to use Preview to Tunneling Event Handler void tbr_PreviewMouseDown(object sender, MouseButtonEventArgs e) { ToolBar tbr = sender as ToolBar; Point pt=e.GetPosition(tbr); object btnClicked=null; UIElement element = tbr.InputHitTest(pt) as UIElement; while (element != null) { if (element == tbr) return; btnClicked = tbr.ItemContainerGenerator.ItemFromContainer(element); if (!btnClicked.Equals(DependencyProperty.UnsetValue)) break; element = (UIElement)VisualTreeHelper.GetParent(element); } if (btnClicked != null) Console.WriteLine((btnClicked as Button).Content); else Console.WriteLine("no item found"); }
Saturday, August 25, 2012
WCF Duplex Client as Observer
Setup Rx observer over the wire requires WCF Duplex callback: (1) ServiceContract need to define IObserverCallback, instead of subscrbe method lamda. (2) Subscribe and unsubscrib() should be one-way to avoid potential blocking (3) If Session is required then Subscribe/Unsubscrib need to be initiating/terminating (4) Note that IO.Subcribe is non-blocking (v.s. deprecated ForEach) and its only purpose is to set up OnNext on Service side which call Client Side OnNext. (5) Service Instancing Context must be PerSession or Single. PerCall cannot do Unsubscribe since state variable bool stopIO is not maintained. On the other hand, Single => Unsubscribe will stop all Sessions. (6) Threading Issues: WCF service as Single-Thread by default,So reentry will cause deadlock and therefore disallowed ( e.g calling Callback during Service Operation). So mark Service Behavior ConcurrencyMode Reentrant/Mutiple (7) netTcp Binding is Duplex (its name did not say Dual) (8) Update Svc Reference on Client will trigger WCF host for WCF Lib project to run for debugging/testing. (9) Client side Auto Gen Service Reference will force Service Constructor taking in InstanceContext, which in term require Callback contract implemntation. Service Side uses OperationContext.Current.GetCallbackChannel<IObservserCallback>(); (10) Note that Callback contract name on client is IService1Callback <> IObservserCallback service side Callback Contract Name. (11) CPU <10% when run test with 1ms data push, no network travel. (12) To signal Complete on an IO, use TakeWhile and check a non-blocking State Variable like stopIO=true. Contract and Service Definition [ServiceContract(CallbackContract = typeof(IObservserCallback),SessionMode= SessionMode.Required)] public interface IService1 { [OperationContract(IsOneWay=true, IsInitiating=true)] void Subscribe(); [OperationContract(IsOneWay = true,IsTerminating=true)] void Unsubscribe(); } public interface IObservserCallback { [OperationContract] void OnNext(CompositeType data); } [DataContract] public class CompositeType { double _value = 30.45; string _Name = "Name1"; [DataMember] public double Value { get { return _value; } set { _value = value; } } [DataMember] public string Name { get { return _Name; } set { _Name = value; } } } Service // [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession,ConcurrencyMode=ConcurrencyMode.Reentrant)] public class Service1 : IService1 { bool stopIO; //Session State public void Subscribe() { stopIO = false; IObservserCallback client = OperationContext.Current.GetCallbackChannel<IObservserCallback>(); var IO = Observable.Interval(TimeSpan.FromMilliseconds(1)).TakeWhile(x => { return !stopIO; }); IO.Subscribe(x => // This is non-blocking { if(client!=null) client.OnNext(new CompositeType() { Name ="Name"+ x.ToString(), Value=(new Random()).NextDouble()*30 }); }); } public void Unsubscribe() { stopIO = true; } } Client side Subscription and Observer class Program { static void Main(string[] args) { ServiceReference1.Service1Client c = new ServiceReference1.Service1Client(new InstanceContext(new callbackObserver())); c.Subscribe(); Console.WriteLine("Wait for Data. To stop IO, hit return"); Console.ReadLine(); c.Unsubscribe(); Console.ReadLine(); } } class callbackObserver : ConsoleApplication1.ServiceReference1.IService1Callback { public void OnNext(CompositeType data) { Console.WriteLine("Data: " + data.Name +" "+data.Value.ToString()); } }
Friday, August 17, 2012
Drag Canvas around using Rx
WPF UI can be Drag around using mouseMove stream Buffer of two element calculation of Delta: (1) Observe 3 streams: mouseDown, mouseUp, mouseMove. The first two are point event and need duration to join to mouseMove. (2) The duration is skip until mouseDown take until mouseUp (3) Delta is the difference between two mouseMove sampling inside Buffer(2,2). Note that Buffer(count, skip) skip=count is standard, skip>count skip and skip<count is overlapping. Buffer means pile up multiple point into one tallypublic MainWindow() { InitializeComponent(); var mouseDown = from evt in Observable.FromEventPattern<MouseButtonEventHandler, MouseButtonEventArgs>(h => cv.MouseDown += h, h => cv.MouseDown -= h) select evt.EventArgs.GetPosition(this); var mouseUp = from evt in Observable.FromEventPattern<MouseButtonEventHandler, MouseButtonEventArgs>(h => MouseUp += h, h => MouseUp -= h) select evt.EventArgs.GetPosition(this); var mouseMove = from evt in Observable.FromEventPattern<MouseEventHandler, MouseEventArgs>(h => MouseMove += h, h => MouseMove -= h) select evt.EventArgs.GetPosition(this); var q = Observable.Join( mouseDown, mouseMove.Buffer(2, 2), _ => mouseMove.SkipUntil(mouseDown).TakeUntil(mouseUp), _ => Observable.Empty<Unit>(), (d, consecPts) =>new Point(consecPts[1].X - consecPts[0].X, consecPts[1].Y - consecPts[0].Y)); q.Subscribe(delta => { Canvas.SetLeft(cv, Canvas.GetLeft(cv) + delta.X); Canvas.SetTop(cv, Canvas.GetTop(cv) + delta.Y); }); // Side Note: To allow resizing do the following and using Microsoft sample Resizing Adorner: // a = AdornerLayer.GetAdornerLayer(g); //g=Canvas for layout // a.Add(new ResizingAdorner(cv)); // cv= any UIElement inside g } // AdornerLayer adornerLayer; } public class ResizingAdorner : Adorner { Thumb topLeft, topRight, bottomLeft, bottomRight; VisualCollection visualChildren; public ResizingAdorner(UIElement adornedElement) : base(adornedElement) { visualChildren = new VisualCollection(this); BuildAdornerCorner(ref topLeft, Cursors.SizeNWSE); BuildAdornerCorner(ref topRight, Cursors.SizeNESW); BuildAdornerCorner(ref bottomLeft, Cursors.SizeNESW); BuildAdornerCorner(ref bottomRight, Cursors.SizeNWSE); bottomLeft.DragDelta += new DragDeltaEventHandler(HandleBottomLeft); bottomRight.DragDelta += new DragDeltaEventHandler(HandleBottomRight); topLeft.DragDelta += new DragDeltaEventHandler(HandleTopLeft); topRight.DragDelta += new DragDeltaEventHandler(HandleTopRight); } #region Handle Resizing from Thumb void HandleBottomRight(object sender, DragDeltaEventArgs args) { FrameworkElement adornedElement = this.AdornedElement as FrameworkElement; Thumb hitThumb = sender as Thumb; if (adornedElement == null || hitThumb == null) return; FrameworkElement parentElement = adornedElement.Parent as FrameworkElement; EnforceSize(adornedElement); adornedElement.Width = Math.Max(adornedElement.Width + args.HorizontalChange, hitThumb.DesiredSize.Width); adornedElement.Height = Math.Max(args.VerticalChange + adornedElement.Height, hitThumb.DesiredSize.Height); } void HandleBottomLeft(object sender, DragDeltaEventArgs args) { FrameworkElement adornedElement = AdornedElement as FrameworkElement; Thumb hitThumb = sender as Thumb; if (adornedElement == null || hitThumb == null) return; // Ensure that the Width and Height are properly initialized after the resize. EnforceSize(adornedElement); adornedElement.Width = Math.Max(adornedElement.Width - args.HorizontalChange, hitThumb.DesiredSize.Width); adornedElement.Height = Math.Max(args.VerticalChange + adornedElement.Height, hitThumb.DesiredSize.Height); } void HandleTopRight(object sender, DragDeltaEventArgs args) { FrameworkElement adornedElement = this.AdornedElement as FrameworkElement; Thumb hitThumb = sender as Thumb; if (adornedElement == null || hitThumb == null) return; FrameworkElement parentElement = adornedElement.Parent as FrameworkElement; EnforceSize(adornedElement); adornedElement.Width = Math.Max(adornedElement.Width + args.HorizontalChange, hitThumb.DesiredSize.Width); adornedElement.Height = Math.Max(adornedElement.Height - args.VerticalChange, hitThumb.DesiredSize.Height); } void HandleTopLeft(object sender, DragDeltaEventArgs args) { FrameworkElement adornedElement = AdornedElement as FrameworkElement; Thumb hitThumb = sender as Thumb; if (adornedElement == null || hitThumb == null) return; EnforceSize(adornedElement); adornedElement.Width = Math.Max(adornedElement.Width - args.HorizontalChange, hitThumb.DesiredSize.Width); adornedElement.Height = Math.Max(adornedElement.Height - args.VerticalChange, hitThumb.DesiredSize.Height); } #endregion // Arrange thumbs relative to Adorner Center protected override Size ArrangeOverride(Size finalSize) { double desiredWidth = AdornedElement.DesiredSize.Width; double desiredHeight = AdornedElement.DesiredSize.Height; double adornerWidth = this.DesiredSize.Width; double adornerHeight = this.DesiredSize.Height; topLeft.Arrange(new Rect(-adornerWidth / 2, -adornerHeight / 2, adornerWidth, adornerHeight)); topRight.Arrange(new Rect(desiredWidth - adornerWidth / 2, -adornerHeight / 2, adornerWidth, adornerHeight)); bottomLeft.Arrange(new Rect(-adornerWidth / 2, desiredHeight - adornerHeight / 2, adornerWidth, adornerHeight)); bottomRight.Arrange(new Rect(desiredWidth - adornerWidth / 2, desiredHeight - adornerHeight / 2, adornerWidth, adornerHeight)); return finalSize; } void BuildAdornerCorner(ref Thumb cornerThumb, Cursor customizedCursor) { if (cornerThumb != null) return; cornerThumb = new Thumb(); // Set some arbitrary visual characteristics. cornerThumb.Cursor = customizedCursor; cornerThumb.Height = cornerThumb.Width = 10; cornerThumb.Opacity = 0.40; cornerThumb.Background = new SolidColorBrush(Colors.MediumBlue); visualChildren.Add(cornerThumb); // Must add to the tree to arrange } void EnforceSize(FrameworkElement adornedElement) { if (adornedElement.Width.Equals(Double.NaN)) adornedElement.Width = adornedElement.DesiredSize.Width; if (adornedElement.Height.Equals(Double.NaN)) adornedElement.Height = adornedElement.DesiredSize.Height; FrameworkElement parent = adornedElement.Parent as FrameworkElement; if (parent != null) { adornedElement.MaxHeight = parent.ActualHeight; adornedElement.MaxWidth = parent.ActualWidth; } } protected override int VisualChildrenCount { get { return visualChildren.Count; } } protected override Visual GetVisualChild(int index) { return visualChildren[index]; } }
Saturday, August 11, 2012
Dualization
(1) Algebra notation indicates IO is dual of any subject =>func pattern, especially IEnumerable<T> (2) Monad has M, bind, return and in Continuation Monad CM<T> = (T ->() ) -> () return :: T -> CM<T> bind :: CM<T> -> (T -> CM<S>) -> CM<S>Daulality Code interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } interface IEnumerator<out T>: IDisposable { bool MoveNext(); T Current { get; } } interface IObservable<out T> { IDisposable Subscribe(IObserver<T> observer); } interface IObserver<in T> { void OnCompleted(bool done); void OnError(Exception exception); T OnNext { set; } } Covariant vs. Contravariant A <: B A is subtype of B,for TypeContructor C C<A> <: C<B> (Covariant) C<B> <: C<A> (Contravariant) Reading = Covar = <out T> Writing = Contra = <in T> =pass args into array. interface IRequireContravariant<in T> { int Write(T t); } interface IRequireCovariant<out T>{ T Read(int t); } IE vs. IO (1) Concurrency: IE need to remove Concurrency and block MoveNext until Source ready for Next Value; IO need to add Concurrency to not block source push to target (2) Async Computation Model void Fib( int n, ACtion CB, Action Err, Action Cncl) IObserver
Fib(int n); (3) IE can sample source interactively while IO cannot push back high speed source. So IScheduler is define to have time specified: IScheduler { DateTimeOffset Now IDisposable Schedule (state, DateTimeOffset dueTime, Func action) IDisposable Schedule (..TimeSpan dueTime,..); IDisposable Schedule (TState state, Func action) // constant push }
Subscribe to:
Posts (Atom)