public HistoryView(UserData data, Func1 setButtons, Func2 changeView, Func3 makeRequest) { //init user data userData = data; //init widgets delete = new Button("Delete history"); vBox = new VBox(false, 20); //populate items list items = new List <HistoryItem>(); foreach (UserData.History h in userData.history) { items.Add(new HistoryItem(h.url, h.time.ToString(), h.title)); } //init and add items to the view for (int i = items.Count - 1; i >= 0; i--) { vBox.PackStart(items[i], false, false, 0); items[i].gotoUrl.Clicked += (obj, args) => gotoHistory(changeView, makeRequest, ((HistoryItem)((Button)obj).Parent.Parent).url); } //add main event handlers delete.Clicked += (obj, args) => deleteHistory(setButtons); //finish layout vBox.PackStart(delete, false, false, 0); this.Add(vBox); }
private bool Increment(DataKey <long> datakey, long delta, Func2 <DataKey <IncrementDataSlot>, bool> storeStrategy) { var slot = new DataKey <IncrementDataSlot>(datakey.Key); if (!Get(slot)) { return(false); } if (!slot.HasValue) { lock (m_sync) { if (!Get(slot)) { return(false); } if (!slot.HasValue) { slot.Value = new IncrementDataSlot(datakey.Value); return(storeStrategy(slot)); } } } datakey.Value = slot.Value.Add(delta); return(true); }
/// <summary> /// Invokes a handler on each <see cref="T:System.Exception"/> contained by this <see /// cref="AggregateException"/>. /// </summary> /// <param name="predicate">The predicate to execute for each exception. The predicate accepts as an /// argument the <see cref="T:System.Exception"/> to be processed and returns a Boolean to indicate /// whether the exception was handled.</param> /// <remarks> /// Each invocation of the <paramref name="predicate"/> returns true or false to indicate whether the /// <see cref="T:System.Exception"/> was handled. After all invocations, if any exceptions went /// unhandled, all unhandled exceptions will be put into a new <see cref="AggregateException"/> /// which will be thrown. Otherwise, the <see cref="Handle"/> method simply returns. If any /// invocations of the <paramref name="predicate"/> throws an exception, it will halt the processing /// of any more exceptions and immediately propagate the thrown exception as-is. /// </remarks> /// <exception cref="AggregateException">An exception contained by this <see /// cref="AggregateException"/> was not handled.</exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="predicate"/> argument is /// null.</exception> public void Handle(Func2 <Exception, bool> predicate) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } List <Exception> unhandledExceptions = null; for (int i = 0; i < m_innerExceptions.Count; i++) { // If the exception was not handled, lazily allocate a list of unhandled // exceptions (to be rethrown later) and add it. if (!predicate(m_innerExceptions[i])) { if (unhandledExceptions == null) { unhandledExceptions = new List <Exception>(); } unhandledExceptions.Add(m_innerExceptions[i]); } } // If there are unhandled exceptions remaining, throw them. if (unhandledExceptions != null) { throw new AggregateException(Message, unhandledExceptions); } }
public FavoritesView(UserData data, Func1 updateStatus, Func2 changeView, Func3 makeRequest) { //init user data userData = data; //init widgets items = new List <FavoriteItem>(); vBox = new VBox(false, 20); //populate item list foreach (UserData.Favorite f in userData.favorites) { items.Add(new FavoriteItem(f.url, f.name)); } //init and add items to the view for (int i = 0; i < items.Count; i++) { vBox.PackStart(items[i], false, false, 0); items[i].save.Clicked += (obj, args) => updateName((FavoriteItem)((Button)obj).Parent, updateStatus); items[i].gotoUrl.Clicked += (obj, args) => gotoFav(changeView, makeRequest, ((FavoriteItem)((Button)obj).Parent).urlEntry.Text); } //finalise this.Add(vBox); }
/// <summary> /// 全ての要素にある処理を行う。 /// </summary> /// <param name="arr">対象の配列</param> /// <param name="f">処理の関数。</param> public static void ForEach(T[] arr, Func2 f) { for (int i = 0; i < arr.Length; i++) { f(i, arr[i]); } }
static void Main() { Func1 ToDigitArray = IntToNumbers; Func2 <int> PrintArray = PrintIntArray; do { Console.Clear(); int randomNumber = rnd.Next(10000, 100000); int[] randomArray = new int[10]; for (int i = 0; i < randomArray.Length; ++i) { randomArray[i] = rnd.Next(10, 100); } Console.WriteLine("Random number: " + randomNumber); Console.WriteLine("Number to digits: "); PrintArray(ToDigitArray(randomNumber)); Console.WriteLine("Print array: "); PrintArray(randomArray); Console.WriteLine("ToDigitArray.Method: " + ToDigitArray.Method); Console.WriteLine("ToDigitArray.Target: " + ToDigitArray.Target); Console.WriteLine("PrintArray.Method: " + PrintArray.Method); Console.WriteLine("PrintArray.Target: " + PrintArray.Target); Console.WriteLine("Press Esc to exit. Press any other key to continue."); } while (Console.ReadKey(true).Key != ConsoleKey.Escape); }
public void Lazy_Value_ExceptionRecovery() { int counter = 0; // set in test function var fint = new Func2 <int>(() => { if (++counter < 5) { throw new Exception(); } else { return(counter); } }); var fobj = new Func2 <string>(() => { if (++counter < 5) { throw new Exception(); } else { return(counter.ToString()); } }); Value_ExceptionRecovery_IntImpl(new Lazy <int>(fint), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy <int>(fint, true), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy <int>(fint, false), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy <int>(fint, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy <int>(fint, LazyThreadSafetyMode.None), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy <int>(fint, LazyThreadSafetyMode.PublicationOnly), ref counter, 5); Value_ExceptionRecovery_StringImpl(new Lazy <string>(fobj), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy <string>(fobj, true), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy <string>(fobj, false), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy <string>(fobj, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy <string>(fobj, LazyThreadSafetyMode.None), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy <string>(fobj, LazyThreadSafetyMode.PublicationOnly), ref counter, 5.ToString()); }
public virtual bool DoWork(Func2 <bool> shutdownCallback) { try { if (Rules == null || SatisfyAllRules(shutdownCallback)) { OnAllRulesSatisfied(); if (TraceInfo.IsInfoEnabled) { TraceHelper.TraceInfo(TraceInfo, "Succeed"); } return(true); } } catch (Exception ex) { if (!HandleException(ex)) { // Rethrow exception and preserve the full call stack trace throw; } } return(false); }
void IInvocation.invoke() { if (avalabilityCheck() == false) { return; } if (_hasReturnValue) { R obj = default(R); switch (_argCount) { case 0: Func <R> f = (Func <R>)_func; obj = f(); break; case 1: Func1 <R, Arg1> f1 = (Func1 <R, Arg1>)_func; obj = f1((Arg1)_argList[0]); break; case 2: Func2 <R, Arg1, Arg2> f2 = (Func2 <R, Arg1, Arg2>)_func; obj = f2((Arg1)_argList[0], (Arg2)_argList[1]); break; default: Log.infoError("Function with " + _argCount + " arguments is not supported!"); break; } _returnValue = (object)obj; } else { switch (_argCount) { case 0: VFunc vf = (VFunc)_func; vf(); break; case 1: VFunc1 <Arg1> vf1 = (VFunc1 <Arg1>)_func; vf1((Arg1)_argList[0]); break; case 2: VFunc2 <Arg1, Arg2> vf2 = (VFunc2 <Arg1, Arg2>)_func; vf2((Arg1)_argList[0], (Arg2)_argList[1]); break; default: Log.infoError("Function with " + _argCount + " arguments is not supported!"); break; } } }
public static double[,] Method(Func f, Func2 f2, double a, double b, double h, double y0, double eps) { double maxPogr = 0; double[,] tableH = f2(f, a, b, y0, h); int count = 0; do { count++; h = h / 2; maxPogr = 0; double[,] tableH2 = f2(f, a, b, y0, h); double tmp; for (int i = 0; i < tableH.GetLength(1); i++) { tmp = Math.Abs(tableH[1, i] - tableH2[1, 2 * i]); if (f2 == createEulerTable) { tmp /= (Math.Pow(2, 1) - 1); Console.WriteLine("Макс. погрешность: {0:f4}\n Шаг: {1:f4}"); } else if (f2 == createEulerKoshiTable || f2 == createModifEulerTable) { tmp /= (Math.Pow(2, 2) - 1); } else { tmp /= (Math.Pow(2, 4) - 1); } if (tmp > maxPogr) { maxPogr = tmp; } } tableH = tableH2; } while (maxPogr > eps && count < GRAN); if (f2 == createEulerTable) { Console.WriteLine("Метод Эйлера"); } else if (f2 == createEulerKoshiTable) { Console.WriteLine("Метод Эйлера-Коши"); } else if (f2 == createModifEulerTable) { Console.WriteLine("Модифицированный Метод Эйлера"); } else { Console.WriteLine("Метод Рунге-Кутта"); } Console.WriteLine("Макс. погрешность: {0:f4}\n Шаг: {1:f4}", maxPogr, h); return(tableH); }
public Object iteri(Object[] arr, Func2 clos) { for (int i = 0; i < arr.Length; i++) { clos(i, arr[i]); } return(null); }
public Scoped2(T4 t4, Scoped3 scoped3, Func2 func2, Single2 single2, Single3 single3) { T4 = t4; Scoped3 = scoped3; Func2 = func2; Single2 = single2; Single3 = single3; }
public EscalateOverdueTicketWorkItem() { Rules = new Func2 <bool>[] { this.RetrieveTicket, this.EscalateToManager }; }
public object fold(Object[] arr, object init, Func2 clos) { for (int i = 0; i < arr.Length; i++) { init = clos(init, arr[i]); } return(init); }
public override bool DoWork(Func2 <bool> shutdownCallback) { Thread.Sleep(25); ThreadName = Thread.CurrentThread.Name; WorkDone = true; RunCount++; return(HasMoreWork); }
public Object[] mapi(Object[] arr, Func2 clos) { Object[] rv = new Object[arr.Length]; for (int i = 0; i < arr.Length; i++) { rv[i] = clos(i, arr[i]); } return(rv); }
public Singleton(Func2 <string, T> factory) { if (factory == null) { throw new ArgumentNullException("factory"); } m_factory = factory; }
/// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the /// specified <paramref name="valueFactory"/> function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when /// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic). /// </exception> public ThreadLocal(Func2 <T> valueFactory) { if (valueFactory == null) { throw new ArgumentNullException(nameof(valueFactory)); } Initialize(valueFactory, false); }
public void Future_EnsureStartOnceTest() { Func2 <int> action = () => 1; Task <int> target = new Task <int>(action); PrivateObject pvTarget = new PrivateObject(target); pvTarget.Invoke("EnsureStartOnce"); pvTarget.Invoke("EnsureStartOnce"); }
public void Future_WaitTest_TimeSpan() { Func2 <int> action = () => { Thread.Sleep(100); return(1); }; Task <int> target = new Task <int>(action); target.Start(); Assert.IsFalse(target.Wait(new TimeSpan(0))); Assert.IsTrue(target.Wait(new TimeSpan(0, 0, 1))); }
public WaitAsyncResult(Func2 <WaitAsyncResult, IAsyncResult, bool> callback) { if (callback == null) { throw new ArgumentNullException("callback"); } m_callback = callback; }
/// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the /// specified <paramref name="valueFactory"/> function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when /// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized. /// </param> /// <param name="trackAllValues">Whether to track all values set on the instance and expose them via the Values property.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic). /// </exception> public ThreadLocal(Func2 <T> valueFactory, bool trackAllValues) { if (valueFactory == null) { throw new ArgumentNullException(nameof(valueFactory)); } Initialize(valueFactory, trackAllValues); }
/// <summary> /// A test for Result /// </summary> private static void ResultTestHelper <TResult>(TResult expected) { Func2 <TResult> action = () => expected; Task <TResult> target = new Task <TResult>(action); target.Start(); target.Wait(); Assert.AreEqual <TResult>(expected, target.Result); }
public LazyObject(Func2 <T> loader) { if (loader == null) { throw new ArgumentNullException("loader"); } m_loader = loader; }
private static TransformFunc3 WrapCylinderZ(Func2 xyFn, Func2 zFn) { return(v => { var vZ = zFn(v.y); var vXY = xyFn(v.x); return new Vector3((1 + v.z) * vXY.x * vZ.x, (1 + v.z) * vXY.y * vZ.x, vZ.y); }); }
private static TransformFunc3 WrapSphereZ(Func2 xyFn, Func2 zFn) { return(v => { var vZ = zFn(v.y); var vXY = xyFn(v.x); return new Vector3(vXY.x * vZ.x, vXY.y * vZ.x, vZ.y) * (1 + v.z); }); }
public LazyPrincipal(Func2 <IPrincipal, T> loader) { if (loader == null) { throw new ArgumentNullException("loader"); } m_loader = loader; m_principal = null; }
static public Operation DoFuncOnMainThread <R, Arg1, Arg2>(Func2 <R, Arg1, Arg2> func, Arg1 arg1, Arg2 arg2, long delay = 0, VFunc1 <R> callback = null) { object[] args = { arg1, arg2 }; Invocation <R, Arg1, Arg2> inv = new Invocation <R, Arg1, Arg2> (func, 2, args, true); Invocation <Null, R, Null> cbInv = callback == null ? null : new Invocation <Null, R, Null> (callback, 1, null); Operation operation = new Operation(inv, ApplicationEX.GetCurrnSystemMillisecond() + delay, cbInv); MainThread.Instance.addExcutable(operation); return(operation); }
static public Operation DoFuncOnThread <R, Arg1, Arg2>(LoopThread loopThrad, Func2 <R, Arg1, Arg2> func, Arg1 arg1, Arg2 arg2, VFunc1 <R> callback = null, bool callbackOnMainThread = true, long delay = 0) { object[] args = { arg1, arg2 }; Invocation <R, Arg1, Arg2> inv = new Invocation <R, Arg1, Arg2> (func, 2, args, true); Invocation <Null, R, Null> cbInv = callback == null ? null : new Invocation <Null, R, Null> (callback, 1); Operation operation = new Operation(inv, ApplicationEX.GetCurrnSystemMillisecond() + delay, cbInv, callbackOnMainThread); loopThrad.addExecution(operation); return(operation); }
/// <summary> /// Initializes a target reference type using the specified function if it has not already been /// initialized. /// </summary> /// <typeparam name="T">The reference type of the reference to be initialized.</typeparam> /// <param name="target">The reference of type <typeparamref name="T"/> to initialize if it has not /// already been initialized.</param> /// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the /// reference.</param> /// <returns>The initialized reference of type <typeparamref name="T"/>.</returns> /// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a /// default constructor.</exception> /// <exception cref="T:System.InvalidOperationException"><paramref name="valueFactory"/> returned /// null.</exception> /// <remarks> /// <para> /// This method may only be used on reference types, and <paramref name="valueFactory"/> may /// not return a null reference (Nothing in Visual Basic). To ensure initialization of value types or /// to allow null reference types, see other overloads of EnsureInitialized. /// </para> /// <para> /// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>. /// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/> /// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the /// objects that were not stored. If such objects must be disposed, it is up to the caller to determine /// if an object was not used and to then dispose of the object appropriately. /// </para> /// </remarks> public static T EnsureInitialized <T>(ref T target, Func2 <T> valueFactory) where T : class { // Fast path. if (Volatile.Read <T>(ref target) != null) { return(target); } return(EnsureInitializedCore <T>(ref target, valueFactory)); }
static void Main() { int a = 6; int b = 2; Func2 add = new Func2(Add); Func2 mul = new Func2(Mul); Func2 div = new Func2(Div); Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(add, a, b)); Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call(mul, a, b)); Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(div, a, b)); }
static int Call(Func2 f, int a, int b) { return f(a, b); }
static extern void glutReshapeFunc(Func2 j);
public static double[] Broadcast(Func2 f, double x, double[] y) { double[] ret = new double[y.Length]; for (int i = 0; i < y.Length; i++) { ret[i] = f(x, y[i]); } return ret; }
public static double[] Broadcast(Func2 f, double[] x, double y) { double[] ret = new double[x.Length]; for (int i = 0; i < x.Length; i++) { ret[i] = f(x[i], y); } return ret; }
public void HandledBy(Func2 handler) { SetHandledBy(handler, 2, HandlerContextParam.None); }