Search Results

Search found 10381 results on 416 pages for 'delegate and events'.

Page 85/416 | < Previous Page | 81 82 83 84 85 86 87 88 89 90 91 92  | Next Page >

  • Why isn't my algorithm for find the biggest and smallest inputs working?

    - by Matt Ellen
    I have started a new job, and with it comes a new language: Ironpython. Thankfully a good language :D Before starting I got to grips with Python on the whole, but that was only a week's worth of learning. Now I'm writing actual code. I've been charged with writing an algorithm that finds the best input parameter to collect data with. The basic algorithm is (as I've been instructed): Set the input parameter to a good guess Start collecting data When data is available stop collecting find the highest point If the point before this (i.e. for the previous parameter value) was higher and the point before that was lower then we've found the max otherwise the input parameter is increased by the initial guess. goto 2 If the max is found then the min needs to be found. To do this the algorithm carries on increasing the input, but by 1/10 of the max, until the current point is greater than the previous point and the point before that is also greater. Once the min is found then the algorithm stops. Currently I have a simplified data generator outputting the sin of the input, so that I know that the min value should be PI and the max value should be PI/2 The main Python code looks like this (don't worry, this is just for my edification, I don't write real code like this): import sys sys.path.append(r"F:\Programming Source\C#\PythonHelp\PythonHelp\bin\Debug") import clr clr.AddReferenceToFile("PythonHelpClasses.dll") import PythonHelpClasses from PHCStruct import Helper from System import Math helper = Helper() def run(): b = PythonHelpClasses.Executor() a = PythonHelpClasses.HasAnEvent() b.Input = 0.0 helper.__init__() def AnEventHandler(e): b.Stop() h = helper h.lastLastVal, h.lastVal, h.currentVal = h.lastVal, h.currentVal, e.Number if h.lastLastVal < h.lastVal and h.currentVal < h.lastVal and h.NotPast90: h.NotPast90 = False h.bestInput = h.lastInput inputInc = 0.0 if h.NotPast90: inputInc = Math.PI/10.0 else: inputInc = h.bestInput/10.0 if h.lastLastVal > h.lastVal and h.currentVal > h.lastVal and h.NotPast180: h.NotPast180 = False if h.NotPast180: h.lastInput, b.Input = b.Input, b.Input + inputInc b.Start(a) else: print "Best input:", h.bestInput print "Last input:", h.lastInput b.Stop() a.AnEvent += AnEventHandler b.Start(a) PHCStruct.py: class Helper(): def __init__(self): self.currentVal = 0 self.lastVal = 0 self.lastLastVal = 0 self.NotPast90 = True self.NotPast180 = True self.bestInput = 0 self.lastInput = 0 PythonHelpClasses has two small classes I wrote in C# before I realised how to do it in Ironpython. Executor runs a delegate asynchronously while it's running member is true. The important code: public void Start(HasAnEvent hae) { running = true; RunDelegate r = new RunDelegate(hae.UpdateNumber); AsyncCallback ac = new AsyncCallback(UpdateDone); IAsyncResult ar = r.BeginInvoke(Input, ac, null); } public void Stop() { running = false; } public void UpdateDone(IAsyncResult ar) { RunDelegate r = (RunDelegate)((AsyncResult)ar).AsyncDelegate; r.EndInvoke(ar); if (running) { AsyncCallback ac = new AsyncCallback(UpdateDone); IAsyncResult ar2 = r.BeginInvoke(Input, ac, null); } } HasAnEvent has a function that generates the sin of its input and fires an event with that result as its argument. i.e.: public void UpdateNumber(double val) { AnEventArgs e = new AnEventArgs(Math.Sin(val)); System.Threading.Thread.Sleep(1000); if (null != AnEvent) { AnEvent(e); } } The sleep is in there just to slow things down a bit. The problem I am getting is that the algorithm is not coming up with the best input being PI/2 and the final input being PI, but I can't see why. Also the best and final inputs are different each time I run the programme. Can anyone see why? Also when the algorithm terminates the best and final inputs are printed to the screen multiple times, not just once. Can someone explain why?

    Read the article

  • jquery live problem

    - by Kay
    Hi, I have a website which uses jquery and lots of mouseover/mouseout effect. So far I used the .bind() method of jquery but if you have 1000 event handlers, this is slowing down your browser a lot. So, I want to move to use .live or .delegate. One part of my portal site is a chat area. User can set chat messages which will then be displayed in a simple table. There is a feature that if you move the mouse over a chat message a trash can will appear allowing you to delete the message (if it is by you or you are a moderator). The trash bin is in the same table cell as the chat message. The problem: Using .bind() it worked like a charm. This is the old code: function CreateChatMessageContextMenu(ctrl, messageID, message, sender) { var a = document.createElement("a"); a.href = "javascript:RemoveChatMessage(" + messageID + ");" a.id = 'aDeleteChatMessage' + messageID; a.style.display = 'none'; var img = document.createElement("span"); img.className = "sprite-common messages-image sprite-common-btnDelete"; a.appendChild(img); ctrl.appendChild(a); $(ctrl) .bind('mouseover', function(event) { $('#aDeleteChatMessage' + messageID).show() }) .bind('mouseout', function(event) { $('#aDeleteChatMessage' + messageID).hide() }); return; } 'ctrl' is the reference to a table cell. Now, using .live() the trashbin also appears but it is flickering a lot and when I move the mouse over the trashbin, it is disappearing or inactive. I have the feeling that more events are thrown or something. It seems like the 'mouseout' is thrown when moving over the trashbin, but the thrashbin is inside the tablecell so mouseout should not be triggered. The new code is as follows. $(document).ready { $('.jDeleteableChatMessage').live('mouseover mouseout', function(event) { var linkID = '#aDelete' + event.target.id; if (event.type == 'mouseover') { $(linkID).show(); } else { $(linkID).hide(); } return false; }); } function CreateChatMessageContextMenu(ctrl, messageID, message, sender) { if (!UserIsModerator && (UserLogin != sender)) return; ctrl.id = 'ChatMessage' + messageID; var deleteString = 'Diese Chatnachricht löschen'; if (UserLang == '1') deleteString = 'Delete this chat message'; var a = document.createElement("a"); a.href = "javascript:RemoveChatMessage(" + messageID + ");" a.id = 'aDeleteChatMessage' + messageID; a.style.display = 'none'; var img = document.createElement("span"); img.className = "sprite-common messages-image sprite-common-btnDelete"; img.alt = deleteString; img.title = deleteString; a.appendChild(img); ctrl.appendChild(a); $(ctrl).addClass('jDeleteableChatMessage'); } I add a class to tell jQuery which chat cell have a trash bin and which don't. I also add an ID to the table cell which is later used to determine the associated trash bin. Yes, that's clumsy data passing to an event method. And, naturally, there is the document.ready function which initialises the .live() method. So, where is my mistake?

    Read the article

  • Windows in StreamInsight: Hopping vs. Snapshot

    - by Roman Schindlauer
    Three weeks ago, we explained the basic concept of windows in StreamInsight: defining sets of events that serve as arguments for set-based operations, like aggregations. Today, we want to discuss the so-called Hopping Windows and compare them with Snapshot Windows. We will compare these two, because they can serve similar purposes with different behaviors; we will discuss the remaining window type, Count Windows, another time. Hopping (and its syntactic-sugar-sister Tumbling) windows are probably the most straightforward windowing concept in StreamInsight. A hopping window is defined by its length, and the offset from one window to the next. They are aligned with some absolute point on the timeline (which can also be given as a parameter to the window) and create sets of events. The diagram below shows an example of a hopping window with length of 1h and hop size (the offset) of 15 minutes, hence creating overlapping windows:   Two aspects in this diagram are important: Since this window is overlapping, an event can fall into more than one windows. If an (interval) event spans a window boundary, its lifetime will be clipped to the window, before it is passed to the set-based operation. That’s the default and currently only available window input policy. (This should only concern you if you are using a time-sensitive user-defined aggregate or operator.) The set-based operation will be applied to each of these sets, yielding a result. This result is: A single scalar value in case of built-in or user-defined aggregates. A subset of the input payloads, in case of the TopK operator. Arbitrary events, when using a user-defined operator. The timestamps of the result are almost always the ones of the windows. Only the user-defined  operator can create new events with timestamps. (However, even these event lifetimes are subject to the window’s output policy, which is currently always to clip to the window end.) Let’s assume we were calculating the sum over some payload field: var result = from window in source.HoppingWindow( TimeSpan.FromHours(1), TimeSpan.FromMinutes(15), HoppingWindowOutputPolicy.ClipToWindowEnd) select new { avg = window.Avg(e => e.Value) }; Now each window is reflected by one result event:   As you can see, the window definition defines the output frequency. No matter how many or few events we got from the input, this hopping window will produce one result every 15 minutes – except for those windows that do not contain any events at all, because StreamInsight window operations are empty-preserving (more about that another time). The “forced” output for every window can become a performance issue if you have a real-time query with many events in a wide group & apply – let me explain: imagine you have a lot of events that you group by and then aggregate within each group – classical streaming pattern. The hopping window produces a result in each group at exactly the same point in time for all groups, since the window boundaries are aligned with the timeline, not with the event timestamps. This means that the query output will become very bursty, delivering the results of all the groups at the same point in time. This becomes especially obvious if the events are long-lasting, spanning multiple windows each, so that the produced result events do not change their value very often. In such a case, a snapshot window can remedy. Snapshot windows are more difficult to explain than hopping windows: they represent those periods in time, when no event changes occur. In other words, if you mark all event start and and times on your timeline, then you are looking at all snapshot window boundaries:   If your events are never overlapping, the snapshot window will not make much sense. It is commonly used together with timestamp modification, which make it a very powerful tool. Or as Allan Mitchell expressed in in a recent tweet: “I used to look at SnapshotWindow() with disdain. Now she is my mistress, the one I turn to in times of trouble and need”. Let’s look at a simple example: I want to compute the average of some value in my events over the last minute. I don’t want this output be produced at fixed intervals, but at soon as it changes (that’s the true event-driven spirit!). The snapshot window will include all currently active event at each point in time, hence we need to extend our original events’ lifetimes into the future: Applying the Snapshot window on these events, it will appear to be “looking back into the past”: If you look at the result produced in this diagram, you can easily prove that, at each point in time, the current event value represents the average of all original input event within the last minute. Here is the LINQ representation of that query, applying the lifetime extension before the snapshot window: var result = from window in source .AlterEventDuration(e => TimeSpan.FromMinutes(1)) .SnapshotWindow(SnapshotWindowOutputPolicy.Clip) select new { avg = window.Avg(e => e.Value) }; With more complex modifications of the event lifetimes you can achieve many more query patterns. For instance “running totals” by keeping the event start times, but snapping their end times to some fixed time, like the end of the day. Each snapshot then “sees” all events that have happened in the respective time period so far. Regards, The StreamInsight Team

    Read the article

  • Partial Trust in WPF 4

    - by Hadi Eskandari
    I've started a new project in WPF 4 (.NET 4) and trying to see if I can run it in xbap mode. I need to run the application in Full Trust with the new mode made available in .NET 4 which asks the end user if the full trust application should be run. I've set the "Security" mode to "Full Trust" application, and it builds just fine. When I run it, an exception is thrown and IE error message shows the following error. Any ways around it?? Startup URI: T:\projects\Hightech Sources\PayRoll\PayRoll.Web\publish\PayRoll.Web.xbap Application Identity: file:///T:/projects/Hightech%20Sources/PayRoll/PayRoll.Web/publish/PayRoll.Web.xbap#PayRoll.Web.xbap, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d910f49755d2c97, processorArchitecture=msil/PayRoll.Web.exe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d910f49755d2c97, processorArchitecture=msil, type=win32 System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Demand() at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark) at System.Reflection.Assembly.LoadFrom(String assemblyFile) at PayRoll.Web.App.SelectAssemblies() at Caliburn.PresentationFramework.ApplicationModel.CaliburnApplication..ctor() at PayRoll.Web.App..ctor() at PayRoll.Web.App.Main() at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel) at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData) at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext) at System.Windows.Interop.PresentationApplicationActivator.CreateInstance(ActivationContext actCtx) at System.Activator.CreateInstance(ActivationContext activationContext) at System.AppDomain.Setup(Object arg) at System.AppDomain.nCreateInstance(String friendlyName, AppDomainSetup setup, Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor) at System.Runtime.Hosting.ApplicationActivator.CreateInstanceHelper(AppDomainSetup adSetup) at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData) at System.Windows.Interop.PresentationApplicationActivator.CreateInstance(ActivationContext actCtx) at System.Activator.CreateInstance(ActivationContext activationContext) at System.Deployment.Application.DeploymentManager.ExecuteNewDomain() at System.Deployment.Application.InPlaceHostingManager.Execute() at MS.Internal.AppModel.XappLauncherApp.ExecuteDownloadedApplication() at System.Windows.Interop.DocObjHost.RunApplication(ApplicationRunner runner) at MS.Internal.AppModel.XappLauncherApp.XappLauncherApp_Exit(Object sender, ExitEventArgs e) at System.Windows.Application.OnExit(ExitEventArgs e) at System.Windows.Application.DoShutdown() at System.Windows.Application.ShutdownImpl() at System.Windows.Application.ShutdownCallback(Object arg) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.StartDispatcherInBrowser(Object unused) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.FileIOPermission

    Read the article

  • TypeInitializeException on MVVM pattern

    - by Mohit Deshpande
    System.TypeInitializationException was unhandled Message=The type initializer for 'SmartHomeworkOrganizer.ViewModels.MainViewModel' threw an exception. Source=SmartHomeworkOrganizer TypeName=SmartHomeworkOrganizer.ViewModels.MainViewModel StackTrace: at SmartHomeworkOrganizer.ViewModels.MainViewModel..ctor() at SmartHomeworkOrganizer.App.OnStartup(Object sender, StartupEventArgs e) in C:\Users\Mohit\Documents\Visual Studio 2010\Projects\SmartHomeworkOrganizer\SmartHomeworkOrganizer\App.xaml.cs:line 21 at System.Windows.Application.OnStartup(StartupEventArgs e) at System.Windows.Application.<.ctor>b__0(Object unused) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at SmartHomeworkOrganizer.App.Main() in C:\Users\Mohit\Documents\Visual Studio 2010\Projects\SmartHomeworkOrganizer\SmartHomeworkOrganizer\obj\Debug\App.g.cs:line 0 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.ArgumentException Message=Default value type does not match type of property 'Score'. Source=WindowsBase StackTrace: at System.Windows.DependencyProperty.ValidateDefaultValueCommon(Object defaultValue, Type propertyType, String propertyName, ValidateValueCallback validateValueCallback, Boolean checkThreadAffinity) at System.Windows.DependencyProperty.ValidateMetadataDefaultValue(PropertyMetadata defaultMetadata, Type propertyType, String propertyName, ValidateValueCallback validateValueCallback) at System.Windows.DependencyProperty.RegisterCommon(String name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, ValidateValueCallback validateValueCallback) at System.Windows.DependencyProperty.Register(String name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata, ValidateValueCallback validateValueCallback) at System.Windows.DependencyProperty.Register(String name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata) at SmartHomeworkOrganizer.ViewModels.MainViewModel..cctor() in C:\Users\Mohit\Documents\Visual Studio 2010\Projects\SmartHomeworkOrganizer\SmartHomeworkOrganizer\ViewModels\MainViewModel.cs:line 72 InnerException: This bit of code throws a System.ArgumentException before the TypeInitializeException. It says: "Default value type does not match type of property Score": public static readonly DependencyProperty ScoreProperty = DependencyProperty.Register("Score", typeof(float), typeof(MainViewModel), new UIPropertyMetadata(0.0)); Here is the .NET property: public float Score { get { return (float) GetValue(ScoreProperty); } set { SetValue(ScoreProperty, value); } }

    Read the article

  • Question about Multicast Delegates?

    - by IbrarMumtaz
    I am going through some exam questions for the 70-536 exam and an actual question one developer posted on his blog has popped up in my exam questions. I cannot remember what his answer was .... but below is the question: You need to write a multicast delegate that accepts a DateTime argument and returns a bool value. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) The answer is A. Can someone please explain why? As I already did some research into this question a while ago and so I was sure that it was C, obviously now looking back at the question its clear that I did not read properly. As i was sure I had seen the same one before so I jumped to the most obvious one. A variation on this question: You need to write a multicast delegate that accepts a DateTime argument. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) Now this is another variation on this question, it still has the same bogus sample answers, as they still kind work in throwing the exam taker off. Notice how by simply keeping the sample answers the same and by removing a small portion of the question text, the answer is C and not A. The variation has no official answer as I just conjured it up using the exam question as a baseplate. The answer is definitely C. This time round its easy to see why C is correct but the very first question I have an inkling but as you know an inkling is not good enough in passing exams. Thanks For Reading.

    Read the article

  • Lazy loading the addthis script? (or lazy loading external js content dependent on already fired eve

    - by Keith Bentrup
    I want to have the addthis widget available for my users, but I want to lazy load it so that my page loads as quickly as possible. However, after trying it via a script tag and then via my lazy loading method, it appears to only work via the script tag. In the obfuscated code, I see something that looks like it's dependent on the DOMContentLoaded event (at least for firefox). Since the DOMContentLoaded event has already fired, the widget doesn't render properly. What to do? I could just use a script tag (slower)... or could I fire (in a cross browser way) the DOMContentLoaded (or equivalent) event? I have a feeling this may not be possible b/c I believe that (like jQuery) there are multiple tests of the content ready event, and so multiple simulated events would have to occur. Nonetheless, this is an interesting problem b/c I have seen a couple widgets now assume that you are including their stuff via static script tags. It would be nice if they wrote code that was more useful to developers concerned about speed, but until then, is there a work around?? And/or are any of my assumptions wrong? Edit: Because the 1st answer to the question seemed to miss the point of my problem, I wanted to clarify the situation. This is about a specific problem. I'm not looking for yet another lazy load script or check if some dependencies are loaded script. Specifically this problem deals with external widgets that you do not have control over and may or may not be obfuscated delaying the load of the external widgets until they are needed or at least, til substantially after everything else has been loaded including other deferred elements b/c of the how the widget was written, precludes existing, typical lazy loading paradigms While it's esoteric, I have seen it happen with a couple widgets - where the widget developers assume that you're just willing to throw in another script tag at the bottom of the page. I'm looking to save those 500-1000 ms** though as numerous studies by yahoo, google, and amazon show it to be important to your user's experience. **My testing with hammerhead and personal experience indicates that this will be my savings in this case.

    Read the article

  • Simple form validation. Object-oriented.

    - by kalininew
    Problem statement: It is necessary for me to write a code, whether which before form sending will check all necessary fields are filled. If not all fields are filled, it is necessary to allocate with their red colour and not to send the form. Now the code exists in such kind: function formsubmit(formName, reqFieldArr){ var curForm = new formObj(formName, reqFieldArr); if(curForm.valid) curForm.send(); else curForm.paint(); } function formObj(formName, reqFieldArr){ var filledCount = 0; var fieldArr = new Array(); for(i=reqFieldArr.length-1; i>=0; i--){ fieldArr[i] = new fieldObj(formName, reqFieldArr[i]); if(fieldArr[i].filled == true) filledCount++; } if(filledCount == fieldArr.length) this.valid = true; else this.valid = false; this.paint = function(){ for(i=fieldArr.length-1; i>=0; i--){ if(fieldArr[i].filled == false) fieldArr[i].paintInRed(); else fieldArr[i].unPaintInRed(); } } this.send = function(){ document.forms[formName].submit(); } } function fieldObj(formName, fName){ var curField = document.forms[formName].elements[fName]; if(curField.value != '') this.filled = true; else this.filled = false; this.paintInRed = function(){ curField.addClassName('red'); } this.unPaintInRed = function(){ curField.removeClassName('red'); } } Function is caused in such a way: <input type="button" onClick="formsubmit('orderform', ['name', 'post', 'payer', 'recipient', 'good'])" value="send" /> Now the code works. But I would like to add "dynamism" in it. That it is necessary for me: to keep an initial code essentially, to add listening form fields (only necessary for filling). For example, when the field is allocated by red colour and the user starts it to fill, it should become white. As a matter of fact I need to add listening of events: onChange, blur for the blank fields of the form. As it to make within the limits of an initial code. If all my code - full nonsense, let me know about it. As to me it to change using object-oriented the approach.

    Read the article

  • Beginning with event listeners

    - by terence6
    I have a simple app, showing picture made of tiled images(named u1, u2,...,u16.jpg). Now I'd like to add some Events to it, so that I can show these images only when proper button is clicked. I've tried doing it on my own, but it's not working. Where am I doing something wrong? Original code : import java.awt.GridLayout; import javax.swing.*; import javax.swing.border.BevelBorder; public class Tiles_2 { public static void main(String[] args) { final JFrame f = new JFrame("Usmiech"); JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3)); JLabel l = new JLabel(); for (int i = 1; i < 17; i++) { String path = "u"+ i+".jpg"; l = new JLabel(new ImageIcon(path)); l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); panel.add(l); } f.setContentPane(panel); f.setSize(300, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } New code : import java.awt.GridLayout; import javax.swing.*; import javax.swing.border.BevelBorder; import java.awt.event.*; public class Zad_8_1 implements ActionListener { public void actionPerformed(ActionEvent e) { JButton b = (JButton)(e.getSource()); String i = b.getText(); b = new JButton(new ImageIcon("u"+i+".jpg")); } public static void main(String[] args) { final JFrame f = new JFrame("Smile"); JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3)); JButton l = null; for (int i = 1; i < 17; i++) { String path = "u"+ i+".jpg"; l = new JButton(""+i); l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); l.setSize(53,53); panel.add(l); } f.setContentPane(panel); f.setSize(300, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } This should work like this : http://img535.imageshack.us/img535/3129/lab8a.jpg

    Read the article

  • Delegation, is this just opinionated or is there a common pattern?

    - by user1446714
    If I have a java class containing substantial code and I wish to add extra features, am I right in thinking the delegate class would have the additional features added as methods. Then my original class would create the delegate object and just call the extra functionality via the delegate instance? I am being told by somebody else that my original class should become the delegate and that the class containing the new functionality should contain an instance of the original class, to use as a delegate? This seemed a little backward to me, because there would be far more delegate calls because most of the code is now in the delegate.... I was always under the impression the delegate object would contain the additional new behaviour and an instance of it would be in the original class to inboke the new behaviour from?

    Read the article

  • Question about Multicaste Delegates?

    - by IbrarMumtaz
    I am going through some exam questions for the 70-536 exam and an actual question one developer postedon his blog has popped up in my exam questions. I cannot remember what his answer was .... but below is the question: You need to write a multicast delegate that accepts a DateTime arguement and returns a bool value. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) The answer is A. Can someone please explain why? As I already did some research into this question a while ago and so I was sure that it was C, obviously now looking back at the question its clear that I did not read properly. As i was sure I had seen the same one before so I jumped to the most obvious one. A varitation on this question: You need to write a multicast delegate that accepts a DateTime arguement. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) Now this is another variation on this quesiton, it still has the same bogus sample answers, as they still kind work in throwing the exam taker off. Notice how by simply keeping the sample asnwers the same and by removing a small portion of the question text, the answer is C and not A. The variation has no official answer as I just conjured it up using the exam question as a baseplate. The answer is definately C. This time round its easy to see why C is correctr but the very first question I have an inkiling but as you know an inkling is not good enough in passing exams. Thanks For Reading.

    Read the article

  • Best way to ask confirmation from user before leaving the page

    - by JohnathanKong
    Hey Everyone, I am currently building a registration page where if the user leaves, I want to pop up a CSS box asking him if he is sure or not. I can accomplish this feat using confirm boxes, but the client says that they are too ugly. I've tried using unload and beforeunload, but both cannot stop the page from being redirected. Using those to events, I return false, so maybe there's a way to cancel other than returning false? Another solution that I've had was redirecting them to another page that has my popup, but the problem with that is that if they do want to leave the page, and it wasn't a mistake, they lose the page they were originally trying to go to. If I was a user, that would irritate me. The last solution was real popup window. The only thing I don't like about that is that the main winow will have their destination page while the pop will have my page. In my opinion it looks disjoint. On top of that, I'd be worried about popup blockers. Just to add to everyones comments. I understand that it is irritating to prevent users from exiting the page, and in my opinion it should not be done. Right now I am using a confirm box at this point. What happens is that it's not actually "preventing" the user from leaving, what the client actually wants to do is make a suggestion if the user is having doubts about registering. If the user is halfway through the registraiton process and leaves for some reason, the client wants to offer the user a free coupon to a seminar (this client is selling seminars) to hopefully persuade the user to register. The client is under the impression that since the user is already on the form, he is thinking of registering, and therefore maybe a seminar of what he is registering for would be the final push to get the user to register. Ideally I don't have to prevent the user from leaving, what would be just as good, and in my opinion better is if I can pause the unload process. Maybe a sleep command? I don't really have to keep the user on the page because either way they will be leaving to go to a different page. Also, as people have stated, this is a terriable title, so if someone knows a better one, I'd really appreciate it if they could change the title to something no so spammer inviting.

    Read the article

  • touchend event doesn't work on Android

    - by Protos
    Hi, I've just started looking at doing some basic mobile web development on the android and an writing a test script to investigate the touch events. I've run the following code in the android emulator, and the touchend event never gets fired. Can anyone tell me why ? I've tried in three versions of the emulator (1.6, 2.1 and 2.2) and all three behave in the same way. Thanks in advance for any help you can give me. Cheers, Colm EDIT - I've also tried this using the XUI framework and have the same problem so I'm guessing I have a fundamental misunderstanding of how this stuff works ...... Map Test <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="language" content="english" /> <meta name="viewport" content="minimum-scale=1.0, width=device-width, height=device-height, user-scalable=no"> <script type="text/javascript"> window.onload = function(){ document.body.appendChild( document.createTextNode("w: " + screen.width + " x " + "h : " +screen.height) ); attachTouchEvents(); } function attachTouchEvents() { console = document.getElementById("console"); var map = document.getElementById("map"); map.addEventListener ('touchstart', function (event) { event.preventDefault(); var touch = event.touches[0]; document.getElementById("touchCoord").innerHTML = "S : " + touch.pageX + " " + touch.pageY; document.getElementById("touchEvent").innerHTML = "Touch Start"; }, false); map.addEventListener ('touchmove', function (event) { event.preventDefault(); var touch = event.touches[0]; document.getElementById("touchCoord").innerHTML = "M : " + touch.pageX + " " + touch.pageY; document.getElementById("touchEvent").innerHTML = "Touch Move"; }, false); map.addEventListener ('touchend', function (event) { var touch = event.touches[0]; document.getElementById("touchCoord").innerHTML = "E : " + touch.pageX + " " + touch.pageY; document.getElementById("touchEvent").innerHTML = "Touch End"; event.preventDefault(); }, false); console.innerHTML = "event attached"; } </script> <style type="text/css"> html, body { height:100%; width:100%; margin: 0; background-color:red; } #map { height: 300px; width: 300px; background-color:yellow; } </style> </head> <body> <div id="map"></div> <div id="touchCoord">Touch Coords</div> <div id="touchEvent">Touch Evnt</div> <div id="console">Console</div> </body>

    Read the article

  • Outlook Addin: DispEventAdvise exception.

    - by framara
    I want to creating an addin that captures when a {contact, calendar, task, note} is {created, edited, removed}. I have the following code, to make it shorter I removed all the code but the related to contact, since all types will be the same I guess. AutoSync.h class ATL_NO_VTABLE AutoSync : public wxPanel, public IDispEventSimpleImpl<1, AutoSync, &__uuidof(Outlook::ItemsEvents)>, public IDispEventSimpleImpl<2, AutoSync, &__uuidof(Outlook::ItemsEvents)>, public IDispEventSimpleImpl<3, AutoSync, &__uuidof(Outlook::ItemsEvents)> { public: AutoSync(); ~AutoSync(); void __stdcall OnItemAdd(IDispatch* Item); /* 0xf001 */ void __stdcall OnItemChange(IDispatch* Item); /* 0xf002 */ void __stdcall OnItemRemove(); /* 0xf003 */ BEGIN_SINK_MAP(AutoSync) SINK_ENTRY_INFO(1, __uuidof(Outlook::ItemsEvents), 0xf001, OnItemAdd, &OnItemsAddInfo) SINK_ENTRY_INFO(2, __uuidof(Outlook::ItemsEvents), 0xf002, OnItemChange, &OnItemsChangeInfo) SINK_ENTRY_INFO(3, __uuidof(Outlook::ItemsEvents), 0xf003, OnItemRemove, &OnItemsRemoveInfo) END_SINK_MAP() typedef IDispEventSimpleImpl<1, AutoSync, &__uuidof(Outlook::ItemsEvents)> ItemAddEvents; typedef IDispEventSimpleImpl<2, AutoSync, &__uuidof(Outlook::ItemsEvents)> ItemChangeEvents; typedef IDispEventSimpleImpl<3, AutoSync, &__uuidof(Outlook::ItemsEvents)> ItemRemoveEvents; private: CComPtr<Outlook::_Items> m_contacts; }; AutoSync.cpp _NameSpacePtr pMAPI = OutlookWorker::GetInstance()->GetNameSpacePtr(); MAPIFolderPtr pContactsFolder = NULL; HRESULT hr = NULL; //get folders if(pMAPI != NULL) { pMAPI-GetDefaultFolder(olFolderContacts, &pContactsFolder); } //get items if(pContactsFolder != NULL) pContactsFolder-get_Items(&m_contacts); //dispatch events if(m_contacts != NULL) { //HERE COMES THE EXCEPTION hr = ItemAddEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemChangeEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemRemoveEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); } somewhere else defined: extern _ATL_FUNC_INFO OnItemsAddInfo; extern _ATL_FUNC_INFO OnItemsChangeInfo; extern _ATL_FUNC_INFO OnItemsRemoveInfo; _ATL_FUNC_INFO OnItemsAddInfo = {CC_STDCALL,VT_EMPTY,1,{VT_DISPATCH}}; _ATL_FUNC_INFO OnItemsChangeInfo = {CC_STDCALL,VT_EMPTY,1,{VT_DISPATCH}}; _ATL_FUNC_INFO OnItemsRemoveInfo = {CC_STDCALL,VT_EMPTY,0}; The problems comes in the hr = ItemAddEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemChangeEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemRemoveEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); It gives exception in 'atlbase.inl' when executes method 'Advise': ATLINLINE ATLAPI AtlAdvise(IUnknown* pUnkCP, IUnknown* pUnk, const IID& iid, LPDWORD pdw) { if(pUnkCP == NULL) return E_INVALIDARG; CComPtr<IConnectionPointContainer> pCPC; CComPtr<IConnectionPoint> pCP; HRESULT hRes = pUnkCP->QueryInterface(__uuidof(IConnectionPointContainer), (void**)&pCPC); if (SUCCEEDED(hRes)) hRes = pCPC->FindConnectionPoint(iid, &pCP); if (SUCCEEDED(hRes)) //HERE GIVES EXCEPTION //Unhandled exception at 0x2fe913e3 in OUTLOOK.EXE: 0xC0000005: //Access violation reading location 0xcdcdcdcd. hRes = pCP->Advise(pUnk, pdw); return hRes; } I can't manage to understand why. Any sugestion here? Everything seems to be fine, but obviously is not. I've been stucked here for quite a long time. Need your help, thanks.

    Read the article

  • Event handle in drop-down menu.

    - by QLiu
    Hello fellows, I am trying to develop a dynamic drop down menu by a customized widget style The custom widget has two main features: Read user's location cookies variable to set the proper contact phone number in the CP pages When users select on the drop down menu, it triggers onChange event, it re-select the contact phone number based on users' selections, but it won't reset the location cookies. My widgets conatins two files: Controller.php: Simply one, it uses to handle get cookies variables class serial extends Widget { function __construct() { parent::__construct(); } function generateWidgetInformation() { $this->info['notes'] = "Serial Number search Box"; } function getData() { //Get cookies code will go here, and pass to view.php $this->data['locale'] = 'gb';// for test purpose now } } view.php is about Presentation layer contains HTML, which get the data from my controller <div style="border: 1px solid black; display: block;" id="<?=$this->instanceID;?>"></div> <script>locale2contact('<?=$this->data['locale']?>', '<?=$this->instanceID;?>');</script> And then the Javascript function, call locale2contact var element_id =''; //Define Global Variables, //Receive the cookies locale, and instance id from view.php function locale2contact(locale, instance_id) { var details = ''; this.element_id=instance_id; //assing the instance id into global variable // alert(instance_id); //Check whether we got the instance id from view files if (locale == 'gb') details = 'UK Contact Details<br>' + build_dropdown(locale); else if (locale == 'fr') details = 'French Contact Details<br>'+build_dropdown(locale); else if (locale == 'be') details = 'Belgian Contact Details<br>'+ build_dropdown(locale); else details = 'Unknown Contact Detail'; writeContactInfo(details); } //Build the drop down menu with pre-selected option by using cookies. function build_dropdown(locale) { var dropdown = '<select onChange=changeContactInfo(this.options[selectedIndex].text)>'; dropdown += '<option' + (locale == 'gb' ? ' selected' : '') + '>UK</option>'; dropdown += '<option' + (locale == 'be' ? ' selected' : '') + '>Belgium</option>'; dropdown += '</select>'; return dropdown; } // Not smart way in here, once the people select the drop down box, it reselect the drop down menu and reset the contact info function changeContactInfo(selected) { var details =''; //alert(this.element_id); //alert(locale); if (selected == 'UK') details = 'UK Contact Details<br>' + build_dropdown2(selected); else if (selected == 'fr') details = 'French Contact Details<br>'+ build_dropdown2(selected); else if (selected == 'Belgium') details = 'Belgian Contact Details<br>'+ build_dropdown2(selected); else details = 'Unknown Contact Detail'; writeContactInfo(details); } //Build the drop down menu function build_dropdown2(selected) { var dropdown = '<select onChange=changeContactInfo(this.options[selectedIndex].text)>'; dropdown += '<option' + (selected == 'UK' ? ' selected' : '') + '>UK</option>'; dropdown += '<option' + (selected == 'Belgium' ? ' selected' : '') + '>Belgium</option>'; dropdown += '</select>'; return dropdown; } //Back to view function writeContactInfo(details) { document.getElementById(this.element_id).innerHTML = details; //update the instance field in view } Javascript function is not efficient. As you see, I got two similar duplicate functions to handle events. Users go to the page, the widget read the cookies variable to display contact info (locale2contact)and preselect the drop-down menu (function build_dropdown) If users select the drop down menu, the displya contact info change (function changeContactInfo), and then I need to rebuild the drop down menu with user previously selection (function build_dropdown2). I am looking for best practices for adding this functionality to RightNow widget. Thank you. I really do not like the way i am doing now. It works; but the code looks bad.

    Read the article

  • When is Facebook Connect supposed to call its delegate methods?

    - by RickiG
    Hi The Facebook connect code is eluding me a bit. I have no problem doing a login, and a wall post, however, I simply can not figure out how the delegate methods for the FBDialog andFBStreamDialog is supposed to work. - (void)postToWall { FBStreamDialog *dialog = [[[FBStreamDialog alloc] init] autorelease]; dialog.delegate = self; dialog.userMessagePrompt = @"Enter your message:"; dialog.attachment = [NSString stringWithFormat:@"JSONpost code"]; [dialog show]; } I adhere to these protocols in my controller: <FBDialogDelegate, FBSessionDelegate, FBRequestDelegate> I then implement the two methods: - (void) dialogDidCancel:(FBDialog *)dialog { NSLog(@"Failed"); } - (void) dialogDidSucceed:(FBDialog *)dialog { NSLog(@"Success"); } After I tap "publish" and the postToWall methods is done executing the Facebook "pop up" in the UI is empty, except a small "X" in the top right corner and a "F" (facebook logo) in the top left corner. The UI will stay there until I tap the "X", this results in the dialogDidCancel delegate method being called. The post data is showing up on the Facebook page, everything seems to work. Why is thedialogDidSucceedmethod never called? I need this to release my facebook controller and restore the UI back to where the user was before "starting" FB Connect. Thank You:)

    Read the article

  • NSNotification vs. Delegate Protocols?

    - by jr
    I have an iPhone application which basically is getting information from an API (in XML, but maybe JSON eventually). The result objects are typically displayed in view controllers (tables mainly). Here is the architecture right now. I have NSOperation classes which fetch the different objects from the remote server. Each of these NSOperation classes, will take a custom delegate method which will fire back the resulting objects as they are parsed, and then finally a method when no more results are available. So, the protocol for the delegates will be something like: (void) ObjectTypeResult:(ObjectType *)result; (void) ObjectTypeNoMoreResults; I think the solution works well, but I do end up with a bunch of delegate protocols around and then my view controllers have to implement all these delegate methods. I don't think its that bad, but I'm always on the lookout for a better design. So, I'm thinking about using NSNotifications to remove the use of the delegates. I could include the object in the userInfo part of the notification and just post objects as received, and then a final event when no more are available. Then I could just have one method in each view controller to receive all the data, even when using multiple objects in one controller.† So, can someone share with me some pros/cons of each approach. Should I consider refactoring my code to use Events rather then the delegates? Is one better then the other in certain situations? In my scenario I'm really not looking to receive notifications in multiple places, so maybe the protocol based delegates are the way to go. Thanks!

    Read the article

  • How can I respond to mouse events in AS3?

    - by Gabriel Meono
    Background: Trying to make a simple "drop the ball" game. The code is located inside the first frame of the timeline. Nothing more is on the stage. Issue: Using QuickBox2D I made a simple If statement that drops and object acording the Mouse-x position: if (MouseEvent.CLICK) { sim.addCircle({x:mouseX, y:1, radius:0.25, density:5}); I imported the MouseEvent library: import flash.events.MouseEvent; Nothing happens if I click, no output errors either. See it in action: http://gabrielmeono.com/download/Lucky_Hit_Alpha.swf http://gabrielmeono.com/download/Lucky_Hit_Alpha.fla Full Code: [SWF(width = 350, height = 600, frameRate = 60)] import com.actionsnippet.qbox.*; import flash.events.MouseEvent; var sim:QuickBox2D = new QuickBox2D(this); sim.createStageWalls(); //var ball:sim.addCircle({x:mouseX, y:1, radius:0.25, density:5}); // // make a heavy circle sim.addCircle({x:3, y:1, radius:0.25, density:5}); sim.addCircle({x:2, y:1, radius:0.25, density:5}); sim.addCircle({x:4, y:1, radius:0.25, density:5}); sim.addCircle({x:5, y:1, radius:0.25, density:5}); sim.addCircle({x:6, y:1, radius:0.25, density:5}); // create a few platforms sim.addBox({x:3, y:2, width:4, height:0.2, density:0, angle:0.1}); // make 26 dominoes for (var i:int = 0; i<7; i++){ //End sim.addCircle({x:1 + i * 1.5, y:16, radius:0.1, density:0}); sim.addCircle({x:2 + i * 1.5, y:15, radius:0.1, density:0}); //Mid end sim.addCircle({x:0 + i * 2, y:14, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:13, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:12, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:11, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:10, radius:0.1, density:0}); //Middle Start sim.addCircle({x:0 + i * 1.5, y:09, radius:0.1, density:0}); sim.addCircle({x:1 + i * 1.5, y:08, radius:0.1, density:0}); sim.addCircle({x:0 + i * 1.5, y:07, radius:0.1, density:0}); sim.addCircle({x:1 + i * 1.5, y:06, radius:0.1, density:0}); } if (MouseEvent.CLICK) { sim.addCircle({x:mouseX, y:1, radius:0.25, density:5}); sim.start(); /*sim.mouseDrag();*/ }

    Read the article

  • How can I show Thunderbird Lightning tasks and events in the Gnome Clock applet?

    - by Niriel
    We used to have this functionality with Evolution: clicking on the date-time in the gnome panel would show a list of events/tasks/appointments from the Evolution Calendar. As an interesting side effect, one would receive alarm notifications even when Evolution wasn't running. Now that Thunderbird is the default email client, I'd imagine that there is a similar functionality for Lightning (Thunberbird's calendar). I just can't find it. Maybe it's not ready ?

    Read the article

  • How to deal with fellow programmer who likes to delegate task with lack any support from boss [closed]

    - by Rudy
    I have a problem with my fellow programmer. We are currently working together in a small project that need to be shipped every 2 weeks. She has a tendency to ask for help for every issues that she is facing. Whether it's a compile error, algorithm problem or even sync/merge issue that caused by herself. She does not even bother to check Google or try to find out by herself. I can be asked to help her for 5-10 times a day. Everyday her husband keeps calling (4-6 times a day), and most of the code that has been delivered by her are actually incorrect. Today she framed me for sending the wrong delivery product. She went home after lunch on the delivery day without telling PM and other team member on that day and her code she commited does not work at all. It's not even tested. I have no choice to roll back her code and cleaning her code just for sake to able to run the product. I have warned her about her defective codes for almost 3 iterations. She said when she was not around I should be able to test her module for her. I snapped and yelled that I am not her slave and directly reported to my boss. However, my boss is not a person that can manage and care about software quality. What is the most important thing to my boss is delivery of product, whether it tested or not. He can even asked us to deliver something that not even tested by QA to the client, on the next day. Most of our suggestion is not followed by him. He even asked me to apologize to her because I snapped. I am tired of the whole situation. This kind of thing keeps repeated. I do have saving to be able to survive for 6 months and the idea of resigning is keep haunting. There is nothing else that can be learned in my current job and I had been in a better environment than this. What should I do with the situation?

    Read the article

  • What could cause a flurry of Microsoft-Windows-Servicing events?

    - by MattUebel
    I have a windows 2k8 machine that generated almost 40,000 WinEventLog:System events in the period of about 20 minutes. The breakdown of these events by eventcode was approximately: 4373 46% 4371 46% 4383 7% 4372 1% Microsoft-Windows-Servicing seemed to go crazy for a short time.... looking at updates, changing the state of updates etc. What could have caused this? UPDATE: Many of the events seem to come in pairs of: Windows Servicing started a process of changing package KBfoobar state from Installed(Installed) to Installed(Installed) and Windows Servicing successfully set package KBfoobar state to Installed(Intstalled)

    Read the article

  • Oracle Solaris Cluster 4.2 Event and its SNMP Interface

    - by user12609115
    Background The cluster event SNMP interface was first introduced in Oracle Solaris Cluster 3.2 release. The details of the SNMP interface are described in the Oracle Solaris Cluster System Administration Guide and the Cluster 3.2 SNMP blog. Prior to the Oracle Solaris Cluster 4.2 release, when the event SNMP interface was enabled, it would take effect on WARNING or higher severity events. The events with WARNING or higher severity are usually for the status change of a cluster component from ONLINE to OFFLINE. The interface worked like an alert/alarm interface when some components in the cluster were out of service (changed to OFFLINE). The consumers of this interface could not get notification for all status changes and configuration changes in the cluster. Cluster Event and its SNMP Interface in Oracle Solaris Cluster 4.2 The user model of the cluster event SNMP interface is the same as what was provided in the previous releases. The cluster event SNMP interface is not enabled by default on a freshly installed cluster; you can enable it by using the cluster event SNMP administration commands on any cluster nodes. Usually, you only need to enable it on one of the cluster nodes or a subset of the cluster nodes because all cluster nodes get the same cluster events. When it is enabled, it is responsible for two basic tasks. • Logs up to 100 most recent NOTICE or higher severity events to the MIB. • Sends SNMP traps to the hosts that are configured to receive the above events. The changes in the Oracle Solaris Cluster 4.2 release are1) Introduction of the NOTICE severity for the cluster configuration and status change events.The NOTICE severity is introduced for the cluster event in the 4.2 release. It is the severity between the INFO and WARNING severity. Now all severities for the cluster events are (from low to high) • INFO (not exposed to the SNMP interface) • NOTICE (newly introduced in the 4.2 release) • WARNING • ERROR • CRITICAL • FATAL In the 4.2 release, the cluster event system is enhanced to make sure at least one event with the NOTICE or a higher severity will be generated when there is a configuration or status change from a cluster component instance. In other words, the cluster events from a cluster with the NOTICE or higher severities will cover all status and configuration changes in the cluster (include all component instances). The cluster component instance here refers to an instance of the following cluster componentsnode, quorum, resource group, resource, network interface, device group, disk, zone cluster and geo cluster heartbeat. For example, pnode1 is an instance of the cluster node component, and oracleRG is an instance of the cluster resource group. With the introduction of the NOTICE severity event, when the cluster event SNMP interface is enabled, the consumers of the SNMP interface will get notification for all status and configuration changes in the cluster. A thrid-party system management platform with the cluster SNMP interface integration can generate alarms and clear alarms programmatically, because it can get notifications for the status change from ONLINE to OFFLINE and also from OFFLINE to ONLINE. 2) Customization for the cluster event SNMP interface • The number of events logged to the MIB is 100. When the number of events stored in the MIB reaches 100 and a new qualified event arrives, the oldest event will be removed before storing the new event to the MIB (FIFO, first in, first out). The 100 is the default and minimum value for the number of events stored in the MIB. It can be changed by setting the log_number property value using the clsnmpmib command. The maximum number that can be set for the property is 500. • The cluster event SNMP interface takes effect on the NOTICE or high severity events. The NOTICE severity is also the default and lowest event severity for the SNMP interface. The SNMP interface can be configured to take effect on other higher severity events, such as WARNING or higher severity events by setting the min_severity property to the WARNING. When the min_severity property is set to the WARNING, the cluster event SNMP interface would behave the same as the previous releases (prior to the 4.2 release). Examples, • Set the number of events stored in the MIB to 200 # clsnmpmib set -p log_number=200 event • Set the interface to take effect on WARNING or higher severity events. # clsnmpmib set -p min_severity=WARNING event Administering the Cluster Event SNMP Interface Oracle Solaris Cluster provides the following three commands to administer the SNMP interface. • clsnmpmib: administer the SNMP interface, and the MIB configuration. • clsnmphost: administer hosts for the SNMP traps • clsnmpuser: administer SNMP users (specific for SNMP v3 protocol) Only clsnmpmib is changed in the 4.2 release to support the aforementioned customization of the SNMP interface. Here are some simple examples using the commands. Examples: 1. Enable the cluster event SNMP interface on the local node # clsnmpmib enable event 2. Display the status of the cluster event SNMP interface on the local node # clsnmpmib show -v 3. Configure my_host to receive the cluster event SNMP traps. # clsnmphost add my_host Cluster Event SNMP Interface uses the common agent container SNMP adaptor, which is based on the JDMK SNMP implementation as its SNMP agent infrastructure. By default, the port number for the SNMP MIB is 11161, and the port number for the SNMP traps is 11162. The port numbers can be changed by using the cacaoadm. For example, # cacaoadm list-params Print all changeable parameters. The output includes the snmp-adaptor-port and snmp-adaptor-trap-port properties. # cacaoadm set-param snmp-adaptor-port=1161 Set the SNMP MIB port number to 1161. # cacaoadm set-param snmp-adaptor-trap-port=1162 Set the SNMP trap port number to 1162. The cluster event SNMP MIB is defined in sun-cluster-event-mib.mib, which is located in the /usr/cluster/lib/mibdirectory. Its OID is 1.3.6.1.4.1.42.2.80, that can be used to walk through the MIB data. Again, for more detail information about the cluster event SNMP interface, please see the Oracle Solaris Cluster 4.2 System Administration Guide. - Leland Chen 

    Read the article

  • Delegates in c#

    - by Jalpesh P. Vadgama
    I have used delegates in my programming since C# 2.0. But I have seen there are lots of confusion going on with delegates so I have decided to blog about it. In this blog I will explain about delegate basics and use of delegates in C#. What is delegate? We can say a delegate is a type safe function pointer which holds methods reference in object. As per MSDN it's a type that references to a method. So you can assign more than one methods to delegates with same parameter and same return type. Following is syntax for the delegate public delegate int Calculate(int a, int b); Here you can see the we have defined the delegate with two int parameter and integer parameter as return parameter. Now any method that matches this parameter can be assigned to above delegates. To understand the functionality of delegates let’s take a following simple example. using System; namespace Delegates { class Program { public delegate int CalculateNumber(int a, int b); static void Main(string[] args) { int a = 5; int b = 5; CalculateNumber addNumber = new CalculateNumber(AddNumber); Console.WriteLine(addNumber(5, 6)); Console.ReadLine(); } public static int AddNumber(int a, int b) { return a + b; } } } Here in the above code you can see that I have created a object of CalculateNumber delegate and I have assigned the AddNumber static method to it. Where you can see in ‘AddNumber’ static method will just return a sum of two numbers. After that I am calling method with the help of the delegates and printing out put to the console application. Now let’s run the application and following is the output as expected. That’s it. You can see the out put of delegates after adding a number. This delegates can be used in variety of scenarios. Like in web application we can use it to update one controls properties from another control’s action. Same you can also call a delegates whens some UI interaction done like button clicked. Hope you liked it. Stay tuned for more. In next post I am going to explain about multicast delegates. Till then happy programming.

    Read the article

  • In Linux, what's the best way to delegate administration responsibilities, like for Apache, a database, or some other application?

    - by Andrew Banks
    In Linux, what's the best way to delegate administration responsibilities for Apache and other "applications"? File permissions? Sudo? A mix of both? Something else? At work we have two tiers of "administrators" Operating system administrators. These are your run-of-the-mill "server administrators." They are responsible for just the operating system. Application administrators. The people who build the web site. This includes not only writing the SQL, PHP, and HTML, but also setting up and running Apache and PostgreSQL or MySQL. The aforementioned OS admins will install this stuff, but it's mainly up to the app admins to edit all the config files, start and stop processes when needed, and so on. I am one of the app admins. This is different than what I am used to. I used to just write code. The sysadmin took care not only of the OS but also installing, setting up, and keeping up the server software. But he left. Now I'm in charge of setting up Apache and the database. The new sysadmins say they just handle the operating system. It's no problem. I welcome learning new stuff. But there is a learning curve, even for the OS admins. Apache, by default, seems to be set up for administration by root directly. All the config files and scripts are 644 and owned by root:root. I'm not given the root password, naturally, so the OS admins must somehow give my ordinary OS user account all the rights necessary to edit Apache's config files, start and stop it, read its log files, and so on. Right now they're using a mix of: (1) giving me certain sudo rights, (2) adding me to certain groups, and (3) changing the file permissions of various directories, to make them writable by one of the groups I'm in. This never goes smoothly. There's always a back-and-forth between me and the sysadmins. They say it's ready. Then I try certain things, and half of them I still can't do. So they make some more changes. Then finally I seem to be independent and can administer Apache and the database without pestering them anymore. It's the sheer complication and amount of changes that make me uncomfortable. Even though it finally works, more or less, it seems hackneyed. I feel like we're doing it wrong. It seems like the makers of the software would have anticipated this scenario (someone other than root administering it) and have a clean two- or three-step program to delegate responsibility to me. But it feels like we are really chewing up the filesystem and making it far and away from the default set-up. Any suggestions? Are we doing it the recommended way? P.S. For PostgreSQL it seems a little better. Its files are owned by a system user named postgres. So giving me the right to run sudo su - postgres gives me just about everything. I'm just now getting into MySQL, but it seems to be set up similarly. But it seems a little weird doing all my work as another user.

    Read the article

  • How to set foreground Window from Powershell event subscriber action

    - by guillermooo
    I have a FileSystemWatcher instance running in the background of my PoSh session watching for changes to text files. A PoSh event subscriber is attached to this event and, when fired, it launches a console program by calling Start-Process. This program steals de focus from the current foreground window (my PoSh console). Calling SetForegroundWindow from the PoSh event subscriber to return the focus to my PoSh console doesn't work. SwitchToThisWindow does work most of the time, but according to the MSDN docs, it shoulnd't be used. Can I prevent Start-Process from stealing the focus in this situation or set it back from the event subscriber to the window that had it before this event is fired?

    Read the article

< Previous Page | 81 82 83 84 85 86 87 88 89 90 91 92  | Next Page >