public void Maybe_String_ValueIsCorrect() { var val = "Value"; var maybe = new Maybe<string>(val); Assert.AreEqual(val, maybe.Value); }
public void Maybe_Equals_BothHaveSameValueIsEqual() { var a = new Maybe<string>("a"); var b = new Maybe<string>("a"); Assert.IsTrue(a.Equals(b)); }
public void Maybe_Equals_DifferentValuesAreNotEqual() { var a = new Maybe<string>("a"); var b = new Maybe<string>("b"); Assert.AreNotEqual(a, b); }
static string DemoTheNewWayOfNullChecking() { Contact contact = new Contact(); contact.Name = "Sean"; contact.Phone = "12345678"; contact.Age = 24; //contact.PersonalPet = new Pet() //{ // PetName = new PetName() // { // Name = "My Pet" // } //}; // Maybe class allow you to do something similar to int? for the reference types. Maybe<Contact> maybeContact = new Maybe<Contact>(contact); var maybePetName = from c in maybeContact from cp in c.PersonalPet from pn in cp.PetName select pn.Name; if (maybePetName.HasValue) return maybePetName.Value; return null; }
public void Maybe_Equals_OnlyLeftHasValueNotEqual() { var a = new Maybe<string>("a"); var b = Maybe<string>.NoValue; Assert.IsFalse(a.Equals(b)); }
public void Value_ReturnsValue() { var value = "jepsen"; var maybe = new Maybe<string>(value); maybe.Value.Should().Be(value); }
public void Constructor_NotNullArgumentShouldHaveValue() { Maybe<string> str = new Maybe<string>("abc"); Assert.IsTrue(str.HasValue); Assert.AreEqual("abc", str.Value); }
/// <summary> /// Returns true if this computer should display the message for the given set of message /// receivers. /// </summary> private bool ShouldDisplay(Maybe<List<Player>> receivers) { if (receivers.IsEmpty) { return true; } return receivers.Value.Contains(_localPlayer); }
void Anything_FlatMapWithNothing_CreatesNothing() { Func<int, Maybe<int>> iiMap = (x) => Maybe<int>.Nothing; Func<int, Maybe<string>> isMap = (x) => Maybe<string>.Nothing; Func<string, Maybe<object>> soMap = (x) => Maybe<object>.Nothing; Maybe<int>[] int_maybes = new Maybe<int>[] { Maybe.Just(0), Maybe.Just(5), Maybe.Just(3282), Maybe.Just(-42), Maybe<int>.Nothing }; foreach (Maybe<int> m in int_maybes) { Maybe<int> ii_result = m.FlatMap(iiMap); Assert.False(ii_result.HasValue); Assert.Throws<NotSupportedException>(() => ii_result.Value); Assert.False(ii_result.FlatMap(iiMap).HasValue); Assert.False(ii_result.FlatMap(iiMap).FlatMap(iiMap).HasValue); Assert.False(ii_result.FlatMap(iiMap).Map(x => x * 2).HasValue); Maybe<string> is_result = m.FlatMap(isMap); Assert.False(is_result.HasValue); Assert.Throws<NotSupportedException>(() => is_result.Value); Assert.False(is_result.FlatMap(soMap).HasValue); Assert.False(is_result.FlatMap(soMap).Map(o => o.ToString()).HasValue); } }
public void standard_equality() { var m1 = new Maybe<int>(3); var m2 = new Maybe<int>(3); m1.HasValue.Should().BeTrue(); m1.Should().Be(m2); }
public PreKeyWhisperMessage(UInt32 messageVersion, UInt32 registrationId, Maybe<UInt32> preKeyId, UInt32 signedPreKeyId, ECPublicKey baseKey, IdentityKey identityKey, WhisperMessage message) { MessageVersion = messageVersion; RegistrationId = registrationId; PreKeyId = preKeyId; SignedPreKeyId = signedPreKeyId; BaseKey = baseKey; IdentityKey = identityKey; Message = message; var preKeyMessage = new WhisperProtos.PreKeyWhisperMessage { signedPreKeyId = SignedPreKeyId, baseKey = BaseKey.Serialize(), identityKey = IdentityKey.Serialize(), message = Message.Serialize(), registrationId = registrationId }; preKeyId.Do(pKid => preKeyMessage.preKeyId = pKid); byte[] versionBytes = { ByteUtil.IntsToByteHighAndLow(MessageVersion, CURRENT_VERSION) }; byte[] messageBytes; using(var stream = new MemoryStream()) { Serializer.Serialize(stream, preKeyMessage); messageBytes = stream.ToArray(); } _serialized = ByteUtil.Combine(versionBytes, messageBytes); }
protected override Maybe<Header> TryConstructHeader( Maybe<int> width, Maybe<int> height, Maybe<Ratio> framerate, Maybe<Ratio> pixelAspectRatio, Maybe<Interlacing> interlacing, Maybe<ColorSpace> colorspace, IEnumerable<string> comments ) { if (width.IsNothing() || height.IsNothing() || framerate.IsNothing()) { return Maybe<Header>.Nothing; } return (new FileHeader( width.Value, height.Value, framerate.Value, pixelAspectRatio, colorspace, interlacing, comments ) as Header).ToMaybe(); }
public static SpecificationProperty WithValue(this SpecificationProperty specProp, Maybe<object> newValue) { if (specProp == null) throw new ArgumentNullException("specProp"); if (newValue == null) throw new ArgumentNullException("newValue"); return SpecificationProperty.Create(specProp.Specification, specProp.Property, newValue); }
public ParseError(string sourceName, string message, Maybe<long> line, Maybe<long> column) { SourceName = sourceName; Message = message; Line = line; Column = column; }
/// <summary>IoC constructor.</summary>> public CloudProvisioning(ICloudConfigurationSettings settings, ILog log) { _log = log; _retryPolicy = AzureManagementPolicies.TransientServerErrorBackOff; // try get settings and certificate _deploymentId = CloudEnvironment.AzureDeploymentId; _subscriptionId = settings.SelfManagementSubscriptionId ?? Maybe.String; var certificateThumbprint = settings.SelfManagementCertificateThumbprint ?? Maybe.String; if (certificateThumbprint.HasValue) { _certificate = CloudEnvironment.GetCertificate(certificateThumbprint.Value); } // early evaluate management status for intrinsic fault states, to skip further processing if (!_deploymentId.HasValue || !_subscriptionId.HasValue || !certificateThumbprint.HasValue) { _status = ManagementStatus.ConfigurationMissing; return; } if (!_certificate.HasValue) { _status = ManagementStatus.CertificateMissing; return; } // ok, now try find service matching the deployment _enabled = true; TryFindDeployment(); }
public void ValueToMaybe() { int value = 10; Maybe<int> maybe = new Maybe<int>(value); Assert.IsTrue(maybe.HasValue); Assert.AreEqual(value, maybe.Value); }
public virtual void Saving(Maybe<Deal> deal) { if(deal.Any()) _logger.Info($"Saving : {deal}."); else _logger.Warn($" Try Saving : {deal}."); }
protected override Maybe<Header> TryConstructHeader( Maybe<int> width, Maybe<int> height, Maybe<Ratio> framerate, Maybe<Ratio> pixelAspectRatio, Maybe<Interlacing> interlacing, Maybe<ColorSpace> colorspace, IEnumerable<string> comments ) { int inputWidth = width.OrElse(_fileLevelHeader.Width); int inputHeight = height.OrElse(_fileLevelHeader.Height); Ratio inputFramerate = framerate.OrElse(_fileLevelHeader.Framerate); Maybe<Ratio> inputPixelAspectRatio = pixelAspectRatio.Or(_fileLevelHeader.PixelAspectRatio); Maybe<Interlacing> inputInterlacing = interlacing.Or(_fileLevelHeader.Interlacing); Maybe<ColorSpace> inputColorSpace = colorspace.Or(_fileLevelHeader.ColorSpace); IEnumerable<string> inputComments = _fileLevelHeader.Comments.Concat(comments); return (new FrameHeader( inputWidth, inputHeight, inputFramerate, inputPixelAspectRatio, inputColorSpace, inputInterlacing, inputComments) as Header).ToMaybe(); }
public Maybe<double> Calculate(string[] args) { if (args.Length == 0) return lastResult; if (args.Length == 1) return lastResult = TryParseDouble(args[0]); if (args.Length == 2) { // Если не хватает первого аргумента, то использовать lastResult // Должно работать так: // 2 + 2 //> 4 // + 1 //>5 return lastResult = Execute(args[0], lastResult.Value, double.Parse(args[1])); } if (args.Length == 3) { var v1 = TryParseDouble(args[0]); var v2 = TryParseDouble(args[2]); if (!v1.HasValue) return v1; if (!v2.HasValue) return v2; return lastResult = Execute(args[1], v1.Value, v2.Value); } return Maybe<double>.FromError("Error input"); }
public void Initialize() { // Required to register bourgeoise XAML URI schemes if (!UriParser.IsKnownScheme("pack")) new Application(); _accent = ThemeManager.TryGetAccent("Blue"); }
/// <summary> /// Restores a GameSnapshot using the given GameSnapshot JSON and the given TemplateGroup /// JSON. /// </summary> public static GameSnapshotRestorer Restore(string snapshotJson, string templateJson, Maybe<GameEngine> gameEngine) { string json = CombineJson(snapshotJson, templateJson); return SerializationHelpers.Deserialize<GameSnapshotRestorer>(json, RequiredConverters.GetConverters(), RequiredConverters.GetContextObjects(gameEngine)); }
public void Maybe_Equals_ComparisonByValue() { var val = "Value"; var a = new Maybe<string>(val); var b = new Maybe<string>(val); Assert.AreEqual(a, b); }
public void Maybe_Equals_SameValueAreEqual() { var val = "Value"; var a = new Maybe<string>(val); object b = new Maybe<string>(val); Assert.IsTrue(a.Equals(b)); }
static Maybe<int> Add(Maybe<int> x, Maybe<int> y) { return from _x in x from _y in y where _x < _y select _x + _y; }
public ValueSpecification(int index, string metaName, bool required, Maybe<int> min, Maybe<int> max, Maybe<object> defaultValue, string helpText, string metaValue, IEnumerable<string> enumValues, Type conversionType, TargetType targetType) : base(SpecificationType.Value, required, min, max, defaultValue, helpText, metaValue, enumValues, conversionType, targetType) { this.index = index; this.metaName = metaName; }
public static SpecificationProperty Create(Specification specification, PropertyInfo property, Maybe<object> value) { if (specification == null) throw new ArgumentNullException("specification"); if (property == null) throw new ArgumentNullException("property"); if (value == null) throw new ArgumentNullException("value"); return new SpecificationProperty(specification, property, value); }
public OptionSpecification(string shortName, string longName, bool required, string setName, int min, int max, Maybe<object> defaultValue, System.Type conversionType, string helpText, string metaValue) : base(SpecificationType.Option, required, min, max, defaultValue, conversionType) { this.shortName = shortName; this.longName = longName; this.setName = setName; this.helpText = helpText; this.metaValue = metaValue; }
public void Apply_EmptyMaybeReturnsEmptyMaybe() { Maybe<string> str = new Maybe<string>(null); Maybe<object> obj = str.Apply(x=>(Object)x); Assert.IsNotNull(obj); Assert.IsFalse(obj.HasValue); }
protected Specification(SpecificationType tag, bool required, int min, int max, Maybe<object> defaultValue, System.Type conversionType) { this.tag = tag; this.required = required; this.min = min; this.max = max; this.defaultValue = defaultValue; this.conversionType = conversionType; }
protected MoleculeSyntax(IEnumerable<Annotation> annotations, bool isExternal, bool isAbstract, Identifier name, Maybe<TypeReferenceSyntax> @base, IEnumerable<PropertySyntax> properties) { Annotations = Guard.NotNull(annotations, "annotations"); IsExternal = isExternal; IsAbstract = isAbstract; Name = Guard.NotNull(name, "name"); Base = @base; Properties = Guard.NotNull(properties, "properties"); }
public static ParserResult <T> Build <T>( Maybe <Func <T> > factory, Func <IEnumerable <string>, IEnumerable <OptionSpecification>, Result <IEnumerable <Token>, Error> > tokenizer, IEnumerable <string> arguments, StringComparer nameComparer, bool ignoreValueCase, CultureInfo parsingCulture, bool autoHelp, bool autoVersion, IEnumerable <ErrorType> nonFatalErrors) { var typeInfo = factory.MapValueOrDefault(f => f().GetType(), typeof(T)); var specProps = typeInfo.GetSpecifications(pi => SpecificationProperty.Create( Specification.FromProperty(pi), pi, Maybe.Nothing <object>())) .Memorize(); var specs = from pt in specProps select pt.Specification; var optionSpecs = specs .ThrowingValidate(SpecificationGuards.Lookup) .OfType <OptionSpecification>() .Memorize(); Func <T> makeDefault = () => typeof(T).IsMutable() ? factory.MapValueOrDefault(f => f(), Activator.CreateInstance <T>()) : ReflectionHelper.CreateDefaultImmutableInstance <T>( (from p in specProps select p.Specification.ConversionType).ToArray()); Func <IEnumerable <Error>, ParserResult <T> > notParsed = errs => new NotParsed <T>(makeDefault().GetType().ToTypeInfo(), errs); var argumentsList = arguments.Memorize(); Func <ParserResult <T> > buildUp = () => { var tokenizerResult = tokenizer(argumentsList, optionSpecs); var tokens = tokenizerResult.SucceededWith().Memorize(); var partitions = TokenPartitioner.Partition( tokens, name => TypeLookup.FindTypeDescriptorAndSibling(name, optionSpecs, nameComparer)); var optionsPartition = partitions.Item1.Memorize(); var valuesPartition = partitions.Item2.Memorize(); var errorsPartition = partitions.Item3.Memorize(); var optionSpecPropsResult = OptionMapper.MapValues( (from pt in specProps where pt.Specification.IsOption() select pt), optionsPartition, (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, parsingCulture, ignoreValueCase), nameComparer); var valueSpecPropsResult = ValueMapper.MapValues( (from pt in specProps where pt.Specification.IsValue() orderby((ValueSpecification)pt.Specification).Index select pt), valuesPartition, (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, parsingCulture, ignoreValueCase)); var missingValueErrors = from token in errorsPartition select new MissingValueOptionError( optionSpecs.Single(o => token.Text.MatchName(o.ShortName, o.LongName, nameComparer)) .FromOptionSpecification()); var specPropsWithValue = optionSpecPropsResult.SucceededWith().Concat(valueSpecPropsResult.SucceededWith()).Memorize(); var setPropertyErrors = new List <Error>(); //build the instance, determining if the type is mutable or not. T instance; if (typeInfo.IsMutable() == true) { instance = BuildMutable(factory, specPropsWithValue, setPropertyErrors); } else { instance = BuildImmutable(typeInfo, factory, specProps, specPropsWithValue, setPropertyErrors); } var validationErrors = specPropsWithValue.Validate(SpecificationPropertyRules.Lookup(tokens)); var allErrors = tokenizerResult.SuccessfulMessages() .Concat(missingValueErrors) .Concat(optionSpecPropsResult.SuccessfulMessages()) .Concat(valueSpecPropsResult.SuccessfulMessages()) .Concat(validationErrors) .Concat(setPropertyErrors) .Memorize(); var warnings = from e in allErrors where nonFatalErrors.Contains(e.Tag) select e; return(allErrors.Except(warnings).ToParserResult(instance)); }; var preprocessorErrors = ( argumentsList.Any() ? arguments.Preprocess(PreprocessorGuards.Lookup(nameComparer, autoHelp, autoVersion)) : Enumerable.Empty <Error>() ).Memorize(); var result = argumentsList.Any() ? preprocessorErrors.Any() ? notParsed(preprocessorErrors) : buildUp() : buildUp(); return(result); }
public void Deconstruct(out Maybe <MutatingChange> mutatingChange, out TData data) { mutatingChange = Change; data = Data; }
public DeferredSource(string name, Maybe <DataContextPromise> promise) : base(name, promise) { }
public ChainCall(StepId id, Maybe <ChainCall> baseCall = default) { BaseCall = baseCall; StepIds = new[] { id }; Position = May(0); }
public TransportMessage(ITransportHeader header, Maybe <IPooledBuffer> payload) { Header = header; Payload = payload; }
internal SwitchOptionDefinition(Maybe <string> shortName, Maybe <string> longName, string configurationKey, string configurationValue) : base(shortName, longName, configurationKey, false) { ConfigurationValue = configurationValue; }
public void Maybe_Of_ThrowsIfNull() { string s = null; Maybe.Of(s); }
public static void IdentityHolds(Maybe <int> v) { Func <int, int> id = x => x; Assert.Equal(Just(id).Apply(v), v); }
public static void _ApplicativeLawHolds(Maybe <int> a, Maybe <int> b) => Assert.Equal( Just(multiply).Apply(a).Apply(b), a.Map(multiply).Apply(b) );
//-------------------------------------------------------------------------------------------------------------------- public override Maybe <uint> fastCount() { return(Maybe.of((uint)(rangeEndExclusive - rangeStartInclusive))); }
public ChainCall(StepId[] ids) { StepIds = ids; Position = May(0); }
// init only via static methods private ScriptingContext(FsTypes fsType, Maybe <string> scriptsPathForRealFs, Maybe <Dictionary <string, string> > inMemoryFs) { if (fsType == FsTypes.InMemoryFs && scriptsPathForRealFs.HasValue) { throw new ArgumentException($"{nameof(scriptsPathForRealFs)} should not have a value if {nameof(fsType)} is of {FsTypes.InMemoryFs.ToString()} type"); } if (fsType == FsTypes.InMemoryFs && inMemoryFs.HasNoValue) { throw new ArgumentException($"{nameof(inMemoryFs)} should have a value if {nameof(fsType)} is of {FsTypes.InMemoryFs.ToString()} type"); } if (fsType == FsTypes.RealFs && scriptsPathForRealFs.HasNoValue) { throw new ArgumentNullException($"{nameof(scriptsPathForRealFs)} should have a value if {nameof(fsType)} is of {FsTypes.RealFs.ToString()} type"); } if (fsType == FsTypes.RealFs && inMemoryFs.HasValue) { throw new ArgumentNullException($"{nameof(inMemoryFs)} should not have a value if {nameof(fsType)} is of {FsTypes.RealFs.ToString()} type"); } if (fsType == FsTypes.NoFs && scriptsPathForRealFs.HasValue) { throw new ArgumentException($"{nameof(scriptsPathForRealFs)} should not have a value if {nameof(fsType)} is of {FsTypes.NoFs.ToString()} type"); } if (fsType == FsTypes.NoFs && inMemoryFs.HasValue) { throw new ArgumentNullException($"{nameof(inMemoryFs)} should not have a value if {nameof(fsType)} is of {FsTypes.NoFs.ToString()} type"); } FsType = fsType; InMemoryFs = inMemoryFs; ScriptsPathForRealFs = scriptsPathForRealFs; }
internal ValueOptionDefinition(Maybe <string> shortName, Maybe <string> longName, string configurationKey, bool isRequired) : base(shortName, longName, configurationKey, isRequired) { }
/// <summary> /// Включает использование брокера <c>RabbitMQ</c>. /// </summary> /// <param name="busConfigurator">Конфигуратор шины сообщений.</param> /// <returns>Конфигуратор шины сообщений с включенной поддержкой брокера.</returns> public static IBusConfigurator UseRabbitMq(this IBusConfigurator busConfigurator) { var c = (BusConfiguration)busConfigurator; if (c.BusFactoryFunc != null) { return(busConfigurator); } var blockedHeaders = new List <string> { Headers.Expires, Headers.MessageLabel, Headers.Persist, Headers.QueueMessageTtl, Headers.ReplyRoute, Headers.Timeout, Headers.Ttl }; var messageHeaderStorage = new Maybe <IIncomingMessageHeaderStorage>(new MessageHeaderStorage(blockedHeaders)); c.BuildBusUsing(bc => new RabbitBus(c)); c.SenderDefaults = new RabbitSenderOptions(c.EndpointOptions) { ConfirmationIsRequired = false, Persistently = false, RequestTimeout = TimeSpan.FromSeconds(30), Ttl = default(TimeSpan?), RouteResolverBuilder = RabbitBusDefaults.RouteResolverBuilder, IncomingMessageHeaderStorage = messageHeaderStorage, ReuseConnection = true, ProducerSelectorBuilder = RabbitBusDefaults.ProducerSelectorBuilder, FailoverAttempts = 7, MaxRetryDelay = 30, InactivityResetDelay = 120 }; c.ReceiverDefaults = new RabbitReceiverOptions(c.EndpointOptions) { AcceptIsRequired = false, ParallelismLevel = 1, EndpointBuilder = RabbitBusDefaults.SubscriptionEndpointBuilder, QoS = new QoSParams(50, 0), IncomingMessageHeaderStorage = messageHeaderStorage, ReuseConnection = true }; c.UseMessageLabelHandler(new DefaultRabbitMessageLabelHandler()); // TODO: extract, combine routing and handler definition Func <IRouteResolverBuilder, IRouteResolver> faultRouteResolverBuilder = b => { TimeSpan messageTtl = c.ReceiverDefaults.GetFaultQueueTtl().HasValue ? c.ReceiverDefaults.GetFaultQueueTtl().Value : TimeSpan.FromDays(FaultMessageTtlDays); string name = b.Endpoint.Address + ".Fault"; Exchange e = b.Topology.Declare(Exchange.Named(name).Durable.Topic); QueueBuilder builder = Queue.Named(name).Durable.WithTtl(messageTtl); if (c.ReceiverDefaults.GetFaultQueueLimit().HasValue) { builder = builder.WithLimit(c.ReceiverDefaults.GetFaultQueueLimit().Value); } Queue q = b.Topology.Declare(builder); b.Topology.Bind(e, q); return(e); }; c.Route("document.Contour.unhandled").Persistently().ConfiguredWith(faultRouteResolverBuilder).ReuseConnection(); c.Route("document.Contour.failed").Persistently().ConfiguredWith(faultRouteResolverBuilder).ReuseConnection(); c.OnUnhandled( d => { d.Forward("document.Contour.unhandled", d.BuildFaultMessage()); d.Accept(); }); c.OnFailed( d => { d.Forward("document.Contour.failed", d.BuildFaultMessage()); d.Accept(); }); return(busConfigurator); }
public static Maybe <T> TryTake <T>(this IProducerConsumerCollection <T> source) { Guard.NotNull(source, "source"); return(Maybe.TrySelect <T>(source.TryTake)); }
protected void WhenStep(StepId id, Action <LambdaStepConfiguration <TContext> > config, Maybe <Action <StepConfiguration <LambdaStep <TContext>, TContext> > > mayStepConfig = default) { var stepConfig = new LambdaStepConfiguration <TContext>(); config.Invoke(stepConfig); var stepConfiguration = WhenStep(id, stepConfig.Build()); Do(from postStepConfig in mayStepConfig select Action(() => postStepConfig.Invoke(stepConfiguration))); }
public void Explode_scalar_with_separator_in_even_args_input_returns_sequence() { // Fixture setup var expectedTokens = new[] { Token.Name("x"), Token.Name("string-seq"), Token.Value("aaa"), Token.Value("bb"), Token.Value("cccc"), Token.Name("switch") }; var specs = new[] { new OptionSpecification(string.Empty, "string-seq", false, string.Empty, Maybe.Nothing <int>(), Maybe.Nothing <int>(), ',', null, string.Empty, string.Empty, new List <string>(), typeof(IEnumerable <string>), TargetType.Sequence) }; // Exercize system var result = Tokenizer.ExplodeOptionList( Result.Succeed( Enumerable.Empty <Token>().Concat(new[] { Token.Name("x"), Token.Name("string-seq"), Token.Value("aaa,bb,cccc"), Token.Name("switch") }), Enumerable.Empty <Error>()), optionName => NameLookup.HavingSeparator(optionName, specs, StringComparer.InvariantCulture)); // Verify outcome Assert.True(expectedTokens.SequenceEqual(((Ok <IEnumerable <Token>, Error>)result).Value.Success)); // Teardown }
private ChainCall(StepId[] stepIds, Maybe <int> position, Maybe <ChainCall> baseCall = default) { BaseCall = baseCall; StepIds = stepIds; Position = position; }
public void Maybe_EqualsObject_NullNotEqual() { var maybe = new Maybe <string>("Test"); Assert.IsFalse(maybe.Equals(null)); }
public MutatingContext <TData> WithChange <TChange>(Maybe <TChange> mutatingChange) where TChange : MutatingChange => Update(mutatingChange.Cast <TChange, MutatingChange>(), Data);
public static SpecificationProperty WithValue(this SpecificationProperty specProp, Maybe <object> newValue) { if (newValue == null) { throw new ArgumentNullException("newValue"); } return(SpecificationProperty.Create(specProp.Specification, specProp.Property, newValue)); }
public void Maybe_GetHashCode() { var maybe = new Maybe <string>("Test"); Assert.AreNotEqual(0, maybe.GetHashCode()); }
protected static void buildItems(DifferenceResult result, List <DifferenceItem> oldItems, List <DifferenceItem> newItems, Maybe <ItemBuilder> _subItemBuilder) { var oldPosition = 0; var newPosition = 0; foreach (var diffBlock in result.DifferenceBlocks) { while (newPosition < diffBlock.NewInsertStart && oldPosition < diffBlock.OldDeleteStart) { oldItems.Add(new DifferenceItem(result.OldItems[oldPosition], DifferenceType.Unchanged, oldPosition + 1)); newItems.Add(new DifferenceItem(result.NewItems[newPosition], DifferenceType.Unchanged, newPosition + 1)); oldPosition++; newPosition++; } var i = 0; while (i < Math.Min(diffBlock.OldDeleteCount, diffBlock.NewInsertCount)) { var oldItem = new DifferenceItem(result.OldItems[i + diffBlock.OldDeleteStart], DifferenceType.Deleted, oldPosition + 1); var newItem = new DifferenceItem(result.NewItems[i + diffBlock.NewInsertStart], DifferenceType.Inserted, newPosition + 1); if (_subItemBuilder.If(out var subItemBuilder)) { var oldWords = result.OldItems[oldPosition].Split("/s+; f"); var newWords = result.NewItems[newPosition].Split("/s+; f"); var differ = new DifferenceBuilder(oldWords, newWords, false, false); if (differ.Build().If(out _)) { subItemBuilder(result.OldItems[oldPosition], result.NewItems[newPosition], oldItem.SubItems, newItem.SubItems); newItem.Type = DifferenceType.Modified; oldItem.Type = DifferenceType.Modified; } } oldItems.Add(oldItem); newItems.Add(newItem); oldPosition++; newPosition++; i++; } if (diffBlock.OldDeleteCount > diffBlock.NewInsertCount) { while (i < diffBlock.OldDeleteCount) { oldItems.Add(new DifferenceItem(result.OldItems[i + diffBlock.OldDeleteStart], DifferenceType.Deleted, oldPosition + 1)); newItems.Add(new DifferenceItem()); oldPosition++; i++; } } else { while (i < diffBlock.NewInsertCount) { newItems.Add(new DifferenceItem(result.NewItems[i + diffBlock.NewInsertStart], DifferenceType.Inserted, newPosition + 1)); oldItems.Add(new DifferenceItem()); newPosition++; i++; } } } while (newPosition < result.NewItems.Length && oldPosition < result.OldItems.Length) { oldItems.Add(new DifferenceItem(result.OldItems[oldPosition], DifferenceType.Unchanged, oldPosition + 1)); newItems.Add(new DifferenceItem(result.NewItems[newPosition], DifferenceType.Unchanged, newPosition + 1)); oldPosition++; newPosition++; } }
public void Maybe_WithValue_ReturnsValue() { var maybe = new Maybe <string>("Test"); Assert.AreEqual("Test", maybe.Value); }
public async Task <IActionResult> GetById(Guid userId) => await Maybe <GetUserByIdQuery> .From(new GetUserByIdQuery(userId)) .Bind(query => Mediator.Send(query)) .Match(Ok, NotFound);
private MutatingContext(Maybe <MutatingChange> change, TData data) { Change = change; Data = data; }
internal ServiceDiscoveryQuery(Maybe <ServiceReference> consumedService) { ConsumedService = consumedService; }
public static Maybe <MutatingContext <TData> > New(Maybe <TData> data) { return (from d in data select new MutatingContext <TData>(Maybe <MutatingChange> .Nothing, d)); }
public async Task <Orderbook> Orderbook(string market, string type) { try { var parameters = new Maybe <FormUrlEncodedContent>(new FormUrlEncodedContent( new Dictionary <string, string>() { { "market", market }, { "type", type } } )); var result = await _downloader.Get("getorderbook", parameters); // Need to split cases. // If the type is not both, API return only an array. if (type.Equals("both")) { return(JsonConvert.DeserializeObject <Orderbook>(result, _jsonSettings)); } if (type.Equals("buy")) { // Set up var orderbook = new Orderbook(); orderbook.Result = new Book(); // Deserialize var response = JsonConvert.DeserializeObject <GenericResponse <IList <Book.Tick> > >(result, _jsonSettings); // Craft object orderbook.Message = response.Message; orderbook.Success = response.Success; orderbook.Result.buy = response.Result; orderbook.Result.sell = new List <Book.Tick>(); return(orderbook); } if (type.Equals("sell")) { // Set up var orderbook = new Orderbook(); orderbook.Result = new Book(); // Deserialize var response = JsonConvert.DeserializeObject <GenericResponse <IList <Book.Tick> > >(result, _jsonSettings); // Craft object orderbook.Message = response.Message; orderbook.Success = response.Success; orderbook.Result.buy = new List <Book.Tick>(); orderbook.Result.sell = response.Result; return(orderbook); } return(null); } catch (Exception e) { throw e; } }
public static Maybe <R> ApplyInTermsOfBind <T, R>(this Maybe <Func <T, R> > func, Maybe <T> arg) => arg.Bind(t => func.Bind <Func <T, R>, R>(f => f(t)));