public static void CopyTo_FilledHashTable_ReturnsSuccessful() { var studentsMarks = new ChainedHashTable <string, int>(); studentsMarks.Add("Name1", 1); studentsMarks.Add("Name2", 5); studentsMarks.Add(new KeyValuePair <string, int>("Name3", 3)); var array = new KeyValuePair <string, int> [studentsMarks.Count]; studentsMarks.CopyTo(array, 0); Assert.True(studentsMarks.Count == 3); Assert.True(array.Length == 3); var arrayKeys = array.Select(x => x.Key).OrderBy(x => x).ToArray(); Assert.Equal("Name1", arrayKeys[0]); Assert.Equal("Name2", arrayKeys[1]); Assert.Equal("Name3", arrayKeys[2]); var arrayValues = array.Select(x => x.Value).OrderBy(x => x).ToArray(); Assert.Equal(1, arrayValues[0]); Assert.Equal(3, arrayValues[1]); Assert.Equal(5, arrayValues[2]); }
public void CopyTo() { var copy = new KeyValuePair <string, string> [5]; _pList.CopyTo(copy, 0); Assert.All(copy.Select(c => c.Key), s => Assert.Contains(s, new [] { "prop1", "prop2", "prop3", "prop4", "prop5" })); Assert.All(copy.Select(c => c.Value), s => Assert.Contains(s, new[] { "value1", "value2", "value3", "value4", "value5" })); }
private static void CompileJumpTarget(KeyValuePair<int, ProxyRule>[] rules, ProxyRule rule) { if (rule.Action == MatchAction.GotoName) { rule.Action = MatchAction.Goto; rule._jumpTarget = ((rules.Select((e, i) => new { Index = i, Item = e }).FirstOrDefault(x => x.Item.Value.Name == rule.ActionString)?.Index) ?? rules.Length - 1); } else if (rule.Action == MatchAction.Goto) { int number; if (!int.TryParse(rule.ActionString, out number)) number = int.MaxValue; rule._jumpTarget = rules.Select((e, i) => new { Index = i, Item = e }).First(x => x.Item.Key >= number).Index; } }
public IInterpolator1D[] Regress(IAssetFxModel model) { if (_regressors != null) { return(_regressors); } var o = new IInterpolator1D[_dateIndexes.Length]; var nPaths = _pathwiseValues.First().Length; var finalSchedules = _portfolio.Select(x => x.ExpectedFlowsByPath(model)).ToArray(); ParallelUtils.Instance.For(0, _dateIndexes.Length, 1, d => { var exposureDate = _regressionDates[d]; var sortedFinalValues = new KeyValuePair <double, double> [nPaths]; for (var p = 0; p < nPaths; p++) { var finalValue = 0.0; foreach (var schedule in finalSchedules) { foreach (var flow in schedule[p].Flows) { if (flow.SettleDate > exposureDate) { finalValue += flow.Pv; } } } sortedFinalValues[p] = new KeyValuePair <double, double>(_pathwiseValues[d][p], finalValue); } sortedFinalValues = sortedFinalValues.OrderBy(q => q.Key).ToArray(); if (_requireContinuity) { o[d] = SegmentedLinearRegression.Regress(sortedFinalValues.Select(x => x.Key).ToArray(), sortedFinalValues.Select(y => y.Value).ToArray(), 5); } else { o[d] = SegmentedLinearRegression.RegressNotContinuous(sortedFinalValues.Select(x => x.Key).ToArray(), sortedFinalValues.Select(y => y.Value).ToArray(), 5); } if (DebugMode) { DumpDataToDisk(sortedFinalValues, o[d], $@"C:\temp\regData{d}.csv"); } }).Wait(); _regressors = o; return(o); }
private string CreateCodeFlowUrl(string state, string nonce) { var model = DefaultClientConfiguration.CurrentOAuthConfig; var requestParams = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("response_type", "code"), new KeyValuePair <string, string>("client_id", model.ClientId), new KeyValuePair <string, string>("scope", model.Scopes), new KeyValuePair <string, string>("redirect_uri", model.CallbackUrl), new KeyValuePair <string, string>("state", state), new KeyValuePair <string, string>("nonce", nonce), new KeyValuePair <string, string>("login_hint", "tenant:" + model.Tenant), }; string queryString = string.Join("&", requestParams.Select(p => string.Format("{0}={1}", Uri.EscapeDataString(p.Key), Uri.EscapeDataString(p.Value ?? string.Empty))).ToArray()); return(string.Format("{0}?{1}", EndpointPaths.GetAuthorizeEndpointUri(model), queryString));/* + "?response_type=code&client_id=" + model.ClientId + "&scope=" + model.Scopes.Replace(" ", "+") + "&redirect_uri=" + encode(model.CallbackUrl) + "&state=" + state + "&nonce=" + nonce + "&login_hint=" + encode("tenant:" + model.Tenant);*/ }
protected void FetchRangeCommand(int startIndex, int pageCount, bool isPriority) { Task.Run(() => { var sortedAndFilteredList = SortAndFilterHttpResponcesList(); int realPageCount; if (sortedAndFilteredList.Count > 0 && sortedAndFilteredList.Count > startIndex + pageCount) { realPageCount = pageCount; } else { realPageCount = sortedAndFilteredList.Count - startIndex; } var array = new KeyValuePair <long, HttpResponce> [realPageCount]; sortedAndFilteredList.CopyTo(startIndex, array, 0, realPageCount); var requestedList = array.Select(l => l.Value).ToList(); var result = new RequestedData <HttpResponce>(startIndex, realPageCount, requestedList, sortedAndFilteredList.Count, isPriority); if (ListUpdates != null) { ListUpdates(new List <ServerListChanging <HttpResponce> > { result }); } }); }
public void CreateAggregateUnsafe() { var aggregationManager = new MetricAggregationManager(); var seriesConfig = new MetricSeriesConfigurationForMeasurement(restrictToUInt32Values: true); IEnumerable <KeyValuePair <string, string> > setDimensionNamesValues = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("Dim 1", "DV1"), new KeyValuePair <string, string>("Dim 2", "DV2"), new KeyValuePair <string, string>("Dim 3", "DV3"), new KeyValuePair <string, string>("Dim 2", "DV2a") }; IEnumerable <KeyValuePair <string, string> > expectedDimensionNamesValues = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("Dim 1", "DV1"), new KeyValuePair <string, string>("Dim 2", "DV2a"), new KeyValuePair <string, string>("Dim 3", "DV3") }; var metric = new MetricSeries( aggregationManager, new MetricIdentifier(String.Empty, "Cows Sold", expectedDimensionNamesValues.Select(nv => nv.Key).ToArray()), setDimensionNamesValues, seriesConfig); var aggregator = new MeasurementAggregator( (MetricSeriesConfigurationForMeasurement)metric.GetConfiguration(), metric, CycleKind.Custom); CommonSimpleDataSeriesAggregatorTests.CreateAggregateUnsafe(aggregator, metric, expectedDimensionNamesValues); }
public IServiceResult PackageSolution(string solutionPath, string buildConfiguration, KeyValuePair<string, string>[] buildProperties) { if (string.IsNullOrWhiteSpace(solutionPath)) { return new FailureResult(Resources.SolutionPackagingService.ErrorSolutionPathParameterCannotBeEmpty); } if (string.IsNullOrWhiteSpace(buildConfiguration)) { return new FailureResult(Resources.SolutionPackagingService.ErrorBuildConfigurationParameterCannotBeEmpty); } if (buildProperties == null) { return new FailureResult(Resources.SolutionPackagingService.ErrorBuildPropertiesParameterCannotBeNull); } // Build the solution IServiceResult buildResult = this.solutionBuilder.Build(solutionPath, buildConfiguration, buildProperties); if (buildResult.Status == ServiceResultType.Failure) { return new FailureResult( Resources.SolutionPackagingService.BuildFailedMessageTemplate, solutionPath, buildConfiguration, string.Join(",", buildProperties.Select(p => p.Key + "=" + p.Value))) { InnerResult = buildResult }; } // pre-packaging IServiceResult prepackagingResult = this.prepackagingService.Prepackage(this.buildFolder); if (prepackagingResult.Status == ServiceResultType.Failure) { return new FailureResult(Resources.SolutionPackagingService.PrepackagingFailedMessageTemplate, solutionPath) { InnerResult = prepackagingResult }; } // packaging IServiceResult packageResult = this.packagingService.Package(); if (packageResult.Status == ServiceResultType.Failure) { return new FailureResult(Resources.SolutionPackagingService.PackagingFailedMessageTemplate, solutionPath) { InnerResult = packageResult }; } string packagePath = packageResult.ResultArtefact; return new SuccessResult( Resources.SolutionPackagingService.PackagingSucceededMessageTemplate, solutionPath, buildConfiguration, string.Join(",", buildProperties.Select(p => p.Key + "=" + p.Value)), packagePath) { ResultArtefact = packagePath }; }
public void KeyCollection(JaggedDictionary<int, string> sut, KeyValuePair<JaggedIndex4<int>, string>[] values) { foreach (var kvp in values) sut[kvp.Key] = kvp.Value; var debugView = new JaggedDictionaryKeyCollectionDebugView<int, string>(sut.Keys); var items = debugView.Items; Assert.Equal(values.Select(kvp => kvp.Key).Distinct().Count(), items.Length); }
public void MultiValueDictionaryCopyToTest() { MultiValueDictionary <Int32, String> dictionary = new MultiValueDictionary <Int32, String>(); foreach (KeyValuePair <Int32, List <String> > item in _items) { dictionary.Add(item.Key, item.Value); } KeyValuePair <Int32, ICollection <String> >[] actual = new KeyValuePair <Int32, ICollection <String> > [10]; (dictionary as ICollection <KeyValuePair <Int32, ICollection <String> > >).CopyTo(actual, 0); IEnumerable <KeyValuePair <Int32, ICollection <String> > > expected = _items.Select(value => new KeyValuePair <Int32, ICollection <String> >(value.Key, value.Value as ICollection <String>)); Assert.AreEqual(expected.Select(v => v.Key), actual.Select(v => v.Key)); Assert.AreEqual(expected.Select(v => v.Value), actual.Select(v => v.Value)); }
/// <inheritdoc /> public IEnumerator <KeyValuePair <TForward, TReverse> > GetEnumerator() { using var _ = _rwLock.UseReadLock(); var array = new KeyValuePair <TForward, TReverse> [_internal.Count]; _internal.CopyTo(array, 0); return(array.Select(t => t).GetEnumerator()); }
public NormalizedGraphSearchTest() { store = new Store(@"..\..\..\Databases\int based\"); store.ClearAll(); //Performance.ComputeTime(() => store.ReloadFrom(Config.Source_data_folder_path + "10M.ttl"), "load 10 млн ", true); store.ReloadFrom(@"C:\deployed\triples.ttl"); store.NodeGenerator.TryGetUri(new OV_iri("http://fogid.net/o/collection-item"), out collectionItempredicate); var triplesCount = store.GetTriplesCount(); store.NodeGenerator.TryGetUri(new OV_iri("http://fogid.net/o/in-collection"), out inCollectionPredicate); edges = (from triple in store.GetTriplesWithPredicate(collectionItempredicate) from item in store.GetTriplesWithSubjectPredicate(triple.Subject, inCollectionPredicate) select new KeyValuePair<int, int>((int)item.WritableValue, (int)triple.Object.WritableValue)).ToArray(); vertexes = edges.Select(pair => pair.Key).Concat(edges.Select(pair => pair.Value)).Distinct(); normalizedGraph4Search = new NormalizedGraph4Search(@"..\..\..\Databases\int based\tree\"); normalizedGraph4Search.ReCreate(edges); var allSubTree = normalizedGraph4Search.GetAllSubTree(edges[0].Key); }
/// <summary> /// Performs unit test on the dictionary contract. /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dictionary">The dictionary object.</param> /// <param name="keyAllocator">A function which returns a new key each time it is called. The key should not be equal /// to any previous value it returned.</param> /// <param name="valueAllocator">A function which returns a new value each time it is called. This value should not be equal /// to any previous value it returned.</param> /// <param name="equalityComparison">Function which compares values for equality.</param> public static void DictionaryContract <TKey, TValue>(IDictionary <TKey, TValue> dictionary, Func <TKey> keyAllocator, Func <TValue> valueAllocator, Func <TValue, TValue, bool> equalityComparison = null) { equalityComparison = equalityComparison ?? ((value1, value2) => ReferenceEquals(value1, value2)); dictionary.Clear(); Assert.AreEqual(0, dictionary.Count, "Clear method did not remove all items."); var firstKey = keyAllocator(); dictionary.Add(firstKey, valueAllocator()); Assert.AreEqual(1, dictionary.Count, "Add method did not add an item."); var v1 = valueAllocator(); var v2 = valueAllocator(); Assert.IsFalse(equalityComparison(v1, v2)); var k1 = keyAllocator(); var k2 = keyAllocator(); dictionary[k1] = v1; dictionary[k2] = v2; Assert.IsTrue(equalityComparison(v1, dictionary[k1]), "Item added to dictionary was not equal to value received."); Assert.AreEqual(3, dictionary.Count, "Count mismatch."); dictionary.Remove(k1); Assert.IsTrue(dictionary.ContainsKey(firstKey), "First key was accidentally removed."); Assert.IsFalse(dictionary.ContainsKey(k1), "Remove did not remove the item."); Assert.IsTrue(dictionary.ContainsKey(k2), "Last key was accidentally removed."); TValue testValue; var success = dictionary.TryGetValue(k2, out testValue); Assert.IsTrue(success, "TryGetValue failed to get a value known to be in the dictionary."); Assert.IsTrue(equalityComparison(testValue, v2), "Value retrieved from TryGetValue did not match value entered."); var k3 = keyAllocator(); var v3 = valueAllocator(); dictionary.Add(new KeyValuePair <TKey, TValue>(k3, v3)); Assert.IsTrue(equalityComparison(v3, dictionary[k3])); Assert.IsTrue(dictionary.Contains(new KeyValuePair <TKey, TValue>(k3, v3))); var array = new KeyValuePair <TKey, TValue> [dictionary.Count]; dictionary.CopyTo(array, 0); CollectionAssert.AreEquivalent(dictionary.Keys.ToArray(), array.Select(x => x.Key).ToArray()); }
public void CopyTo_ValidIndex_CopiesKeysInCorrectOrder() { var linkedDictionary = InitializeDictionarySequentialKeys(10); KeyValuePair <int, int>[] targetArray = new KeyValuePair <int, int> [11]; linkedDictionary.CopyTo(targetArray, 1); var expectedKeys = new List <int>() { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Assert.Equal <int>(expectedKeys, targetArray.Select(x => x.Key)); }
public async Task TestGetAllEntitiesReadsConsistentState() { using (var firstGet = await store.GetForUse(1, true)) firstGet.Item = new TestItem("a"); using (var secondGet = await store.GetForUse(2, true)) secondGet.Item = new TestItem("b"); using (await store.GetForUse(3, true)) { // keep this item null. // we'll be testing that this isn't returned later. } KeyValuePair <long, TestItem>[] items = new KeyValuePair <long, TestItem> [0]; ManualResetEventSlim backgroundRetrievalStarted = new ManualResetEventSlim(); ManualResetEventSlim backgroundRetrievalDone = new ManualResetEventSlim(); Thread backgroundRetrievalThread = new Thread(() => { backgroundRetrievalStarted.Set(); items = store.GetAllEntities(); backgroundRetrievalDone.Set(); }); using (var fourthGet = await store.GetForUse(4, true)) { // ensure the item is set to non-null before allowing retrieval to happen. fourthGet.Item = new TestItem("c"); // start background retrieval while this get is holding the lock. backgroundRetrievalThread.Start(); backgroundRetrievalStarted.Wait(1000); } Assert.True(backgroundRetrievalDone.Wait(1000)); Assert.NotNull(items); Assert.Equal(3, items.Length); Assert.DoesNotContain(3, items.Select(item => item.Key)); Assert.All(items, item => Assert.NotNull(item.Value)); }
public async Task <string> GetClientToken([Query(Value = "customer_id")] string customerId, [Query(Value = "merchant_account_id")] string merchantAccountId) { var content = new KeyValuePair <string, string>[] { new KeyValuePair <string, string> ("customer_id", customerId), new KeyValuePair <string, string> ("merchant_account_id", merchantAccountId) }; var response = await client.GetAsync("/client_token?" + string.Join("&", content.Select(x => $"{x.Key}={x.Value}"))); if (response.IsSuccessStatusCode) { var data = JsonConvert.DeserializeObject <ClientToken>(await response.Content.ReadAsStringAsync()); return(data.Token); } else { throw new Exception("Unable to get token."); } }
public static void RunCmdlet(this PSCmdlet cmdlet, string parameterSet, KeyValuePair<string, object[]>[] incomingValues) { var cmdletType = cmdlet.GetType(); parameterSetFieldInfo.SetValue(cmdlet, parameterSet); beginProcessingMethodInfo.Invoke(cmdlet, emptyParameters); var parameterProperties = incomingValues.Select(x => new Tuple<PropertyInfo, object[]>( cmdletType.GetProperty(x.Key), x.Value)).ToArray(); for (int i = 0; i < incomingValues[0].Value.Length; i++) { foreach (var parameter in parameterProperties) { parameter.Item1.SetValue(cmdlet, parameter.Item2[i], null); } processRecordMethodInfo.Invoke(cmdlet, emptyParameters); } endProcessingMethodInfo.Invoke(cmdlet, emptyParameters); }
public void ShouldPutMultiple() { _db = _txn.OpenDatabase(configuration: new DatabaseConfiguration { Flags = DatabaseOpenFlags.DuplicatesFixed | DatabaseOpenFlags.Create }); var values = new[] { 1, 2, 3, 4, 5 }.Select(BitConverter.GetBytes).ToArray(); using (var cur = _txn.CreateCursor(_db)) cur.PutMultiple(UTF8.GetBytes("TestKey"), values); var pairs = new KeyValuePair <byte[], byte[]> [values.Length]; using (var cur = _txn.CreateCursor(_db)) { for (var i = 0; i < values.Length; i++) { cur.MoveNextDuplicate(); pairs[i] = cur.Current; } } Assert.Equal(values, pairs.Select(x => x.Value).ToArray()); }
public void ShouldPutMultiple() { _db = _txn.OpenDatabase(configuration: new DatabaseConfiguration { Flags = DatabaseOpenFlags.DuplicatesFixed | DatabaseOpenFlags.Create }); var values = new[] { 1, 2, 3, 4, 5 }.Select(BitConverter.GetBytes).ToArray(); using (var cur = _txn.CreateCursor(_db)) cur.PutMultiple(UTF8.GetBytes("TestKey"), values); var pairs = new KeyValuePair<byte[], byte[]>[values.Length]; using (var cur = _txn.CreateCursor(_db)) { for (var i = 0; i < values.Length; i++) { cur.MoveNextDuplicate(); pairs[i] = cur.Current; } } Assert.Equal(values, pairs.Select(x => x.Value).ToArray()); }
public static void Message_Tranfer_Arbol_Union(MarkovNet arboldeunion, KeyValuePair<BayesianNode, int>[] evidence = null) { //absorber evidence if (evidence != null && evidence.Length > 0) { arboldeunion.BayesianNet.Evidence = evidence.Select(x => x.Value).ToArray(); } if (arboldeunion.Count() > ParalellStartNumber) { #region ParalellAlgorithm arboldeunion.Debug = true; var taskarr = new Task[arboldeunion.Count]; for (int i = 0; i < arboldeunion.Count; i++) { taskarr[i] = new Task(o => { var node = o as BayesianNode; if (node != null) lock (node) { do { arboldeunion.Work(node); } while (!node.Finished); } }, arboldeunion[i]); taskarr[i].Start(); } for (int i = 0; i < arboldeunion.Count*8; i++) { System.Threading.Thread.Sleep(300); Increment(); } Task.WaitAll(taskarr); arboldeunion.Debug = false; #endregion } else #region DeterministicAlgorithm while (!arboldeunion.AllConditionalProbabilitiesComputed()) { foreach (var item in arboldeunion) { arboldeunion.Work(item); } Increment(); } #endregion foreach (var node in arboldeunion.BayesianNet) arboldeunion.Marginalize_X(node); }
public Scatter(KeyValuePair<double, double>[] Points) { points = Points.Select(i => new PointF((float)i.Key, ToFloat(i.Value))).ToArray(); }
public void CopyTo_should_copy_values() { var dict = CreateTwoItemDictionary(); var copy = new KeyValuePair<int, string>[2]; dict.CopyTo(copy, 0); Assert.That(copy.Select(v => v.Value).ToArray(), Is.EquivalentTo(new[] { "35A", "35B"})); }
public void StreamPropertyNoMetadataAtomTest() { IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[] { #region only href // read link with only href. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null), }, // edit-link with only href. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null), }, // read link with only href. - two links - case sensitive difference. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null) .StreamProperty("StreampRoperty", "http://odata.org/readlink2", null, null, null), }, // edit-link with only href. - two links - case sensitive difference. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null) .StreamProperty("sTreamProperty", null, "http://odata.org/editlink2", null, null), }, #endregion #region missing content type // read link with missing content type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null), }, // edit-link with missing content type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null), }, // edit-link with content type in different namespace. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null) .XmlRepresentation(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' foo:type='application/atom+xml' /> </entry>"), }, #endregion #region content type on both // both read and edit link with the same content type, read link first new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", "http://odata.org/editlink", "mime/type") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' type='mime/type'/> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' type='mime/type'/> </entry>"), }, // both read and edit link with the same content type, edit link first new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", "http://odata.org/editlink", "mime/type") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' type='mime/type'/> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' type='mime/type'/> </entry>"), }, #endregion #region etag // verify that read link discards etag. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null) .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' m:etag='someetag'/> </entry>"), }, #endregion etag #region all possible valid attributes // edit-link with href, content type and etag. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", "some_etag"), }, // read link with href and content type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, "application/atom+xml", null), }, #endregion #region extra attributes // extra attributes in the read link. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' foo1='bar1' href='http://odata.org/readlink' foo='bar'/> </entry>"), }, // extra attributes in the edit-link. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' foo1='bar1' href='http://odata.org/editlink' foo='bar'/> </entry>"), }, #endregion #region missing rel // missing rel new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link href='http://odata.org/editlink' type='application/atom+xml'/> </entry>"), }, // rel attribute in different namespace new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'> <link href='http://odata.org/editlink' type='application/atom+xml' foo:rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'/> </entry>"), }, #endregion missing rel #region name prefix // verify that invalid stream name prefix is discarded. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/data/somename/StreamProperty' href='http://odata.org/readlink' /> </entry>"), }, // verify that stream name prefix is case-sensitive. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/Mediaresource/StreamProperty' href='http://odata.org/readlink' type='application/atom+xml'/> </entry>"), }, // verify that incomplete rel is not recognized as stream property (missing the last slash in read link) new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource' href='http://odata.org/readlink' /> </entry>"), }, // verify that incomplete rel is not recognized as stream property (missing the last slash in edit link) new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/edit-media' href='http://odata.org/editlink' /> </entry>"), }, #endregion #region order of the attributes and link // edit link first. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty1", null, "http://odata.org/editlink", null, null) .StreamProperty("StreamProperty2", "http://odata.org/readlink", null, null, null), }, // read link first. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty1", "http://odata.org/readlink", null, null, null) .StreamProperty("StreamProperty2", null, "http://odata.org/editlink", null, null), }, // rel after etag, href and type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", "some_etag") .XmlRepresentation(@"<entry> <link m:etag='some_etag' href='http://odata.org/editlink' type='application/atom+xml' rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'/> </entry>"), }, #endregion order of the attributes and link #region content inside link element // verify that all contents inside link element are skipped. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", null) .XmlRepresentation(@"<entry> <link href='http://odata.org/editlink' type='application/atom+xml' rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'> <m:unknown>some text</m:unknown> <!-- Some comments --> <d:unknown/> <ns:someelement xmlns:ns='somenamespace'/> <![CDATA[cdata]]> </link> </entry>"), }, #endregion content inside link element }; #region empty or missing etag KeyValuePair <string, string>[] etags = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(string.Empty, "m:etag=''"), // empty etag new KeyValuePair <string, string>("some_etag", "m:etag='some_etag'"), // valid etag new KeyValuePair <string, string>(null, "foo:etag='some_etag'"), // etag in a different namespace }; testDescriptors = testDescriptors.Concat(etags.Select(etag => new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, etag.Key) .XmlRepresentation(string.Format(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' {0} /> </entry>", etag.Value)), })); #endregion empty or missing etag // WCF DS client, server and default ODataLib show the same behavior for stream properties. this.CombinatorialEngineProvider.RunCombinations( TestReaderUtils.ODataBehaviorKinds, testDescriptors, this.ReaderTestConfigurationProvider.AtomFormatConfigurations, (behaviorKind, testDescriptor, testConfiguration) => { if (testConfiguration.IsRequest) { testDescriptor = new PayloadReaderTestDescriptor(testDescriptor) { ExpectedException = null, ExpectedResultPayloadElement = tc => RemoveStreamPropertyPayloadElementNormalizer.Normalize(testDescriptor.PayloadElement.DeepCopy()) }; } testDescriptor.RunTest(testConfiguration.CloneAndApplyBehavior(behaviorKind)); }); }
public void StreamPropertyNoMetadataAtomTest() { IEnumerable<PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[] { #region only href // read link with only href. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null), }, // edit-link with only href. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null), }, // read link with only href. - two links - case sensitive difference. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null) .StreamProperty("StreampRoperty", "http://odata.org/readlink2", null, null, null), }, // edit-link with only href. - two links - case sensitive difference. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null) .StreamProperty("sTreamProperty", null, "http://odata.org/editlink2", null, null), }, #endregion #region missing content type // read link with missing content type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null), }, // edit-link with missing content type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null), }, // edit-link with content type in different namespace. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null) .XmlRepresentation(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' foo:type='application/atom+xml' /> </entry>"), }, #endregion #region content type on both // both read and edit link with the same content type, read link first new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", "http://odata.org/editlink", "mime/type") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' type='mime/type'/> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' type='mime/type'/> </entry>"), }, // both read and edit link with the same content type, edit link first new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", "http://odata.org/editlink", "mime/type") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' type='mime/type'/> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' type='mime/type'/> </entry>"), }, #endregion #region etag // verify that read link discards etag. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null) .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' m:etag='someetag'/> </entry>"), }, #endregion etag #region all possible valid attributes // edit-link with href, content type and etag. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", "some_etag"), }, // read link with href and content type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, "application/atom+xml", null), }, #endregion #region extra attributes // extra attributes in the read link. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' foo1='bar1' href='http://odata.org/readlink' foo='bar'/> </entry>"), }, // extra attributes in the edit-link. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty",null, "http://odata.org/editlink") .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' foo1='bar1' href='http://odata.org/editlink' foo='bar'/> </entry>"), }, #endregion #region missing rel // missing rel new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link href='http://odata.org/editlink' type='application/atom+xml'/> </entry>"), }, // rel attribute in different namespace new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'> <link href='http://odata.org/editlink' type='application/atom+xml' foo:rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'/> </entry>"), }, #endregion missing rel #region name prefix // verify that invalid stream name prefix is discarded. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/data/somename/StreamProperty' href='http://odata.org/readlink' /> </entry>"), }, // verify that stream name prefix is case-sensitive. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/Mediaresource/StreamProperty' href='http://odata.org/readlink' type='application/atom+xml'/> </entry>"), }, // verify that incomplete rel is not recognized as stream property (missing the last slash in read link) new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/mediaresource' href='http://odata.org/readlink' /> </entry>"), }, // verify that incomplete rel is not recognized as stream property (missing the last slash in edit link) new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .XmlRepresentation(@"<entry> <link rel='http://docs.oasis-open.org/odata/ns/edit-media' href='http://odata.org/editlink' /> </entry>"), }, #endregion #region order of the attributes and link // edit link first. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty1", null, "http://odata.org/editlink", null, null) .StreamProperty("StreamProperty2", "http://odata.org/readlink", null, null, null), }, // read link first. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty1", "http://odata.org/readlink", null, null, null) .StreamProperty("StreamProperty2", null, "http://odata.org/editlink", null, null), }, // rel after etag, href and type. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", "some_etag") .XmlRepresentation(@"<entry> <link m:etag='some_etag' href='http://odata.org/editlink' type='application/atom+xml' rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'/> </entry>"), }, #endregion order of the attributes and link #region content inside link element // verify that all contents inside link element are skipped. new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity() .StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", null) .XmlRepresentation(@"<entry> <link href='http://odata.org/editlink' type='application/atom+xml' rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'> <m:unknown>some text</m:unknown> <!-- Some comments --> <d:unknown/> <ns:someelement xmlns:ns='somenamespace'/> <![CDATA[cdata]]> </link> </entry>"), }, #endregion content inside link element }; #region empty or missing etag KeyValuePair<string, string>[] etags = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>(string.Empty, "m:etag=''"), // empty etag new KeyValuePair<string, string>("some_etag", "m:etag='some_etag'"), // valid etag new KeyValuePair<string, string>(null, "foo:etag='some_etag'"), // etag in a different namespace }; testDescriptors = testDescriptors.Concat(etags.Select(etag => new PayloadReaderTestDescriptor(this.Settings) { PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, etag.Key) .XmlRepresentation(string.Format(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'> <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' {0} /> </entry>", etag.Value)), })); #endregion empty or missing etag // WCF DS client, server and default ODataLib show the same behavior for stream properties. this.CombinatorialEngineProvider.RunCombinations( TestReaderUtils.ODataBehaviorKinds, testDescriptors, this.ReaderTestConfigurationProvider.AtomFormatConfigurations, (behaviorKind, testDescriptor, testConfiguration) => { if (testConfiguration.IsRequest) { testDescriptor = new PayloadReaderTestDescriptor(testDescriptor) { ExpectedException = null, ExpectedResultPayloadElement = tc => RemoveStreamPropertyPayloadElementNormalizer.Normalize(testDescriptor.PayloadElement.DeepCopy()) }; } testDescriptor.RunTest(testConfiguration.CloneAndApplyBehavior(behaviorKind)); }); }
private static void Vote(string host, KeyValuePair<User, int[]>[] voters, Guid id, PublicKey publicKey) { log.Info("Voting in parallel..."); var candidateTasks = voters.Select(kvp => ElectroClient.VoteAsync(host, Program.PORT, kvp.Key.Cookies, id, HomoCrypto.EncryptVector(kvp.Value, publicKey))).ToArray(); try { Task.WaitAll(); log.InfoFormat("Voted by {0} users", voters.Length); } catch(Exception e) { throw new ServiceException(ExitCode.DOWN, string.Format("Failed to vote by {0} users in parallel: {1}", candidateTasks.Length, e)); } }
public void RedisStorageStoresAndRemovesObjectsInBulks() { KeyValuePair<string, string>[] objectsToStore = new KeyValuePair<string, string>[100]; for (int i = 0; i < objectsToStore.Length; i++) { objectsToStore[i] = new KeyValuePair<string, string>(Guid.NewGuid().ToString(), "jack checked chicken"); } using (var storage = new RedisStorage(RedisStorageTests.Host)) { storage.BulkStore(objectsToStore); storage.BulkRemove(objectsToStore.Select(o => o.Key).ToArray()); foreach (var @object in objectsToStore) { Assert.That(() => storage.Retrieve<string>(@object.Key), Throws.InstanceOf<ArgumentOutOfRangeException>()); } } }
private static string InsertStatement(string tableName, KeyValuePair<string, string>[] keysAndValues) { return string.Format("{0} ({1}) VALUES ({2}); ", tableName, string.Join<string>(", ", keysAndValues.Select(x => x.Key)), string.Join<string>(", ", keysAndValues.Select(x => x.Value))); }
public override async Task ExcuteFunc(CancellationToken cancellationToken) { var stringKey = "stringKey"; var isDelete = this._cache.KeyDelete(stringKey); // 1. 新增一筆String, 回傳是否成功失敗 var isSet = this._cache.StringSet(stringKey, $"hello {stringKey}"); // 2. 取的一筆String, 回傳String結果(hello stringKey) var stringResult = this._cache.StringGet(stringKey); // 3. 回傳String長度 var stringLength1 = this._cache.StringLength(stringKey); var stringLength2 = await this._cache.StringLengthAsync(stringKey); // 4. 在原本Key(hello stringKey), append string(hello stringKey append), 回傳append後的長度 var appendCount = this._cache.StringAppend(stringKey, " append"); var setList = new KeyValuePair <RedisKey, RedisValue>[] { new KeyValuePair <RedisKey, RedisValue> ($"{stringKey}List1", $"{stringKey}List1"), new KeyValuePair <RedisKey, RedisValue> ($"{stringKey}List2", $"{stringKey}List2"), new KeyValuePair <RedisKey, RedisValue> ($"{stringKey}List3", $"{stringKey}List3"), }; this._cache.KeyDelete(setList.Select(x => x.Key).ToArray()); // 5. 新增多筆String, 回傳是否成功失敗(true/false) var isSetList = this._cache.StringSet(setList); this._cache.KeyDelete($"{stringKey}2"); this._cache.StringSet($"{stringKey}2", "test"); // 6. 先回傳取得原本key裡面value(test), 再將之後的值設定進去(hello stringKey) var result = this._cache.StringGetSet($"{stringKey}2", $"hello {stringKey}"); // 7. 取得key裡面value(hello stringKey), 開始跟結束的String (stringKey) var getRange = this._cache.StringGetRange($"{stringKey}2", 6, 14); this._cache.KeyDelete($"{stringKey}3"); this._cache.KeyDelete($"{stringKey}4"); this._cache.StringSet($"{stringKey}3", $"hello 1234"); this._cache.StringSet($"{stringKey}4", $"hello 123456"); // 8. 指定key(hello 1234)裡面 index 的更換成 value (hello test) => 回傳key字串長度 // 指定key(hello 123456)裡面 index 的更換成 value (hello test56) => 回傳key字串長度 var result3 = this._cache.StringSetRange($"{stringKey}3", 6, "test"); var result4 = this._cache.StringSetRange($"{stringKey}4", 6, "test"); this._cache.KeyDelete($"{stringKey}5"); this._cache.StringSet($"{stringKey}5", "a"); // 01100001 (97) var strbit1 = this._cache.StringGet($"{stringKey}5"); // 9. 取得 字串 位移的 Bit 值 var bitGetResult6 = this._cache.StringGetBit($"{stringKey}5", 6); // 0 var bitGetResult7 = this._cache.StringGetBit($"{stringKey}5", 7); // 1 // 10. 設定 字串 位移的 Bit 值, 先取得舊字串 位移的 Bit 值 var bitSetResult6 = this._cache.StringSetBit($"{stringKey}5", 6, true); // 01100011 var bitSetResult7 = this._cache.StringSetBit($"{stringKey}5", 7, false); // 01100010 var strbit2 = this._cache.StringGet($"{stringKey}5"); // 01100010 (98) "b" this._cache.KeyDelete($"{stringKey}6"); this._cache.StringSet($"{stringKey}6", "ac"); // 01100001 01100011 var strbit3 = this._cache.StringGet($"{stringKey}6"); // 11. 取得 key 裡面字串 Bit(1) 個數 var bitCount1 = this._cache.StringBitCount($"{stringKey}6", 0, -1); // 01100001 01100011 => 7 var bitCount2 = this._cache.StringBitCount($"{stringKey}6", 0, -2); // 01100001 => 3 var bitCount3 = this._cache.StringBitCount($"{stringKey}6", 1, -1); // 01100011 => 4 this._cache.KeyDelete($"{stringKey}7"); this._cache.StringSet($"{stringKey}7", "ac"); // 01100001 01100011 var strbit4 = this._cache.StringGet($"{stringKey}7"); // 12. 取得 key 裡面字串, 所選取字串第一個 Bit(1) Position var bitPosition1 = this._cache.StringBitPosition($"{stringKey}7", true, 0, -1); // 0"1"100001 01100011 => 1 var bitPosition2 = this._cache.StringBitPosition($"{stringKey}7", true, 1, 1); // 01100001 0"1"100011 => 9 this._cache.KeyDelete($"{stringKey}8"); this._cache.StringSet($"{stringKey}8", "a"); // 01100001 97 var strOperation1 = this._cache.StringGet($"{stringKey}8"); this._cache.KeyDelete($"{stringKey}9"); this._cache.StringSet($"{stringKey}9", "b"); // 01100010 98 var strOperation2 = this._cache.StringGet($"{stringKey}9"); this._cache.KeyDelete($"{stringKey}10"); this._cache.StringSet($"{stringKey}10", "c"); // 01100011 99 var strOperation3 = this._cache.StringGet($"{stringKey}10"); this._cache.KeyDelete($"{stringKey}11"); this._cache.StringSet($"{stringKey}11", "97"); // 00111001 57 00110111 55 var strOperation4 = this._cache.StringGet($"{stringKey}11"); // 13. 取得 key 裡面字串 Bit 邏輯判斷 var strOperationResult1 = this._cache.StringBitOperation(Bitwise.And, $"{stringKey}Operation1", $"{stringKey}8", $"{stringKey}9"); // 01100000 96 var strOperationResult2 = this._cache.StringBitOperation(Bitwise.And, $"{stringKey}Operation2", new RedisKey[] { $"{stringKey}8", $"{stringKey}9", $"{stringKey}10" }); // 01100000 96 var strOperationResult01 = this._cache.StringGet($"{stringKey}Operation1"); var strOperationResult02 = this._cache.StringGet($"{stringKey}Operation2"); var strOperationResult3 = this._cache.StringBitOperation(Bitwise.Or, $"{stringKey}Operation3", $"{stringKey}8", $"{stringKey}9"); // 01100011 99 var strOperationResult4 = this._cache.StringBitOperation(Bitwise.Or, $"{stringKey}Operation4", new RedisKey[] { $"{stringKey}8", $"{stringKey}9", $"{stringKey}10" }); // 01100011 99 var strOperationResult03 = this._cache.StringGet($"{stringKey}Operation3"); var strOperationResult04 = this._cache.StringGet($"{stringKey}Operation4"); var strOperationResult5 = this._cache.StringBitOperation(Bitwise.Xor, $"{stringKey}Operation5", $"{stringKey}8", $"{stringKey}9"); // 00000011 3 var strOperationResult6 = this._cache.StringBitOperation(Bitwise.Xor, $"{stringKey}Operation6", new RedisKey[] { $"{stringKey}8", $"{stringKey}9", $"{stringKey}10" }); //(8, 9) 00000011 3 => (x, 10) [00000011, 01100011] 01100000 96 var strOperationResult05 = this._cache.StringGet($"{stringKey}Operation5"); var strOperationResult06 = this._cache.StringGet($"{stringKey}Operation6"); // Not 只能轉換單一 var strOperationResult7 = this._cache.StringBitOperation(Bitwise.Not, $"{stringKey}Operation7", $"{stringKey}8", $"{stringKey}9"); // 10011110 158 var strOperationResult8 = this._cache.StringBitOperation(Bitwise.Not, $"{stringKey}Operation8", new RedisKey[] { $"{stringKey}9" }); // 10011101 157 var strOperationResult07 = this._cache.StringGet($"{stringKey}Operation7"); var strOperationResult08 = this._cache.StringGet($"{stringKey}Operation8"); var strOperationResult9 = this._cache.StringBitOperation(Bitwise.Not, $"{stringKey}Operation9", $"{stringKey}11"); // 11000110 198 11001000 200 var strOperationResult09 = this._cache.StringGet($"{stringKey}Operation9"); this._cache.KeyDelete($"{stringKey}Expire"); this._cache.StringSet($"{stringKey}Expire", $"{stringKey}Expire"); // 14. 設定Key Expire var isSetExpire = this._cache.KeyExpire($"{stringKey}Expire", TimeSpan.FromSeconds(15)); // 15. 取得Key Expire var strExpire = this._cache.StringGetWithExpiry($"{stringKey}Expire"); this._cache.KeyDelete($"{stringKey}Number1"); this._cache.KeyDelete($"{stringKey}Number2"); this._cache.KeyDelete($"{stringKey}Number3"); this._cache.StringSet($"{stringKey}Number3", "0"); var number1 = this._cache.StringIncrement($"{stringKey}Number1"); number1 = this._cache.StringDecrement($"{stringKey}Number1"); var number2 = this._cache.StringIncrement($"{stringKey}Number2", 2.20); // 會溢位 number2 = this._cache.StringDecrement($"{stringKey}Number2", 1.10); var number3 = this._cache.StringIncrement($"{stringKey}Number3", 2.2d); number3 = this._cache.StringDecrement($"{stringKey}Number3", 1.1d); // ================================================================================================== // 1. String Batch var bactch = this._cache.CreateBatch(); var data = Enumerable.Range(1, 10) .Select(x => new KeyValuePair <RedisKey, RedisValue>($"stringKeyBatch{x}", $"stringKeyBatch{x}")); var deleteTasks = bactch.KeyDeleteAsync(data.Select(x => x.Key).ToArray()); //bactch.Execute(); var setTasks = bactch.StringSetAsync(data.ToArray()); var expireTasks = data.Select(x => bactch.KeyExpireAsync(x.Key, TimeSpan.FromSeconds(10))).ToList(); bactch.Execute(); var deleteResults = await Task.WhenAll(deleteTasks); var setResult = await Task.WhenAll(setTasks); var expireResult = await Task.WhenAll(expireTasks); //return Task.CompletedTask; }
public static void GetSetTest(ListDictionary ld, KeyValuePair<string, string>[] data) { DictionaryEntry[] translated = data.Select(kv => new DictionaryEntry(kv.Key, kv.Value)).ToArray(); foreach (KeyValuePair<string, string> kv in data) { Assert.Equal(kv.Value, ld[kv.Key]); } for (int i = 0; i < data.Length / 2; i++) { object temp = ld[data[i].Key]; ld[data[i].Key] = ld[data[data.Length - i - 1].Key]; ld[data[data.Length - i - 1].Key] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1].Value, ld[data[i].Key]); } }
public void RedisStorageStoresAndRetrievesComplexObjectsInBulks() { var objectToStore = new ComplexParameter() { SomeProperty = "this is string", AnotherProperty = 47 }; KeyValuePair<string, ComplexParameter>[] objectsToStore = new KeyValuePair<string, ComplexParameter>[100]; for (int i = 0; i < objectsToStore.Length; i++) { objectsToStore[i] = new KeyValuePair<string, ComplexParameter>(Guid.NewGuid().ToString(), objectToStore); } using (var storage = new RedisStorage(RedisStorageTests.Host)) { storage.BulkStore(objectsToStore); var retrievedObjects = storage.BulkRetrieve<ComplexParameter>(objectsToStore.Select(o => o.Key).ToArray()); foreach (var retrievedObject in retrievedObjects) { retrievedObject.SomeProperty.ShouldBe(objectToStore.SomeProperty); retrievedObject.AnotherProperty.ShouldBe(objectToStore.AnotherProperty); } } }
private IEnumerator ProcessTwitchCommand(string command) { if (command == "animals") { yield return("sendtochat Acceptable animal names are:"); getAnimalListMsgs(); yield return(_animalListMsg1); yield return(_animalListMsg2); } // The door could still be open from a previous command where someone didn’t press enough animals. if (_state != State.DoorClosed) { yield break; } var m = Regex.Match(command, @"^press (.*)$"); if (!m.Success) { yield break; } var animals = m.Groups[1].Value.Split(',').Select(str => str.Trim()).ToArray(); var animalInfos = new KeyValuePair <Hex, string> [animals.Length]; for (int i = 0; i < animals.Length; i++) { animalInfos[i] = _inGrid.FirstOrDefault(kvp => kvp.Value.Equals(animals[i], StringComparison.InvariantCultureIgnoreCase)); if (animalInfos[i].Value == null) { yield return(string.Format("sendtochat What the hell is a {0}?! I only know about the following animals:", animals[i])); getAnimalListMsgs(); yield return(_animalListMsg1); yield return(_animalListMsg2); yield break; } } Debug.LogFormat("[Zoo #{0}] Received Twitch Plays command to press: {1}.", _moduleId, animalInfos.Select(i => i.Value).JoinString(", ")); yield return(null); Door.OnInteract(); yield return(new WaitForSeconds(1f)); for (int i = 0; i < animalInfos.Length; i++) { yield return(new WaitForSeconds(.1f)); var j = Array.IndexOf(_selection, animalInfos[i].Value); if (j == -1) { continue; } _pedestals[_selectionPedestalIxs[j]].OnInteract(); if (_state != State.DoorOpen) // strike or solve { yield break; } } // If you get here, you didn’t press enough animals. // The time will run out and the door will close after some time. yield return("strike"); }
public static Texture2D FromLabels(KeyValuePair<string, Color>[] labels, SpriteFont font, Size size, GraphicsDevice device) { RenderTarget2D target = new RenderTarget2D(device, size.Width, size.Height); SpriteBatch sb = new SpriteBatch(device); device.SetRenderTarget(target); device.Clear(Color.Transparent); sb.Begin(); for (int i = 0; i < labels.Length; i++) { string prevString = string.Join(" ", labels.Select(l => l.Key).ToArray(), 0, i); if (i > 0) prevString += " "; float x = 1 + font.MeasureString(prevString).X; sb.DrawString(font, labels[i].Key, new Vector2(x, 1), labels[i].Value, 0f, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f); } sb.End(); device.SetRenderTarget(null); Texture2D texture = new Texture2D(device, size.Width, size.Height); Color[] colorData = target.GetColorData(); texture.SetData(colorData); target.Dispose(); return texture; }
public void Test() { // Path.GetTempFileName will create a uniquely named, zero-byte temporary file // on disk and returns the full path of that file. File.Exists(temporaryIniFilePath_).Should().BeTrue(); new FileInfo(temporaryIniFilePath_).Length.Should().Be(0); ini_.GetSections().Should().BeEmpty(); ini_.GetKeys("bang").Should().BeEmpty(); var serverSection = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("IP", "127.0.0.1"), new KeyValuePair <string, string>("Port", "8080"), }; ini_.WriteSection("Server", serverSection); File.Exists(temporaryIniFilePath_).Should().BeTrue(); new FileInfo(temporaryIniFilePath_).Length.Should().NotBe(0); var sections = ini_.GetSections(); sections.Length.Should().Be(1); sections.Should().Equal("Server"); ini_.HasSection("Server").Should().BeTrue(); ini_.HasSection("server").Should().BeTrue(); ini_.ReadSection("serVer").Should().Equal(serverSection); var serverKeys = serverSection.Select(kv => kv.Key).ToArray(); ini_.GetKeys("SERVER").Should().Equal("IP", "Port"); ini_.HasKey("server", "ip").Should().BeTrue(); ini_.ReadString("server", "ip").Should().Equals("127.0.0.1"); ini_.ReadString("server", "port").Should().Equals("8080"); ini_.ReadInt("server", "port").Should().Be(8080); ini_.ReadUInt("server", "port").Should().Be(8080); ini_.Write("server", "ip", "192.168.0.1").Should().BeTrue(); ini_.ReadString("server", "ip").Should().Equals("192.168.0.1"); ini_.Write("server", "port", 80).Should().BeTrue(); ini_.ReadInt("server", "port").Should().Be(80); ini_.ReadString("server", "ip-not-existed", null).Should().BeEmpty(); ini_.ReadString("server", "ip-not-existed", "ghost").Should().Be("ghost"); ini_.ReadInt("server", "port-not-existed").Should().Be(0); ini_.ReadInt("server", "port-not-existed", 3000).Should().Be(3000); ini_.Write("server", "UseIPv6", false).Should().BeTrue(); ini_.ReadBoolean("server", "useipv6").Should().BeFalse(); ini_.Write("server", "UseIPv6", true).Should().BeTrue(); ini_.ReadString("server", "UseIPv6").Should().Be("true"); ini_.ReadBoolean("server", "UseIPv6").Should().BeTrue(); ini_.Read("server", "UseIPv6", false, bool.TryParse).Should().BeTrue(); ini_.Write("server", "UseIPv6", "no").Should().BeTrue(); ini_.Read("server", "UseIPv6", false, bool.TryParse).Should().BeFalse(); ini_.Write("Session", "User", "Jerry").Should().BeTrue(); ini_.Write("Session", "Password", "admin").Should().BeTrue(); ini_.GetSections().Should().Equal("Server", "Session"); var lastSeen = DateTime.Now; ini_.Write("Session", "LastSeen", DateTime.Now, dt => dt.ToString("o")).Should().BeTrue(); ini_.ReadString("Session", "LastSeen").Should().Be(lastSeen.ToString("o")); ini_.GetKeys("Session").Should().Equal("User", "Password", "LastSeen"); ini_["session", "user"].Should().Be("Jerry"); ini_.ReadLong("server", "port").Should().Be(80); ini_.ReadULong("server", "port").Should().Be(80); ini_.Write("math", "pi", 3.14).Should().BeTrue(); ini_.Write("math", "e", 2.71828).Should().BeTrue(); ini_.ReadDouble("math", "pi").Should().BeApproximately(3.14, 1e-6); ini_.ReadDouble("math", "e").Should().BeApproximately(2.71828, 1e-6); }
/// <summary> /// Gets an image control with mouse events required to rotate the image cycle on mouse over. Returns null if /// no image is available. /// </summary> /// <param name="deviceURL"></param> /// <param name="images"></param> /// <returns></returns> internal static System.Web.UI.WebControls.WebControl GetDeviceImageRotater(KeyValuePair<string, Uri>[] images, string deviceURL) { HyperLink deviceLink = new HyperLink(); deviceLink.NavigateUrl = deviceURL; if (images != null) { System.Web.UI.WebControls.Image deviceImage = new System.Web.UI.WebControls.Image(); if (images.Length > 0) { deviceImage.ImageUrl = images[0].Value.ToString(); // Hover events are only useful if there are extra images to cycle to if (images.Length > 1) { string[] imageUrls = images.Select(i => String.Format("'{0}'", i.Value)).ToArray(); // Create onmouseover event. It creates an array of url strings that should be cycled in order string mouseOver = String.Format("ImageHovered(this, new Array({0}))", String.Join(",", imageUrls) ); // Create onmouseout event. It is passed a single url string that should be loaded when the cursor leaves the image string mouseOff = String.Format("ImageUnHovered(this, '{0}')", images[0].Value.ToString()); deviceImage.Attributes.Add("onmouseover", mouseOver.Replace("\\", "\\\\")); deviceImage.Attributes.Add("onmouseout", mouseOff.Replace("\\", "\\\\")); } } else // there are no images availble, so use the unknown one deviceImage.ImageUrl = UNKNOWN_IMAGE_URL; deviceImage.Height = Unit.Pixel(128); deviceImage.Width = Unit.Pixel(128); deviceLink.Controls.Add(deviceImage); return deviceLink; } else return null; }
public static void CopyToTest(ListDictionary ld, KeyValuePair<string, string>[] data) { DictionaryEntry[] translated = data.Select(kv => new DictionaryEntry(kv.Key, kv.Value)).ToArray(); DictionaryEntry[] full = new DictionaryEntry[data.Length]; ld.CopyTo(full, 0); Assert.Equal(translated, full); DictionaryEntry[] large = new DictionaryEntry[data.Length * 2]; ld.CopyTo(large, data.Length / 2); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 2 || i >= data.Length + data.Length / 2) { Assert.Equal(new DictionaryEntry(), large[i]); Assert.Null(large[i].Key); Assert.Null(large[i].Value); } else { Assert.Equal(translated[i - data.Length / 2], large[i]); } } }
private void AddFunction(PrimitiveTypeKind returnType, string functionName, KeyValuePair<string, PrimitiveTypeKind>[] parameterDefinitions) { FunctionParameter returnParameter = CreateReturnParameter(returnType); FunctionParameter[] parameters = parameterDefinitions.Select(paramDef => CreateParameter(paramDef.Value, paramDef.Key)).ToArray(); EdmFunction function = new EdmFunction(functionName, EdmConstants.EdmNamespace, DataSpace.CSpace, new EdmFunctionPayload { IsBuiltIn = true, ReturnParameters = new FunctionParameter[] {returnParameter}, Parameters = parameters, IsFromProviderManifest = true, }); function.SetReadOnly(); this.functions.Add(function); }
public void InitTaskRemote(string taskName, KeyValuePair<string, byte[]>[] mainFileList, KeyValuePair<string, byte[]>[] extraFileList) { if(_tasks.ContainsKey(taskName)) throw new Exception("Такая задача уже была ранее проинициализирована"); Directory.CreateDirectory(taskName); foreach (var f in mainFileList) File.WriteAllBytes(f.Key, f.Value); if(extraFileList != null) foreach (var f in extraFileList) File.WriteAllBytes(f.Key, f.Value); var t = new TaskScheduler(taskName, taskName, mainFileList.Select(p => p.Key).ToArray(), _finder, _connection); if (_isStarted) t.Start(); _tasks.Add(taskName, t); }
private static string GetUrl(KeyValuePair<string, object>[] parameters) { return "{0}?{1}".AsFormat( Target, string.Join("&", parameters.Select(p => "{0}={1}".AsFormat(p.Key, p.Value)))); }