public Task Start(string[] rawData, FSharpFunc <int[], Observation> classifier) { var tasks = new List <Task <Observation> >(); foreach (var imageString in rawData) { int actual = imageString.Split(',').Select(x => Convert.ToInt32(x)).First(); int[] ints = imageString.Split(',').Select(x => Convert.ToInt32(x)).Skip(1).ToArray(); var task = Task.Run <Observation>(() => { return(Recognizers.predict <Observation>(ints, classifier)); } ); tasks.Add(task); task.ContinueWith(t => { CreateUIElements(t.Result.Label, actual.ToString(), imageString, DigitsBox); }, TaskScheduler.FromCurrentSynchronizationContext() ); } Task.WhenAny(tasks).ContinueWith(t => startTime = DateTime.Now); return(Task.CompletedTask); }
public static FSharpFunc <T1, FSharpFunc <T2, TResult> > Create <T1, T2, TResult>(Func <T1, T2, TResult> func) { Converter <T1, FSharpFunc <T2, TResult> > conv = value1 => { return(Create <T2, TResult>(value2 => func(value1, value2))); }; return(FSharpFunc <T1, FSharpFunc <T2, TResult> > .FromConverter(conv)); }
public static V Max <K, V>(this Series <K, V> series) { Series <K, V> series1 = series; FSharpFunc <V, FSharpFunc <V, V> > fsharpFunc = (FSharpFunc <V, FSharpFunc <V, V> >) new SeriesStatsExtensions.Max <V>(); Series <K, V> series2 = series1; V v = default(V); bool flag = false; IEnumerator <OptionalValue <V> > enumerator = FVectorextensionscore.IVector ` 1get_DataSequence < V > (series2.Vector).GetEnumerator(); try { while (enumerator.MoveNext()) { OptionalValue <V> current = enumerator.Current; if (current.HasValue) { v = !flag ? current.Value : (V)FSharpFunc <V, V> .InvokeFast <V>((FSharpFunc <V, FSharpFunc <V, M0> >) fsharpFunc, v, current.Value); flag = true; } } } finally { (enumerator as IDisposable)?.Dispose(); } return((V)OptionModule.GetValue <V>(!flag ? (FSharpOption <M0>)null : (FSharpOption <M0>)FSharpOption <V> .Some(v))); }
internal Scheduler(bool foreground, Job <int> idleHandler, int maxStackSize, int numWorkers, ThreadPriority priority, FSharpFunc <Exception, Job <Unit> > topLevelHandler) { StaticData.Init(); TopLevelHandler = topLevelHandler; IdleHandler = idleHandler; WaiterStack = -1; NumActive = numWorkers; Events = new WorkerEvent[numWorkers]; var threads = new Thread[numWorkers]; for (int i = 0; i < numWorkers; ++i) { Events[i] = new WorkerEvent(i); var index = i; var thread = new Thread(() => Worker.Run(this, index), maxStackSize); threads[i] = thread; thread.Priority = priority; thread.IsBackground = !foreground; } for (int i = 0; i < numWorkers; ++i) { threads[i].Start(); } }
private Union CreateUnion(Type t) { Union u = new Union(); u.TagReader = FSharpFunc <object, int> .ToConverter(FSharpValue.PreComputeUnionTagReader(t, null)); u.Cases = new List <UnionCase>(); UnionCaseInfo[] cases = FSharpType.GetUnionCases(t, null); foreach (UnionCaseInfo unionCaseInfo in cases) { UnionCase unionCase = new UnionCase(); unionCase.Tag = unionCaseInfo.Tag; unionCase.Name = unionCaseInfo.Name; unionCase.Fields = unionCaseInfo.GetFields(); unionCase.FieldReader = FSharpFunc <object, object[]> .ToConverter(FSharpValue.PreComputeUnionReader(unionCaseInfo, null)); unionCase.Constructor = FSharpFunc <object[], object> .ToConverter(FSharpValue.PreComputeUnionConstructor(unionCaseInfo, null)); u.Cases.Add(unionCase); } return(u); }
internal static void QuickThrowOnFail <T>(this FSharpFunc <T, bool> test, int maxNb) { // Fluent.Configuration does not support ThrowOnFailure && Config type is F# record. var config = MBrace.Flow.Tests.Check.QuickThrowOnFailureConfig(maxNb); Check.One(config, test); }
public UWP() { TargetHelper.Target("Default", FSharpFunc.FromAction(() => { Console.WriteLine("Android"); })); }
public void Filter() { var arbInt = Arb.Default.Int32(); var arbFiltered = Arb.filter(FSharpFunc <int, bool> .FromConverter(i => i > 10 && i < 20), arbInt); Check.VerboseThrowOnFailure(Prop.forAll(arbFiltered, FSharpFunc <int, bool> .FromConverter(i => true))); }
public void GenSized() { var genInt = Arb.generate <int>(); var genSized = Gen.sized(FSharpFunc <int, Gen <int[]> > .FromConverter(size => Gen.arrayOfLength(size, genInt))); genSized.DumpSamples(Formatters.FormatCollection); }
public void ToArbitrary() { var genInt = Any.OfType <int>(); var arb = genInt.ToArbitrary(); Check.VerboseThrowOnFailure(Prop.forAll(arb, FSharpFunc <int, bool> .FromConverter(i => true))); }
public Task ExecuteAsync( ControllerActionDescriptor action, Utf8JsonWriter writer, JsonSerializerOptions options) { var namingPolicy = options.PropertyNamingPolicy; writer.WriteStartObject(); writer.WriteString(namingPolicy.ConvertName("type"), "object"); writer.WriteStartObject(namingPolicy.ConvertName("properties")); writer.WriteStartObject(namingPolicy.ConvertName("api")); writer.WriteString(namingPolicy.ConvertName("type"), "object"); writer.WriteStartObject(namingPolicy.ConvertName("properties")); writer.WriteStartObject(namingPolicy.ConvertName("title")); writer.WriteString(namingPolicy.ConvertName("type"), "string"); writer.WriteEndObject(); writer.WriteEndObject(); writer.WriteEndObject(); writer.WriteStartObject(namingPolicy.ConvertName("resources")); writer.WriteString(namingPolicy.ConvertName("type"), "object"); writer.WriteBoolean(namingPolicy.ConvertName("additionalProperties"), false); writer.WriteEndObject(); writer.WriteEndObject(); var returnType = action.MethodInfo.GetCustomAttribute <ReturnsAttribute>()?.ReturnType ?? typeof(object); var links = Links.ForType(FSharpFunc <Type, InputJsonSchema> .FromConverter(SchemaGenerator.getInputSchema), returnType); SchemaSerializer.writeLinks(links).Invoke(Tuple.Create(writer, options)); writer.WriteEndObject(); return(Task.CompletedTask); }
public ManyCharsTill(FSharpFunc <CharStream <TUserState>, Reply <char> > charParser1, FSharpFunc <CharStream <TUserState>, Reply <char> > charParser, FSharpFunc <CharStream <TUserState>, Reply <TEnd> > endParser, FSharpFunc <string, FSharpFunc <TEnd, TResult> > mapping) : base(charParser1, charParser, endParser, mapping) { }
/// <summary> /// <para> /// `p.RunOnStream(stream,u,enc,name)` runs the parser `p` on the content of the /// `System.IO.Stream` `stream`, starting with the initial user state `u`. /// </para> /// <para> /// The `name` is used in error messages to describe the source of the input (e.g. a file /// path) and may be `null` or empty. /// </para> /// <para> /// In case no unicode byte order mark is found, the stream data is assumed to be encoded /// with the given `enc`. `Encoding.Default` will be used if `enc` was not specified. /// </para> /// <para>The parser's `Reply` is captured and returned as a `ParserResult` value.</para> /// </summary> public static ParserResult <TResult, U?> RunOnStream <U, TResult>( this FSharpFunc <CharStream <U?>, Reply <TResult> > p, Stream byteStream, U?userState = default, Encoding?encoding = null, string?streamName = null) => runParserOnStream(p, userState, streamName, byteStream, encoding ?? Encoding.Default);
public void OnShrink(FSharpList <object> args, FSharpFunc <FSharpList <object>, string> everyShrink) { TestTimer.Stop(); RunnerImplementation.OnShrink(args, everyShrink); numberOfShrinks++; if (!isDetailedTraces) { if (isRunningTests && FsCheckRunnerConfig.TraceNumberOfRuns) { isRunningTests = false; FormattableString.Invariant($"Failed test: {latestNumTests} / {MaxTest}"); } if (isRunningShrinks && FsCheckRunnerConfig.TraceNumberOfRuns) { Trace( FormattableString.Invariant( $"Ran shrink: {numberOfShrinks} in {TestTimer.ElapsedMilliseconds:n0}ms" ) ); } isRunningShrinks = true; } TestTimer.Restart(); }
public static void MapOne() { // define a list of names List <string> names = new List <string>( new string[] { "Stefany", "Oussama", "Sebastien", "Frederik" }); // define a predicate delegate/function Converter <string, bool> pred = delegate(string s) { return(s.StartsWith("S")); }; // convert to a FastFunc FSharpFunc <string, bool> ff = FuncConvert.ToFSharpFunc <string, bool>(pred); // call the F# demo function IEnumerable <string> results = DemoModule2.filterStringList(ff, names); // write the results to the console foreach (var name in results) { Console.WriteLine(name); } }
public void Merge(ICell source, Model model) { if (source != this) { var c = (ICell <T>)source; var f = _func; _func = c.Function; Parent = c.Parent; c.Function = f; } if (source != this) { source.Dispose(); } // handle update of current while this cell is being constructed if (Parent is Model m) { var cur = m[this.Mnemonic]; if (cur != this && cur.GetType() == this.GetType()) { cur.Merge(this, model); } } }
public static double Mean <K, V>(this Series <K, V> series) { Series <K, V> series1 = series; int num1 = 1; OptionalValue <V>[] optionalValueArray = StatsInternal.valuesAllOpt <K, V>(series1); int num2 = num1; V[] vArray1 = ArrayModule.Choose <OptionalValue <V>, V>((FSharpFunc <M0, FSharpOption <M1> >) new SeriesStatsExtensions.Mean <V>(), (M0[])optionalValueArray); FSharpFunc <V, double> fsharpFunc = (FSharpFunc <V, double>) new SeriesStatsExtensions.Mean <V>(); V[] vArray2 = vArray1; if ((object)vArray2 == null) { throw new ArgumentNullException("array"); } double[] init = new double[vArray2.Length]; int moment = num2; for (int index = 0; index < init.Length; ++index) { init[index] = fsharpFunc.Invoke(vArray2[index]); } StatsInternal.Sums sums = StatsInternal.initSumsDense(moment, init); return(sums.sum / sums.nobs); }
public static FSharpOption <T2> Map <T1, T2>(this FSharpOption <T1> opt, Func <T1, T2> f) { return(OptionModule.Map( FSharpFunc <T1, T2> .FromConverter(a => f(a)), opt )); }
public static TimeWarpStateCalculator GetTimeWarpStateCalculator() { Func <TimeWarpState, TimeSpan> csFunc = i => { switch (i) { case (TimeWarpState.None): return(TimeSpan.Zero); case (TimeWarpState.Resting): return(TimeSpan.FromMilliseconds(100)); case (TimeWarpState.Working): return(TimeSpan.FromMilliseconds(200)); default: throw new InvalidEnumArgumentException("i", (int)i, typeof(TimeWarpState)); } }; var fsharpFunc = FSharpFunc <TimeWarpState, TimeSpan> .FromConverter( new Converter <TimeWarpState, TimeSpan>(csFunc)); var timeWarpStateCalculator = new TimeWarpStateCalculator(fsharpFunc); return(timeWarpStateCalculator); }
public static Frame <TRowKey, TColumnKey> GetRowsAt <TRowKey, TColumnKey>(this Frame <TRowKey, TColumnKey> frame, params int[] indices) { int[] numArray1 = indices; FSharpFunc <int, TRowKey> fsharpFunc1 = (FSharpFunc <int, TRowKey>) new FrameExtensions.keys9 <TRowKey, TColumnKey>(frame.Rows); int[] numArray2 = numArray1; if ((object)numArray2 == null) { throw new ArgumentNullException("array"); } TRowKey[] rowKeyArray1 = new TRowKey[numArray2.Length]; for (int index = 0; index < rowKeyArray1.Length; ++index) { rowKeyArray1[index] = fsharpFunc1.Invoke(numArray2[index]); } TRowKey[] rowKeyArray2 = rowKeyArray1; int[] numArray3 = indices; FSharpFunc <int, ISeries <TColumnKey> > fsharpFunc2 = (FSharpFunc <int, ISeries <TColumnKey> >) new FrameExtensions.values0 <TColumnKey, TRowKey>(frame); int[] numArray4 = numArray3; if ((object)numArray4 == null) { throw new ArgumentNullException("array"); } ISeries <TColumnKey>[] seriesArray1 = new ISeries <TColumnKey> [numArray4.Length]; for (int index = 0; index < seriesArray1.Length; ++index) { seriesArray1[index] = fsharpFunc2.Invoke(numArray4[index]); } ISeries <TColumnKey>[] seriesArray2 = seriesArray1; return(FFrameextensions.FrameofRowsStatic <TRowKey, ISeries <TColumnKey>, TColumnKey>((IEnumerable <Tuple <TRowKey, ISeries <TColumnKey> > >)SeqModule.Zip <TRowKey, ISeries <TColumnKey> >((IEnumerable <M0>)rowKeyArray2, (IEnumerable <M1>)seriesArray2))); }
public void GenSuchThatOption() { var genInt = Arb.generate <int>(); var genSuchThatOption = Gen.suchThatOption(FSharpFunc <int, bool> .FromConverter(i => i > 10 && i < 20), genInt); genSuchThatOption.DumpSamples(); }
public void Merge(ICell source, Model model) { if (source != this) { var c = (ICell <T>)source; var f = _func; _func = c.Function; c.Function = f; Parent = c.Parent; _state = (int)CellState.Dirty; } RaiseChange(CellEvent.Calculate, this, this, DateTime.Now, null); // handle update of current while this cell is being constructed if (Parent is Model m) { ICell cur; if (m.TryGetValue(this.Mnemonic, out cur)) { if (cur != this && cur.GetType() == this.GetType()) { cur.Merge(this, model); } } } }
static SimpleJson() { FSharpFunc <CharStream <Unit>, Reply <JToken?> >?jvalue = null; var jnull = StringCI("null", (JToken?)null).Lbl("null"); var jnum = Float.Map(i => (JToken?)i).Lbl("number"); var jbool = StringCI("true").Or(StringCI("false")) .Map(b => (JToken?)bool.Parse(b)) .Lbl("bool"); var quotedString = Between('"', ManyChars(NoneOf("\"")), '"'); var jstring = quotedString.Map(s => (JToken?)s).Lbl("string"); var arrItems = Many(Rec(() => jvalue), sep: CharP(',').And(WS)); var jarray = Between(CharP('[').And(WS), arrItems, CharP(']')) .Map(elems => (JToken?)new JArray(elems)) .Lbl("array"); var jidentifier = quotedString.Lbl("identifier"); var jprop = jidentifier.And(WS).And(Skip(':')).And(WS).And(Rec(() => jvalue)) .Map((name, value) => new JProperty(name, value)); var objProps = Many(jprop, sep: CharP(',').And(WS)); var jobject = Between(CharP('{').And(WS), objProps, CharP('}')) .Map(props => (JToken?)new JObject(props)) .Lbl("object"); jvalue = Choice(jnum, jbool, jnull, jstring, jarray, jobject).And(WS); SimpleJsonParser = WS.And(jobject).And(WS).And(EOF).Map(o => (JObject?)o); }
public static Arbitrary <Doc> Doc() { //TODO: add Gen.sized which accepts Func<int, Gen<T>> - ?? var func = FSharpFunc <int, Gen <Doc> > .FromConverter(new Converter <int, Gen <Doc> >(DocGenenerator.Generator)); return(Arb.fromGen(Gen.sized(func))); }
public TraceSubscriber(Generic.ICell <T> source, FSharpFunc <T, string> formater, string prefix = "") { listener = source.Subscribe(this); printline = "Observed " + prefix + source.Mnemonic + " : {0}"; _formater = formater; var v = source.Value; }
public static double Median <K, V>(this Series <K, V> series) { V[] vArray1 = (V[])ArrayModule.OfSeq <V>((IEnumerable <M0>)series.Values); FSharpFunc <V, double> fsharpFunc = (FSharpFunc <V, double>) new SeriesStatsExtensions.Median <V>(); V[] vArray2 = vArray1; if ((object)vArray2 == null) { throw new ArgumentNullException("array"); } double[] numArray = new double[vArray2.Length]; for (int index = 0; index < numArray.Length; ++index) { numArray[index] = fsharpFunc.Invoke(vArray2[index]); } double[] arr = numArray; int n = arr.Length / 2; if (arr.Length == 0) { return(Operators.get_NaN()); } if (arr.Length % 2 == 1) { return(StatsInternal.quickSelectInplace(n, arr)); } return((StatsInternal.quickSelectInplace(n, arr) + StatsInternal.quickSelectInplace(n - 1, arr)) / 2.0); }
private static FSharpFunc <CharStream <Unit>, Reply <double> > MathFunc(FSharpFunc <CharStream <Unit>, Reply <double> > term, string key, Func <double, double> func) { var noParenthesis = Pipe(StringP(key).And(WS), term, (_, d) => func(d)); var withParenthesis = Pipe(StringP(key).And(WS), CharP('(').And(WS), term.And(WS), CharP(')'), (_, pl, d, pr) => func(d)); return(noParenthesis.Or(withParenthesis)); }
public iOS() { TargetHelper.Target("Default", FSharpFunc.FromAction(() => { Console.WriteLine("iOS"); })); }
/// <summary> /// Perform the specified action when the specified text view is ready /// </summary> /// <param name="textView"></param> /// <param name="action"></param> public virtual void DoActionWhenTextViewReady(FSharpFunc <Unit, Unit> action, ITextView textView) { // Local functions to do the action. void doAction() { // Perform action if the text view is still open. if (!textView.IsClosed && !textView.InLayout) { action.Invoke(null); } } void doActionHandler(object sender, RoutedEventArgs e) { // Unsubscribe. if (sender is FrameworkElement element) { element.Loaded -= doActionHandler; } // Then schedule the action. _protectedOperations.BeginInvoke(doAction, DispatcherPriority.Loaded); } if (textView is IWpfTextView wpfTextView && !wpfTextView.VisualElement.IsLoaded) { // FrameworkElement.Loaded Event: // // Occurs when a FrameworkElement has been constructed and // added to the object tree, and is ready for interaction. wpfTextView.VisualElement.Loaded += doActionHandler; }
public static Deedle.Series <a, b> ofObservations <a, b>(IEnumerable <Tuple <a, b> > observations) { Tuple <a, b>[] tupleArray1 = (Tuple <a, b>[])ArrayModule.OfSeq <Tuple <a, b> >((IEnumerable <M0>)observations); FSharpFunc <Tuple <a, b>, a> fsharpFunc1 = (FSharpFunc <Tuple <a, b>, a>) new FSeriesextensions.ofObservations <a, b>(); Tuple <a, b>[] tupleArray2 = tupleArray1; if ((object)tupleArray2 == null) { throw new ArgumentNullException("array"); } a[] aArray1 = new a[tupleArray2.Length]; for (int index = 0; index < aArray1.Length; ++index) { aArray1[index] = fsharpFunc1.Invoke(tupleArray2[index]); } a[] aArray2 = aArray1; FSharpFunc <Tuple <a, b>, b> fsharpFunc2 = (FSharpFunc <Tuple <a, b>, b>) new FSeriesextensions.ofObservations <a, b>(); Tuple <a, b>[] tupleArray3 = tupleArray1; if ((object)tupleArray3 == null) { throw new ArgumentNullException("array"); } b[] values = new b[tupleArray3.Length]; a[] keys = aArray2; for (int index = 0; index < values.Length; ++index) { values[index] = fsharpFunc2.Invoke(tupleArray3[index]); } return(new Deedle.Series <a, b>(keys, values)); }
void IRunner.OnShrink ( FSharpList<object> args , FSharpFunc<FSharpList<object>, string> everyShrink ) { var msg = everyShrink.Invoke(args); if (!silent) { Console.Write(msg); } }
public RecognizerControl(string classifierName, FSharpFunc<int[], string> classifier, string[] rawData) { InitializeComponent(); this.classifierName = classifierName; this.classifier = classifier; this.rawData = rawData; Loaded += RecognizerControl_Loaded; }
void IRunner.OnArguments ( int ntest , FSharpList<object> args , FSharpFunc<int, FSharpFunc<FSharpList<object>, string>> every ) { var msg = every.Invoke(ntest).Invoke(args); if (!silent) { Console.Write(msg); } }
private void connect() { string host = textBox1.Text.Substring(0,textBox1.Text.IndexOf(':')); string port = textBox1.Text.Substring(host.Length + 1); var fsharp_func = Microsoft.FSharp.Core.FSharpFunc<string, object>.FromConverter( new Converter<string, object>(AfterReceivingFunction)); writer = fsmsclient.library.initconnectionCS(fsmsclient.library.initConnection, host, Convert.ToInt32(port), fsharp_func); writer.Invoke("0\n\n"); textBox1.Text = "Connected"; }
public ConverterPropertyGroup( INumeralConverter sut, FSharpFunc<int, string> toNumeralImp, FSharpFunc<string, FSharpOption<int>> tryParseImp) { this.Sut = sut; this.ToNumeralImp = toNumeralImp; this.TryParseImp = tryParseImp; }
//Binds symbols of the given string to the given External Function. public void DefineExternal(string name, FSharpFunc<FSharpList<Value>, Value> func) { //add(name, Value.NewFunction(func)); Evaluate(Expression.NewDefine(name, Expression.NewFunction_E(func))); }
/// <summary> /// Example of a higher order function /// </summary> public static FinalGameScore MapScore(FSharpFunc<int, int> f, FinalGameScore game) { return new FinalGameScore(game.Game, f.Invoke(game.FinalScore)); }
private CountedTagger<TextMarkerTag> Create(object key, PropertyCollection propertyCollection, FSharpFunc<Unit, ITagger<TextMarkerTag>> func) { var result = CountedTagger<TextMarkerTag>.Create(key, propertyCollection, func); return (CountedTagger<TextMarkerTag>)result; }