content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) 2019 Lykke Corp. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading.Tasks; using JetBrains.Annotations; using MarginTrading.AssetService.Contracts.Scheduling; using Refit; namespace MarginTrading.AssetService.Contracts { /// <summary> /// Schedule settings management /// </summary> [PublicAPI] public interface IScheduleSettingsApi { /// <summary> /// Get the list of schedule settings. Optional filter by market may be applied. /// </summary> [Get("/api/scheduleSettings")] Task<List<ScheduleSettingsContract>> List([Query][CanBeNull] string marketId = null); /// <summary> /// Create new schedule setting /// </summary> [Post("/api/scheduleSettings")] Task<ScheduleSettingsContract> Insert([Body] ScheduleSettingsContract scheduleSetting); /// <summary> /// Get the schedule setting /// </summary> [ItemCanBeNull] [Get("/api/scheduleSettings/{settingId}")] Task<ScheduleSettingsContract> Get([NotNull] string settingId); /// <summary> /// Update the schedule setting /// </summary> [Put("/api/scheduleSettings/{settingId}")] Task<ScheduleSettingsContract> Update( [NotNull] string settingId, [Body] ScheduleSettingsContract scheduleSetting); /// <summary> /// Delete the schedule setting /// </summary> [Delete("/api/scheduleSettings/{settingId}")] Task Delete([NotNull] string settingId); /// <summary> /// Get the list of compiled schedule settings based on array of asset pairs /// </summary> /// <param name="assetPairIds">Null by default</param> [Post("/api/scheduleSettings/compiled")] Task<List<CompiledScheduleContract>> StateList([Body][CanBeNull] string[] assetPairIds); /// <summary> /// Get current trading day info for markets. Platform schedule (with PlatformScheduleMarketId) overrides all others. /// </summary> /// <param name="marketIds">Optional. List of market Id's.</param> /// <param name="date">Timestamp of check (allows to check as at any moment of time</param> [Post("/api/scheduleSettings/markets-info")] Task<Dictionary<string, TradingDayInfoContract>> GetMarketsInfo([Body] string[] marketIds = null, [Query] DateTime? date = null); /// <summary> /// Get current platform trading info: is trading enabled, and last trading day. /// If interval has only date component i.e. time is 00:00:00.000, then previous day is returned. /// </summary> /// <param name="date">Timestamp of check (allows to check as at any moment of time</param> [Get("/api/scheduleSettings/platform-info")] Task<TradingDayInfoContract> GetPlatformInfo([Query] DateTime? date = null); } }
39.789474
137
0.641534
[ "MIT-0" ]
gponomarev-lykke/MarginTrading.AssetService
src/MarginTrading.AssetService.Contracts/IScheduleSettingsApi.cs
3,026
C#
using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tests.Zip { [TestFixture] public class ZipNameTransformHandling : TransformBase { [Test] [Category("Zip")] public void Basic() { var t = new ZipNameTransform(); TestFile(t, "abcdef", "abcdef"); TestFile(t, @"\\uncpath\d1\file1", "file1"); TestFile(t, @"C:\absolute\file2", "absolute/file2"); // This is ignored but could be converted to 'file3' TestFile(t, @"./file3", "./file3"); // The following relative paths cant be handled and are ignored TestFile(t, @"../file3", "../file3"); TestFile(t, @".../file3", ".../file3"); // Trick filenames. TestFile(t, @".....file3", ".....file3"); TestFile(t, @"c::file", "_file"); } [Test] public void TooLong() { var zt = new ZipNameTransform(); var veryLong = new string('x', 65536); try { zt.TransformDirectory(veryLong); Assert.Fail("Expected an exception"); } catch (PathTooLongException) { } } [Test] public void LengthBoundaryOk() { var zt = new ZipNameTransform(); string veryLong = "c:\\" + new string('x', 65535); try { zt.TransformDirectory(veryLong); } catch { Assert.Fail("Expected no exception"); } } [Test] [Category("Zip")] public void NameTransforms() { INameTransform t = new ZipNameTransform(@"C:\Slippery"); Assert.AreEqual("Pongo/Directory/", t.TransformDirectory(@"C:\Slippery\Pongo\Directory"), "Value should be trimmed and converted"); Assert.AreEqual("PoNgo/Directory/", t.TransformDirectory(@"c:\slipperY\PoNgo\Directory"), "Trimming should be case insensitive"); Assert.AreEqual("slippery/Pongo/Directory/", t.TransformDirectory(@"d:\slippery\Pongo\Directory"), "Trimming should be case insensitive"); Assert.AreEqual("Pongo/File", t.TransformFile(@"C:\Slippery\Pongo\File"), "Value should be trimmed and converted"); } /// <summary> /// Test ZipEntry static file name cleaning methods /// </summary> [Test] [Category("Zip")] public void FilenameCleaning() { Assert.AreEqual(ZipEntry.CleanName("hello"), "hello"); if(Environment.OSVersion.Platform == PlatformID.Win32NT) { Assert.AreEqual(ZipEntry.CleanName(@"z:\eccles"), "eccles"); Assert.AreEqual(ZipEntry.CleanName(@"\\server\share\eccles"), "eccles"); Assert.AreEqual(ZipEntry.CleanName(@"\\server\share\dir\eccles"), "dir/eccles"); } else { Assert.AreEqual(ZipEntry.CleanName(@"/eccles"), "eccles"); } } [Test] [Category("Zip")] public void PathalogicalNames() { string badName = ".*:\\zy3$"; Assert.IsFalse(ZipNameTransform.IsValidName(badName)); var t = new ZipNameTransform(); string result = t.TransformFile(badName); Assert.IsTrue(ZipNameTransform.IsValidName(result)); } } }
26.427273
141
0.660475
[ "MIT" ]
0xced/SharpZipLib
test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs
2,909
C#
 using Xunit; using ProtoBuf.Meta; namespace Examples.Issues { using System.Collections.Generic; using System.IO; using ProtoBuf; public class SO7333233 { [ProtoContract] [ProtoInclude(2, typeof(Ant))] [ProtoInclude(3, typeof(Cat))] public interface IBeast { [ProtoMember(1)] string Name { get; set; } } [ProtoContract] public class Ant : IBeast { public string Name { get; set; } } [ProtoContract] public class Cat : IBeast { public string Name { get; set; } } [ProtoContract] public interface IRule<T> where T : IBeast { bool IsHappy(T beast); } [ProtoContract] public class AntRule1 : IRule<IAnt>, IRule<Ant> { public bool IsHappy(IAnt beast) { return true; } public bool IsHappy(Ant beast) { return true; } } [ProtoContract] public class AntRule2 : IRule<IAnt>, IRule<Ant> { public bool IsHappy(IAnt beast) { return true; } public bool IsHappy(Ant beast) { return true; } } public interface ICat : IBeast { } public interface IAnt : IBeast { } [ProtoContract] public class CatRule1 : IRule<ICat>, IRule<Cat> { public bool IsHappy(ICat beast) { return true; } public bool IsHappy(Cat beast) { return true; } } [ProtoContract] public class CatRule2 : IRule<ICat>, IRule<Cat> { public bool IsHappy(ICat beast) { return true; } public bool IsHappy(Cat beast) { return true; } } [Fact] public void Execute() { // note these are unrelated networks, so we can use the same field-numbers RuntimeTypeModel.Default[typeof(IRule<Ant>)].AddSubType(1, typeof(AntRule1)).AddSubType(2, typeof(AntRule2)); RuntimeTypeModel.Default[typeof(IRule<Cat>)].AddSubType(1, typeof(CatRule1)).AddSubType(2, typeof(CatRule2)); var antRules = new List<IRule<Ant>>(); antRules.Add(new AntRule1()); antRules.Add(new AntRule2()); var catRules = new List<IRule<Cat>>(); catRules.Add(new CatRule1()); catRules.Add(new CatRule2()); using (var fs = File.Create(@"antRules.bin")) { ProtoBuf.Serializer.Serialize(fs, antRules); fs.Close(); } using (var fs = File.OpenRead(@"antRules.bin")) { List<IRule<Ant>> list; list = ProtoBuf.Serializer.Deserialize<List<IRule<Ant>>>(fs); fs.Close(); } using (var fs = File.Create(@"catRules.bin")) { ProtoBuf.Serializer.Serialize(fs, catRules); fs.Close(); } using (var fs = File.OpenRead(@"catRules.bin")) { List<IRule<Cat>> list; list = ProtoBuf.Serializer.Deserialize<List<IRule<Cat>>>(fs); fs.Close(); } } } }
24.255034
121
0.465689
[ "Apache-2.0" ]
mustang2247/protobuf-net-ILRuntime
src/Examples/Issues/SO7333233.cs
3,616
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461/blob/master/LICENSE * */ #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Playground")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Playground")] [assembly: AssemblyCopyright("Copyright © Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV) 2018 - 2020. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e10c5153-0007-4dd3-930d-9d3117db7c44")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.461.1032.0")] [assembly: AssemblyFileVersion("5.461.1032.0")] [assembly: Dependency("System", LoadHint.Always)] [assembly: Dependency("System.Xml", LoadHint.Always)] [assembly: Dependency("System.Drawing", LoadHint.Always)] [assembly: Dependency("System.Windows.Forms", LoadHint.Always)] [assembly: Dependency("ComponentFactory.Krypton.Toolkit", LoadHint.Always)]
39.823529
136
0.751846
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461
Source/Krypton Toolkit Suite Extended/Demos/Playground/Properties/AssemblyInfo.cs
2,034
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Xunit; #if CISTERN_LINQ using Cistern.Linq; #elif CISTERN_VALUELINQ using Cistern.ValueLinq; #else using System.Linq; #endif namespace Linqs.Tests { public partial class GroupByTests : EnumerableTests { private static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<System.Linq.IGrouping<TKey, TElement>> grouping) { AssertGroupingCorrect<TKey, TElement>(keys, elements, grouping, EqualityComparer<TKey>.Default); } private static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<System.Linq.IGrouping<TKey, TElement>> grouping, IEqualityComparer<TKey> keyComparer) { if (grouping == null) { Assert.Null(elements); Assert.Null(keys); return; } Assert.NotNull(elements); Assert.NotNull(keys); Dictionary<TKey, List<TElement>> dict = new Dictionary<TKey, List<TElement>>(keyComparer); List<TElement> groupingForNullKeys = new List<TElement>(); using (IEnumerator<TElement> elEn = elements.GetEnumerator()) using (IEnumerator<TKey> keyEn = keys.GetEnumerator()) { while (keyEn.MoveNext()) { Assert.True(elEn.MoveNext()); TKey key = keyEn.Current; if (key == null) { groupingForNullKeys.Add(elEn.Current); } else { List<TElement> list; if (!dict.TryGetValue(key, out list)) dict.Add(key, list = new List<TElement>()); list.Add(elEn.Current); } } Assert.False(elEn.MoveNext()); } foreach (System.Linq.IGrouping<TKey, TElement> group in grouping) { Assert.NotEmpty(group); TKey key = group.Key; List<TElement> list; if (key == null) { Assert.Equal(groupingForNullKeys, group); groupingForNullKeys.Clear(); } else { Assert.True(dict.TryGetValue(key, out list)); Assert.Equal(list, group); dict.Remove(key); } } Assert.Empty(dict); Assert.Empty(groupingForNullKeys); } public struct Record { public string Name; public int Score; } [Fact] public void SameResultsRepeatCallsStringQuery() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; ; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.NotNull(q.GroupBy(e => e.a1, e => e.a2)); Assert.Equal(q.GroupBy(e => e.a1, e => e.a2), q.GroupBy(e => e.a1, e => e.a2)); } [Fact] public void Grouping_IList_IsReadOnly() { IEnumerable<System.Linq.IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); foreach (IList<int> grouping in oddsEvens) { Assert.True(grouping.IsReadOnly); } } [Fact] public void Grouping_IList_NotSupported() { IEnumerable<System.Linq.IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); foreach (IList<int> grouping in oddsEvens) { Assert.Throws<NotSupportedException>(() => grouping.Add(5)); Assert.Throws<NotSupportedException>(() => grouping.Clear()); Assert.Throws<NotSupportedException>(() => grouping.Insert(0, 1)); Assert.Throws<NotSupportedException>(() => grouping.Remove(1)); Assert.Throws<NotSupportedException>(() => grouping.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => grouping[0] = 1); } } [Fact] public void Grouping_IList_IndexerGetter() { IEnumerable<System.Linq.IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Equal(1, odds[0]); Assert.Equal(3, odds[1]); Assert.True(e.MoveNext()); IList<int> evens = (IList<int>)e.Current; Assert.Equal(2, evens[0]); Assert.Equal(4, evens[1]); } [Fact] public void Grouping_IList_IndexGetterOutOfRange() { IEnumerable<System.Linq.IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => odds[-1]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => odds[23]); } [Fact] public void Grouping_ICollection_Contains() { IEnumerable<System.Linq.IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); ICollection<int> odds = (IList<int>)e.Current; Assert.True(odds.Contains(1)); Assert.True(odds.Contains(3)); Assert.False(odds.Contains(2)); Assert.False(odds.Contains(4)); Assert.True(e.MoveNext()); ICollection<int> evens = (IList<int>)e.Current; Assert.True(evens.Contains(2)); Assert.True(evens.Contains(4)); Assert.False(evens.Contains(1)); Assert.False(evens.Contains(3)); } [Fact] public void Grouping_IList_IndexOf() { IEnumerable<System.Linq.IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Equal(0, odds.IndexOf(1)); Assert.Equal(1, odds.IndexOf(3)); Assert.Equal(-1, odds.IndexOf(2)); Assert.Equal(-1, odds.IndexOf(4)); Assert.True(e.MoveNext()); IList<int> evens = (IList<int>)e.Current; Assert.Equal(0, evens.IndexOf(2)); Assert.Equal(1, evens.IndexOf(4)); Assert.Equal(-1, evens.IndexOf(1)); Assert.Equal(-1, evens.IndexOf(3)); } [Fact] public void SingleNullKeySingleNullElement() { string[] key = { null }; string[] element = { null }; AssertGroupingCorrect(key, element, new string[] { null }.GroupBy(e => e, e => e, EqualityComparer<string>.Default), EqualityComparer<string>.Default); } [Fact] public void EmptySource() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void EmptySourceRunOnce() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.RunOnce().GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SourceIsNull() { Record[] source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void SourceIsNullResultSelectorUsed() { Record[] source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void SourceIsNullResultSelectorUsedNoComparer() { Record[] source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum())); } [Fact] public void SourceIsNullResultSelectorUsedNoComparerOrElementSelector() { Record[] source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score))); } [Fact] public void KeySelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, new AnagramEqualityComparer())); } [Fact] public void KeySelectorNullResultSelectorUsed() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void KeySelectorNullResultSelectorUsedNoComparer() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, string> keySelector = null; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(keySelector, e => e.Score, (k, es) => es.Sum())); } [Fact] public void KeySelectorNullResultSelectorUsedNoElementSelector() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer())); } [Fact] public void ElementSelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, int> elementSelector = null; AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, new AnagramEqualityComparer())); } [Fact] public void ElementSelectorNullResultSelectorUsedNoComparer() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, int> elementSelector = null; AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum())); } [Fact] public void ResultSelectorNull() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<int>, long> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNullNoComparer() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<int>, long> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelector() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<Record>, long> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelectorCustomComparer() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Func<string, IEnumerable<Record>, long> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector, new AnagramEqualityComparer())); } [Fact] public void EmptySourceWithResultSelector() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void DuplicateKeysCustomComparer() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 240, 365, -600, 63 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void DuplicateKeysCustomComparerRunOnce() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 240, 365, -600, 63 }; Assert.Equal(expected, source.RunOnce().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void NullComparer() { string[] key = { "Tim", null, null, "Robert", "Chris", "miT" }; int[] element = { 55, 49, 9, -100, 24, 25 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = null, Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = null, Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 165, 58, -600, 120, 75 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null)); } [Fact] public void NullComparerRunOnce() { string[] key = { "Tim", null, null, "Robert", "Chris", "miT" }; int[] element = { 55, 49, 9, -100, 24, 25 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = null, Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = null, Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 165, 58, -600, 120, 75 }; Assert.Equal(expected, source.RunOnce().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null)); } [Fact] public void SingleNonNullElement() { string[] key = { "Tim" }; Record[] source = { new Record { Name = key[0], Score = 60 } }; AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name)); } [Fact] public void AllElementsSameKey() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] scores = { 60, -10, 40, 100 }; var source = key.Zip(scores, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name, new AnagramEqualityComparer()), new AnagramEqualityComparer()); } [Fact] public void AllElementsDifferentKeyElementSelectorUsed() { string[] key = { "Tim", "Chris", "Robert", "Prakash" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SomeDuplicateKeys() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SomeDuplicateKeysIncludingNulls() { string[] key = { null, null, "Chris", "Chris", "Prakash", "Prakash" }; int[] element = { 55, 25, 49, 24, 9, 9 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SingleElementResultSelectorUsed() { string[] key = { "Tim" }; int[] element = { 60 }; long[] expected = { 180 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => (long)(k ?? " ").Length * es.Sum(e => e.Score))); } [Fact] public void GroupedResultCorrectSize() { var elements = Enumerable.Repeat('q', 5); var result = elements.GroupBy(e => e, (e, f) => new { Key = e, Element = f }); Assert.Equal(1, result.Count()); var grouping = result.First(); Assert.Equal(5, grouping.Element.Count()); Assert.Equal('q', grouping.Key); Assert.True(grouping.Element.All(e => e == 'q')); } [Fact] public void AllElementsDifferentKeyElementSelectorUsedResultSelector() { string[] key = { "Tim", "Chris", "Robert", "Prakash" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); long[] expected = { 180, -50, 240, 700 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum())); } [Fact] public void AllElementsSameKeyResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; long[] expected = { 570 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] } }; Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), new AnagramEqualityComparer())); } [Fact] public void NullComparerResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] }, }; long[] expected = { 150, 420 }; Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), null)); } [Fact] public void GroupingToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; System.Linq.IGrouping<string, Record>[] groupedArray = source.GroupBy(r => r.Name).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name), groupedArray); } [Fact] public void GroupingWithElementSelectorToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; System.Linq.IGrouping<string, int>[] groupedArray = source.GroupBy(r => r.Name, e => e.Score).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name, e => e.Score), groupedArray); } [Fact] public void GroupingWithResultsToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IEnumerable<Record>[] groupedArray = source.GroupBy(r => r.Name, (r, e) => e).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name, (r, e) => e), groupedArray); } [Fact] public void GroupingWithElementSelectorAndResultsToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IEnumerable<Record>[] groupedArray = source.GroupBy(r => r.Name, e => e, (r, e) => e).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name, e => e, (r, e) => e), groupedArray); } [Fact] public void GroupingToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<System.Linq.IGrouping<string, Record>> groupedList = source.GroupBy(r => r.Name).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name), groupedList); } [Fact] public void GroupingWithElementSelectorToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<System.Linq.IGrouping<string, int>> groupedList = source.GroupBy(r => r.Name, e => e.Score).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name, e => e.Score), groupedList); } [Fact] public void GroupingWithResultsToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<IEnumerable<Record>> groupedList = source.GroupBy(r => r.Name, (r, e) => e).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name, (r, e) => e), groupedList); } [Fact] public void GroupingWithElementSelectorAndResultsToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<IEnumerable<Record>> groupedList = source.GroupBy(r => r.Name, e => e, (r, e) => e).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name, e => e, (r, e) => e), groupedList); } [Fact] public void GroupingCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name).Count()); } [Fact] public void GroupingWithElementSelectorCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name, e => e.Score).Count()); } [Fact] public void GroupingWithResultsCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name, (r, e) => e).Count()); } [Fact] public void GroupingWithElementSelectorAndResultsCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name, e=> e, (r, e) => e).Count()); } [Fact] public void EmptyGroupingToArray() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i).ToArray()); } [Fact] public void EmptyGroupingToList() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i).ToList()); } [Fact] public void EmptyGroupingCount() { Assert.Equal(0, Enumerable.Empty<int>().GroupBy(i => i).Count()); } [Fact] public void EmptyGroupingWithResultToArray() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).ToArray()); } [Fact] public void EmptyGroupingWithResultToList() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).ToList()); } [Fact] public void EmptyGroupingWithResultCount() { Assert.Equal(0, Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).Count()); } [Fact] public static void GroupingKeyIsPublic() { // Grouping.Key needs to be public (not explicitly implemented) for the sake of WPF. object[] objs = { "Foo", 1.0M, "Bar", new { X = "X" }, 2.00M }; object group = objs.GroupBy(x => x.GetType()).First(); Type grouptype = group.GetType(); PropertyInfo key = grouptype.GetProperty("Key", BindingFlags.Instance | BindingFlags.Public); Assert.NotNull(key); } [Fact] public static void GroupBy_CreateViaPush() { var counts = new[] { 2, 10, 1000 }; foreach (var count in counts) { var z = Enumerable .Range(0, count) .GroupBy(x => x % 2 == 0) .OrderBy(x => x.Key) .Select(x => x.Max()) .ToList(); Assert.Equal(count - 1, z[0]); Assert.Equal(count - 2, z[1]); } } [Fact] public static void GroupBy_CreateViaPullDescend() { var counts = new[] { 2, 10, 1000 }; foreach (var count in counts) { var z = Enumerable .Range(0, count) .GroupBy(x => x % 2 == 0) .OrderBy(x => x.Key) .Select(x => x.Where(_ => true).ToArray()) .ToList(); Assert.Equal(count / 2, z[0].Length); Assert.Equal(count / 2, z[1].Length); } } [Fact] public static void GroupBy_TryPushOptimization() { var counts = new[] { 2, 10, 1000 }; foreach (var count in counts) { var z = Enumerable .Range(0, count) .GroupBy(x => x % 2 == 0) .OrderBy(x => x.Key) .Select(x => x.Reverse().ToArray()) .ToList(); Assert.Equal(count / 2, z[0].Length); Assert.Equal(count / 2, z[1].Length); } } [Fact] public static void GroupBy_TryPullOptimization() { var counts = new[] { 2, 10, 1000 }; foreach (var count in counts) { var z = Enumerable .Range(1, count) .Select(x => -x) .GroupBy(x => x % 2 == 0) .OrderBy(x => x.Key) .Select(x => { var max = int.MinValue; foreach(var n in x.Select(x => x)) { max = Math.Max(max, n); } return max; }) .ToList(); Assert.Equal(-1, z[0]); Assert.Equal(-2, z[1]); } } } }
38.450413
219
0.480253
[ "MIT" ]
manofstick/Cistern.ValueLinq
Tests/GroupByTests.cs
37,220
C#
namespace EA.Iws.Domain.NotificationApplication { using System; using System.Collections.Generic; using System.Linq; using Core.WasteType; public partial class NotificationApplication { public bool HasWasteType { get { return WasteType != null; } } public void SetWasteType(WasteType wasteType) { if (WasteType == null) { WasteType = wasteType; return; } if (WasteType.ChemicalCompositionType == wasteType.ChemicalCompositionType) { UpdateSameChemicalCompositionType(wasteType); } else { ClearAllWasteData(); WasteType = wasteType; } } private void UpdateSameChemicalCompositionType(WasteType wasteType) { if (wasteType.ChemicalCompositionType == ChemicalComposition.Other) { WasteType.ChemicalCompositionName = wasteType.ChemicalCompositionName; } if (wasteType.ChemicalCompositionType == ChemicalComposition.RDF || wasteType.ChemicalCompositionType == ChemicalComposition.SRF) { ClearWasteAdditionalInformation(); WasteType.SetWasteAdditionalInformation(wasteType.WasteAdditionalInformation.ToList()); } if (wasteType.ChemicalCompositionType == ChemicalComposition.Wood) { ClearWasteAdditionalInformation(); WasteType.SetWasteAdditionalInformation(wasteType.WasteAdditionalInformation.ToList()); WasteType.WoodTypeDescription = wasteType.WoodTypeDescription; } } private void ClearAllWasteData() { if (WasteType != null) { WasteType.OptionalInformation = null; WasteType.EnergyInformation = null; WasteType.WoodTypeDescription = null; WasteType.OtherWasteTypeDescription = null; WasteType.HasAnnex = false; ClearWasteCompositions(); ClearWasteAdditionalInformation(); } } private void ClearWasteCompositions() { if (WasteType != null && WasteType.WasteCompositions != null) { WasteType.ClearWasteCompositions(); } } private void ClearWasteAdditionalInformation() { if (WasteType != null && WasteType.WasteAdditionalInformation != null) { WasteType.ClearWasteAdditionalInformation(); } } public void AddOtherWasteTypeAdditionalInformation(string description, bool hasAnnex) { if (WasteType == null) { throw new InvalidOperationException(string.Format("Waste type does not exist on notification: {0}", Id)); } WasteType.OtherWasteTypeDescription = description; WasteType.HasAnnex = hasAnnex; } public void SetWasteAdditionalInformation(IList<WasteAdditionalInformation> wasteType) { if (WasteType == null) { throw new InvalidOperationException(string.Format("Waste type does not exist on notification: {0}", Id)); } ClearWasteAdditionalInformation(); WasteType.SetWasteAdditionalInformation(wasteType); } public void SetChemicalCompostitionContinues(IList<WasteComposition> wasteCompositions) { if (wasteCompositions == null) { throw new InvalidOperationException(string.Format("Waste type does not exist on notification: {0}", Id)); } ClearWasteCompositions(); WasteType.WasteCompositions = wasteCompositions; } public void SetWoodTypeDescription(string woodTypeDescription) { if (WasteType == null) { throw new InvalidOperationException(String.Format("Waste Type can not be null for notification: {0}", Id)); } WasteType.WoodTypeDescription = woodTypeDescription; } public void SetOptionalInformation(string optionalInformation, bool hasAnnex) { if (WasteType == null) { throw new InvalidOperationException(String.Format("Waste Type can not be null for notification: {0}", Id)); } WasteType.OptionalInformation = optionalInformation; WasteType.HasAnnex = hasAnnex; } public void SetEnergy(string energyInformation) { if (WasteType == null) { throw new InvalidOperationException(String.Format("Waste Type can not be null for notification: {0}", Id)); } WasteType.EnergyInformation = energyInformation; } } }
34.77931
141
0.580408
[ "Unlicense" ]
DEFRA/prsd-iws
src/EA.Iws.Domain/NotificationApplication/NotificationApplication.WasteType.cs
5,045
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Support { /// <summary>backup support feature type.</summary> [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Support.FeatureTypeTypeConverter))] public partial struct FeatureType : System.Management.Automation.IArgumentCompleter { /// <summary> /// Implementations of this function are called by PowerShell to complete arguments. /// </summary> /// <param name="commandName">The name of the command that needs argument completion.</param> /// <param name="parameterName">The name of the parameter that needs argument completion.</param> /// <param name="wordToComplete">The (possibly empty) word being completed.</param> /// <param name="commandAst">The command ast in case it is needed for completion.</param> /// <param name="fakeBoundParameters">This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot /// or will not attempt to evaluate an argument, in which case you may need to use commandAst.</param> /// <returns> /// A collection of completion results, most like with ResultType set to ParameterValue. /// </returns> public global::System.Collections.Generic.IEnumerable<global::System.Management.Automation.CompletionResult> CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) { if (global::System.String.IsNullOrEmpty(wordToComplete) || "Invalid".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) { yield return new global::System.Management.Automation.CompletionResult("Invalid", "Invalid", global::System.Management.Automation.CompletionResultType.ParameterValue, "Invalid"); } if (global::System.String.IsNullOrEmpty(wordToComplete) || "DataSourceType".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) { yield return new global::System.Management.Automation.CompletionResult("DataSourceType", "DataSourceType", global::System.Management.Automation.CompletionResultType.ParameterValue, "DataSourceType"); } } } }
72.846154
373
0.722633
[ "MIT" ]
Amrinder-Singh29/azure-powershell
src/DataProtection/generated/api/Support/FeatureType.Completer.cs
2,803
C#
using FSharpUtils.Newtonsoft; using LanguageExt; using static LanguageExt.Prelude; namespace Tweek.Engine.Drivers { public static class JsonValueExtensions { public static Option<JsonValue> GetPropertyOption(this JsonValue json, string propName) { var prop = json.TryGetProperty(propName); return Optional(prop?.Value); } } }
27.642857
95
0.684755
[ "MIT" ]
Gabrn/tweek
core/Engine/Tweek.Engine.Drivers/Utils/JsonValueExtensions.cs
387
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; using Umbraco.Core; namespace MCFly.Core { public abstract class FieldType : IFieldType { private string frontEndRenderView; public virtual string FrontEndRenderView { get { return frontEndRenderView??Name; } set { frontEndRenderView = value; } } private string backOfficeEditView = UIOMatic.Constants.FieldEditors.Textfield; public virtual string BackOfficeEditView { get { return backOfficeEditView; } set { backOfficeEditView = value; } } private string backOfficeListView = UIOMatic.Constants.FieldViews.Label; public virtual string BackOfficeListView { get { return backOfficeListView; } set { backOfficeListView = value; } } private string emailRenderView = "Text"; public virtual string EmailRenderView { get { return emailRenderView; } set { emailRenderView = value; } } private bool supportsOptions = false; public virtual bool SupportsOptions { get { return supportsOptions; } set { supportsOptions = value; } } private bool supportsPlaceholder = true; public virtual bool SupportsPlaceholder { get { return supportsPlaceholder; } set { supportsPlaceholder = value; } } private bool storesData = true; public virtual bool StoresData { get { return storesData; } set { storesData = value; } } private bool hideCaption = false; public virtual bool HideCaption { get { return hideCaption; } set { hideCaption = value; } } private Type propertyType = typeof(string); public virtual Type PropertyType { get { return propertyType; } set { propertyType = value; } } private string name; public virtual string Name { get { return name??this.GetType().Name; } set { name = value; } } public virtual IEnumerable<CustomAttributeBuilder> ValidationAttributes(Form form, Field field) { return null; } public virtual object Process(Form form, Field field, object value, ControllerContext controllerContext) { if (value == null) return value; return Convert.ChangeType(value, field.FieldType.PropertyType); } public virtual IEnumerable<string> RequiredJSFiles() { return new string[0]; } public virtual IEnumerable<string> RequiredCssFiles() { return new string[0]; } public virtual string RequiredJSInitialization(string fieldId) { return string.Empty; } } }
25.133858
112
0.58396
[ "MIT" ]
KonradCshark/MCFly
MCFly/Core/FieldType.cs
3,194
C#
using System; using static System.Console; namespace BinarySearch { class Program { static void Main(string[] args) { int theValue = 43; int[] array = new int[] { 11, 22, 43, 54, 57, 59, 62, 78 }; WriteLine("Our array contains:"); Array.ForEach(array, x => Write($"{x} ")); Write($"\n\nThe result of a binary search for {theValue} is: "); WriteLine(binarySearch(array, theValue)); } /// <summary> /// a = array /// x = wha we'ar searching /// p = first index /// q = midpoint /// r = last index /// </summary> public static int binarySearch(int[] a, int x) { // Step 1 - initialize the variables int p = 0; // begining of the range int r = a.Length - 1; // the end of the range aka last sot // Step 2 - we do somthing (search for our value) while (p <= r) { int q = (p + r) / 2; // find midpoint if (x < a[q]) { r = q - 1; // set r to midpoint. We narrowed to 1st // half of the array in the case x i sless // the data in slot q } else if (x > a[q]) { p = q + 1; // the opposite occurs. We bring p to the // right of the array } else { return q; } } // Step 3 - indicate not fund return -1; } } }
29.457627
78
0.395857
[ "MIT" ]
ValkovStoil/newCoursec
Ex_Files_Learning_C_Sharp_Algorithms/Exercise Files/Ch05/05_02/Begin/BinarySearch/Program.cs
1,740
C#
using System; using Xamarin.Forms; namespace PCL { public class FormsPage : ContentPage { public FormsPage() { JsonSerialize json = new JsonSerialize(); var _form = json.parseJson(); var mainLayout = new StackLayout { Padding = 20 }; this.Title = _form.Title; foreach (var el in _form.Elements) { switch (el.Type) { //Add Label case "Label": mainLayout.Children.Add(new Label { Text = ((FormLabel)el).LabelText, FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.FillAndExpand }); break; //Add Entry case "Entry": mainLayout.Children.Add(new Label { Text = ((FormEntryField)el).LabelText, HorizontalOptions = LayoutOptions.FillAndExpand }); mainLayout.Children.Add(new Entry { Placeholder = ((FormEntryField)el).PlaceHolderText, HorizontalOptions = LayoutOptions.FillAndExpand }); break; //Add text field case "TextField": mainLayout.Children.Add(new Label { Text = ((FormTextField)el).LabelText, HorizontalOptions = LayoutOptions.FillAndExpand }); mainLayout.Children.Add(new Editor { //Text = ((FormTextField)el).LabelText, HorizontalOptions = LayoutOptions.FillAndExpand }); break; case "Picker": mainLayout.Children.Add(new Label { Text = ((Picker)el).LabelText, HorizontalOptions = LayoutOptions.FillAndExpand }); var _picker = new Xamarin.Forms.Picker(); _picker.HorizontalOptions = LayoutOptions.FillAndExpand; foreach (var option in ((Picker)el).Values) { _picker.Items.Add(option); } mainLayout.Children.Add(_picker); break; case "Switch": mainLayout.Children.Add(new Label { Text = ((FormSwitch)el).LabelText, HorizontalOptions = LayoutOptions.FillAndExpand }); mainLayout.Children.Add(new Switch { IsToggled = ((FormSwitch)el).DefaultValue, HorizontalOptions = LayoutOptions.FillAndExpand }); break; case "DatePicker": mainLayout.Children.Add(new Label { Text = ((DatePicker)el).LabelText, HorizontalOptions = LayoutOptions.FillAndExpand }); mainLayout.Children.Add(new Xamarin.Forms.DatePicker { HorizontalOptions = LayoutOptions.FillAndExpand }); break; default: break; } } this.Content = mainLayout; } async public void getFormAsync() { } } }
20.88189
62
0.605204
[ "MIT" ]
malirezai/Dynamic-Forms-App
PROJECT-STEPS/Part2/PCL/Pages/FormsPage.cs
2,654
C#
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.Globalization; using System.Linq; using System.Web; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Security; using DotNetNuke.Services.Personalization; using DotNetNuke.Services.Tokens; using DotNetNuke.Common; using DotNetNuke.Abstractions.Portals; #endregion namespace DotNetNuke.Entities.Portals { /// ----------------------------------------------------------------------------- /// <summary> /// The PortalSettings class encapsulates all of the settings for the Portal, /// as well as the configuration settings required to execute the current tab /// view within the portal. /// </summary> /// ----------------------------------------------------------------------------- [Serializable] public partial class PortalSettings : BaseEntityInfo, IPropertyAccess, IPortalSettings { #region ControlPanelPermission enum public enum ControlPanelPermission { TabEditor, ModuleEditor } #endregion #region Mode enum public enum Mode { View, Edit, Layout } #endregion #region PortalAliasMapping enum public enum PortalAliasMapping { None, CanonicalUrl, Redirect } #endregion #region Data Consent UserDeleteAction enum public enum UserDeleteAction { Off = 0, Manual = 1, DelayedHardDelete = 2, HardDelete = 3 } #endregion #region Constructors public PortalSettings() { Registration = new RegistrationSettings(); } public PortalSettings(int portalId) : this(Null.NullInteger, portalId) { } public PortalSettings(int tabId, int portalId) { PortalId = portalId; var portal = PortalController.Instance.GetPortal(portalId); BuildPortalSettings(tabId, portal); } /// ----------------------------------------------------------------------------- /// <summary> /// The PortalSettings Constructor encapsulates all of the logic /// necessary to obtain configuration settings necessary to render /// a Portal Tab view for a given request. /// </summary> /// <remarks> /// </remarks> /// <param name="tabId">The current tab</param> /// <param name="portalAliasInfo">The current portal</param> /// ----------------------------------------------------------------------------- public PortalSettings(int tabId, PortalAliasInfo portalAliasInfo) { PortalId = portalAliasInfo.PortalID; PortalAlias = portalAliasInfo; var portal = string.IsNullOrEmpty(portalAliasInfo.CultureCode) ? PortalController.Instance.GetPortal(portalAliasInfo.PortalID) : PortalController.Instance.GetPortal(portalAliasInfo.PortalID, portalAliasInfo.CultureCode); BuildPortalSettings(tabId, portal); } public PortalSettings(PortalInfo portal) : this(Null.NullInteger, portal) { } public PortalSettings(int tabId, PortalInfo portal) { PortalId = portal != null ? portal.PortalID : Null.NullInteger; BuildPortalSettings(tabId, portal); } private void BuildPortalSettings(int tabId, PortalInfo portal) { PortalSettingsController.Instance().LoadPortalSettings(this); if (portal == null) return; PortalSettingsController.Instance().LoadPortal(portal, this); var key = string.Join(":", "ActiveTab", portal.PortalID.ToString(), tabId.ToString()); var items = HttpContext.Current != null ? HttpContext.Current.Items : null; if (items != null && items.Contains(key)) { ActiveTab = items[key] as TabInfo; } else { ActiveTab = PortalSettingsController.Instance().GetActiveTab(tabId, this); if (items != null && ActiveTab != null) { items[key] = ActiveTab; } } } #endregion #region Auto-Properties public TabInfo ActiveTab { get; set; } public int AdministratorId { get; set; } public int AdministratorRoleId { get; set; } public string AdministratorRoleName { get; set; } public int AdminTabId { get; set; } public string BackgroundFile { get; set; } public int BannerAdvertising { get; set; } public string CultureCode { get; set; } public string Currency { get; set; } public string DefaultLanguage { get; set; } public string Description { get; set; } public string Email { get; set; } public DateTime ExpiryDate { get; set; } public string FooterText { get; set; } public Guid GUID { get; set; } public string HomeDirectory { get; set; } public string HomeSystemDirectory { get; set; } public int HomeTabId { get; set; } public float HostFee { get; set; } public int HostSpace { get; set; } public string KeyWords { get; set; } public int LoginTabId { get; set; } public string LogoFile { get; set; } public int PageQuota { get; set; } public int Pages { get; set; } public int PortalId { get; set; } public PortalAliasInfo PortalAlias { get; set; } public PortalAliasInfo PrimaryAlias { get; set; } public string PortalName { get; set; } public int RegisteredRoleId { get; set; } public string RegisteredRoleName { get; set; } public int RegisterTabId { get; set; } public RegistrationSettings Registration { get; set; } public int SearchTabId { get; set; } [Obsolete("Deprecated in 8.0.0. Scheduled removal in v10.0.0.")] public int SiteLogHistory { get; set; } public int SplashTabId { get; set; } public int SuperTabId { get; set; } public int UserQuota { get; set; } public int UserRegistration { get; set; } public int Users { get; set; } public int UserTabId { get; set; } public int TermsTabId { get; set; } public int PrivacyTabId { get; set; } #endregion #region Read-Only Properties /// ----------------------------------------------------------------------------- /// <summary> /// Allows users to select their own UI culture. /// When set to false (default) framework will allways same culture for both /// CurrentCulture (content) and CurrentUICulture (interface) /// </summary> /// <remarks>Defaults to False</remarks> /// ----------------------------------------------------------------------------- public bool AllowUserUICulture { get; internal set; } public int CdfVersion { get; internal set; } public bool ContentLocalizationEnabled { get; internal set; } public ControlPanelPermission ControlPanelSecurity { get; internal set; } public string DefaultAdminContainer { get; internal set; } public string DefaultAdminSkin { get; internal set; } public string DefaultAuthProvider { get; internal set; } public Mode DefaultControlPanelMode { get; internal set; } public bool DefaultControlPanelVisibility { get; internal set; } public string DefaultIconLocation { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets the Default Module Id /// </summary> /// <remarks>Defaults to Null.NullInteger</remarks> /// ----------------------------------------------------------------------------- public int DefaultModuleId { get; internal set; } public string DefaultModuleActionMenu { get; internal set; } public string DefaultPortalContainer { get; internal set; } public string DefaultPortalSkin { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets the Default Tab Id /// </summary> /// <remarks>Defaults to Null.NullInteger</remarks> /// ----------------------------------------------------------------------------- public int DefaultTabId { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether Browser Language Detection is Enabled /// </summary> /// <remarks>Defaults to True</remarks> /// ----------------------------------------------------------------------------- public bool EnableBrowserLanguage { get; internal set; } public bool EnableCompositeFiles { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether to use the module effect in edit mode. /// </summary> /// <remarks>Defaults to True</remarks> /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public bool EnableModuleEffect { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether to use the popup. /// </summary> /// <remarks>Defaults to True</remarks> /// ----------------------------------------------------------------------------- public bool EnablePopUps { get; internal set; } /// <summary> /// Website Administrator whether receive the notification email when new user register. /// </summary> public bool EnableRegisterNotification { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether the Skin Widgets are enabled/supported /// </summary> /// <remarks>Defaults to True</remarks> /// ----------------------------------------------------------------------------- public bool EnableSkinWidgets { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether a cookie consent popup should be shown /// </summary> /// <remarks>Defaults to False</remarks> /// ----------------------------------------------------------------------------- public bool ShowCookieConsent { get; internal set; } /// <summary> /// Link for the user to find out more about cookies. If not specified the link /// shown will point to cookiesandyou.com /// </summary> public string CookieMoreLink { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether enable url language. /// </summary> /// <remarks>Defaults to True</remarks> /// ----------------------------------------------------------------------------- public bool EnableUrlLanguage { get; internal set; } public int ErrorPage404 { get; internal set; } public int ErrorPage500 { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether folders which are hidden or whose name begins with underscore /// are included in folder synchronization. /// </summary> /// <remarks> /// Defaults to True /// </remarks> /// ----------------------------------------------------------------------------- public bool HideFoldersEnabled { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether hide the login link. /// </summary> /// <remarks>Defaults to False.</remarks> /// ----------------------------------------------------------------------------- public bool HideLoginControl { get; internal set; } public string HomeDirectoryMapPath { get; internal set; } public string HomeSystemDirectoryMapPath { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether the Inline Editor is enabled /// </summary> /// <remarks>Defaults to True</remarks> /// ----------------------------------------------------------------------------- public bool InlineEditorEnabled { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether to inlcude Common Words in the Search Index /// </summary> /// <remarks>Defaults to False</remarks> /// ----------------------------------------------------------------------------- public bool SearchIncludeCommon { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether to inlcude Numbers in the Search Index /// </summary> /// <remarks>Defaults to False</remarks> /// ----------------------------------------------------------------------------- public bool SearchIncludeNumeric { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets the filter used for inclusion of tag info /// </summary> /// <remarks> /// Defaults to "" /// </remarks> /// ----------------------------------------------------------------------------- public string SearchIncludedTagInfoFilter { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets the maximum Search Word length to index /// </summary> /// <remarks>Defaults to 3</remarks> /// ----------------------------------------------------------------------------- public int SearchMaxWordlLength { get; internal set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets the minum Search Word length to index /// </summary> /// <remarks>Defaults to 3</remarks> /// ----------------------------------------------------------------------------- public int SearchMinWordlLength { get; internal set; } public bool SSLEnabled { get; internal set; } public bool SSLEnforced { get; internal set; } public string SSLURL { get; internal set; } public string STDURL { get; internal set; } public int SMTPConnectionLimit { get; internal set; } public int SMTPMaxIdleTime { get; internal set; } #endregion #region Public Properties public CacheLevel Cacheability { get { return CacheLevel.fullyCacheable; } } public bool ControlPanelVisible { get { var setting = Convert.ToString(Personalization.GetProfile("Usability", "ControlPanelVisible" + PortalId)); return String.IsNullOrEmpty(setting) ? DefaultControlPanelVisibility : Convert.ToBoolean(setting); } } public static PortalSettings Current { get { return PortalController.Instance.GetCurrentPortalSettings(); } } public string DefaultPortalAlias { get { foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(PortalId).Where(alias => alias.IsPrimary)) { return alias.HTTPAlias; } return String.Empty; } } public PortalAliasMapping PortalAliasMappingMode { get { return PortalSettingsController.Instance().GetPortalAliasMappingMode(PortalId); } } /// <summary>Gets the currently logged in user identifier.</summary> /// <value>The user identifier.</value> public int UserId { get { if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) { return UserInfo.UserID; } return Null.NullInteger; } } /// <summary>Gets the currently logged in user.</summary> /// <value>The current user information.</value> public UserInfo UserInfo { get { return UserController.Instance.GetCurrentUserInfo(); } } public Mode UserMode { get { Mode mode; if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) { mode = DefaultControlPanelMode; string setting = Convert.ToString(Personalization.GetProfile("Usability", "UserMode" + PortalId)); switch (setting.ToUpper()) { case "VIEW": mode = Mode.View; break; case "EDIT": mode = Mode.Edit; break; case "LAYOUT": mode = Mode.Layout; break; } } else { mode = Mode.View; } return mode; } } /// <summary> /// Get a value indicating whether the current portal is in maintenance mode (if either this specific portal or the entire instance is locked). If locked, any actions which update the database should be disabled. /// </summary> public bool IsLocked { get { return IsThisPortalLocked || Host.Host.IsLocked; } } /// <summary> /// Get a value indicating whether the current portal is in maintenance mode (note, the entire instance may still be locked, this only indicates whether this portal is specifically locked). If locked, any actions which update the database should be disabled. /// </summary> public bool IsThisPortalLocked { get { return PortalController.GetPortalSettingAsBoolean("IsLocked", PortalId, false); } } public TimeZoneInfo TimeZone { get; set; } = TimeZoneInfo.Local; public string PageHeadText { get { // For New Install string pageHead = "<meta content=\"text/html; charset=UTF-8\" http-equiv=\"Content-Type\" />"; string setting; if (PortalController.Instance.GetPortalSettings(PortalId).TryGetValue("PageHeadText", out setting)) { // Hack to store empty string portalsetting with non empty default value pageHead = (setting == "false") ? "" : setting; } return pageHead; } } /* * add <a name="[moduleid]"></a> on the top of the module * * Desactivate this remove the html5 compatibility warnings * (and make the output smaller) * */ public bool InjectModuleHyperLink { get { return PortalController.GetPortalSettingAsBoolean("InjectModuleHyperLink", PortalId, true); } } /* * generates a : Page.Response.AddHeader("X-UA-Compatible", ""); * */ public string AddCompatibleHttpHeader { get { string CompatibleHttpHeader = "IE=edge"; string setting; if (PortalController.Instance.GetPortalSettings(PortalId).TryGetValue("AddCompatibleHttpHeader", out setting)) { // Hack to store empty string portalsetting with non empty default value CompatibleHttpHeader = (setting == "false") ? "" : setting; } return CompatibleHttpHeader; } } /* * add a cachebuster parameter to generated file URI's * * of the form ver=[file timestame] ie ver=2015-02-17-162255-735 * */ public bool AddCachebusterToResourceUris { get { return PortalController.GetPortalSettingAsBoolean("AddCachebusterToResourceUris", PortalId, true); } } /// <summary> /// If this is true, then regular users can't send message to specific user/group. /// </summary> public bool DisablePrivateMessage { get { return PortalController.GetPortalSetting("DisablePrivateMessage", PortalId, "N") == "Y"; } } /// <summary> /// If true then all users will be pushed through the data consent workflow /// </summary> public bool DataConsentActive { get; internal set; } /// <summary> /// Last time the terms and conditions have been changed. This will determine if the user needs to /// reconsent or not. Legally once the terms have changed, users need to sign again. This value is set /// by the "reset consent" button on the UI. /// </summary> public DateTime DataConsentTermsLastChange { get; internal set; } /// <summary> /// If set this is a tab id of a page where the user will be redirected to for consent. If not set then /// the platform's default logic is used. /// </summary> public int DataConsentConsentRedirect { get; internal set; } /// <summary> /// Sets what should happen to the user account if a user has been deleted. This is important as /// under certain circumstances you may be required by law to destroy the user's data within a /// certain timeframe after a user has requested deletion. /// </summary> public UserDeleteAction DataConsentUserDeleteAction { get; internal set; } /// <summary> /// Sets the delay time (in conjunction with DataConsentDelayMeasurement) for the DataConsentUserDeleteAction /// </summary> public int DataConsentDelay { get; internal set; } /// <summary> /// Units for DataConsentDelay /// </summary> public string DataConsentDelayMeasurement { get; internal set; } #endregion #region IPropertyAccess Members public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { var outputFormat = string.Empty; if (format == string.Empty) { outputFormat = "g"; } var lowerPropertyName = propertyName.ToLowerInvariant(); if (accessLevel == Scope.NoSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } propertyNotFound = true; var result = string.Empty; var isPublic = true; switch (lowerPropertyName) { case "url": propertyNotFound = false; result = PropertyAccess.FormatString(PortalAlias.HTTPAlias, format); break; case "fullurl": //return portal alias with protocol propertyNotFound = false; result = PropertyAccess.FormatString(Globals.AddHTTP(PortalAlias.HTTPAlias), format); break; case "passwordreminderurl": //if regsiter page defined in portal settings, then get that page url, otherwise return home page. propertyNotFound = false; var reminderUrl = Globals.AddHTTP(PortalAlias.HTTPAlias); if (RegisterTabId > Null.NullInteger) { reminderUrl = Globals.RegisterURL(string.Empty, string.Empty); } result = PropertyAccess.FormatString(reminderUrl, format); break; case "portalid": propertyNotFound = false; result = (PortalId.ToString(outputFormat, formatProvider)); break; case "portalname": propertyNotFound = false; result = PropertyAccess.FormatString(PortalName, format); break; case "homedirectory": propertyNotFound = false; result = PropertyAccess.FormatString(HomeDirectory, format); break; case "homedirectorymappath": isPublic = false; propertyNotFound = false; result = PropertyAccess.FormatString(HomeDirectoryMapPath, format); break; case "logofile": propertyNotFound = false; result = PropertyAccess.FormatString(LogoFile, format); break; case "footertext": propertyNotFound = false; var footerText = FooterText.Replace("[year]", DateTime.Now.Year.ToString()); result = PropertyAccess.FormatString(footerText, format); break; case "expirydate": isPublic = false; propertyNotFound = false; result = (ExpiryDate.ToString(outputFormat, formatProvider)); break; case "userregistration": isPublic = false; propertyNotFound = false; result = (UserRegistration.ToString(outputFormat, formatProvider)); break; case "banneradvertising": isPublic = false; propertyNotFound = false; result = (BannerAdvertising.ToString(outputFormat, formatProvider)); break; case "currency": propertyNotFound = false; result = PropertyAccess.FormatString(Currency, format); break; case "administratorid": isPublic = false; propertyNotFound = false; result = (AdministratorId.ToString(outputFormat, formatProvider)); break; case "email": propertyNotFound = false; result = PropertyAccess.FormatString(Email, format); break; case "hostfee": isPublic = false; propertyNotFound = false; result = (HostFee.ToString(outputFormat, formatProvider)); break; case "hostspace": isPublic = false; propertyNotFound = false; result = (HostSpace.ToString(outputFormat, formatProvider)); break; case "pagequota": isPublic = false; propertyNotFound = false; result = (PageQuota.ToString(outputFormat, formatProvider)); break; case "userquota": isPublic = false; propertyNotFound = false; result = (UserQuota.ToString(outputFormat, formatProvider)); break; case "administratorroleid": isPublic = false; propertyNotFound = false; result = (AdministratorRoleId.ToString(outputFormat, formatProvider)); break; case "administratorrolename": isPublic = false; propertyNotFound = false; result = PropertyAccess.FormatString(AdministratorRoleName, format); break; case "registeredroleid": isPublic = false; propertyNotFound = false; result = (RegisteredRoleId.ToString(outputFormat, formatProvider)); break; case "registeredrolename": isPublic = false; propertyNotFound = false; result = PropertyAccess.FormatString(RegisteredRoleName, format); break; case "description": propertyNotFound = false; result = PropertyAccess.FormatString(Description, format); break; case "keywords": propertyNotFound = false; result = PropertyAccess.FormatString(KeyWords, format); break; case "backgroundfile": propertyNotFound = false; result = PropertyAccess.FormatString(BackgroundFile, format); break; case "admintabid": isPublic = false; propertyNotFound = false; result = AdminTabId.ToString(outputFormat, formatProvider); break; case "supertabid": isPublic = false; propertyNotFound = false; result = SuperTabId.ToString(outputFormat, formatProvider); break; case "splashtabid": isPublic = false; propertyNotFound = false; result = SplashTabId.ToString(outputFormat, formatProvider); break; case "hometabid": isPublic = false; propertyNotFound = false; result = HomeTabId.ToString(outputFormat, formatProvider); break; case "logintabid": isPublic = false; propertyNotFound = false; result = LoginTabId.ToString(outputFormat, formatProvider); break; case "registertabid": isPublic = false; propertyNotFound = false; result = RegisterTabId.ToString(outputFormat, formatProvider); break; case "usertabid": isPublic = false; propertyNotFound = false; result = UserTabId.ToString(outputFormat, formatProvider); break; case "defaultlanguage": propertyNotFound = false; result = PropertyAccess.FormatString(DefaultLanguage, format); break; case "users": isPublic = false; propertyNotFound = false; result = Users.ToString(outputFormat, formatProvider); break; case "pages": isPublic = false; propertyNotFound = false; result = Pages.ToString(outputFormat, formatProvider); break; case "contentvisible": isPublic = false; break; case "controlpanelvisible": isPublic = false; propertyNotFound = false; result = PropertyAccess.Boolean2LocalizedYesNo(ControlPanelVisible, formatProvider); break; } if (!isPublic && accessLevel != Scope.Debug) { propertyNotFound = true; result = PropertyAccess.ContentLocked; } return result; } #endregion #region Public Methods public PortalSettings Clone() { return (PortalSettings)MemberwiseClone(); } #endregion } }
38.169623
267
0.476691
[ "MIT" ]
pmsereno/Dnn.Platform
DNN Platform/Library/Entities/Portals/PortalSettings.cs
34,431
C#
/* _BEGIN_TEMPLATE_ { "id": "AT_042t", "name": [ "刃牙德鲁伊", "Druid of the Saber" ], "text": [ "<b>冲锋</b>", "<b>Charge</b>" ], "cardClass": "DRUID", "type": "MINION", "cost": 2, "rarity": "COMMON", "set": "TGT", "collectible": null, "dbfId": 2784 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_AT_042t : SimTemplate //* Sabertooth Lion { //Charge } }
13.966667
55
0.520286
[ "MIT" ]
chi-rei-den/Silverfish
cards/TGT/AT/Sim_AT_042t.cs
433
C#
#region license //Original Source Code: https://github.com/abpframework/abp //Permissions of this copyleft license are conditioned on making available //complete source code of licensed works and modifications under the same license //or the GNU GPLv3. Copyright and license notices must be preserved. //Contributors provide an express grant of patent rights. However, a larger //work using the licensed work through interfaces provided by the licensed //work may be distributed under different terms and without source code for //the larger work. //You may obtain a copy of the License at //https://www.gnu.org/licenses/lgpl-3.0.en.html //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #endregion using System; namespace RCommon.BackgroundJobs { public interface IBackgroundJobSerializer { string Serialize(object obj); object Deserialize(string value, Type type); } }
35.727273
81
0.770992
[ "Apache-2.0" ]
Reactor2Team/RCommon
Src/RCommon.BackgroundJobs/IBackgroundJobSerializer.cs
1,181
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Merged { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Datatype.Lang; using Ca.Infoway.Messagebuilder.Domainvalue; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Coct_mt240003ca; using System; /** * <summary>PORX_MT980030CA.Location: *b:dispensed at</summary> * * <p>Indicates the facility where the dispense event was * performed</p> <p>A_DetectedMedicationIssue</p> <p>Used for * contacting the pharmacy or pharmacist involved in the * dispense.</p><p>The association is marked as populated * because it may be masked.</p> <p>Used for contacting the * pharmacy or pharmacist involved in the dispense.</p><p>The * association is marked as populated because it may be * masked.</p> COMT_MT300003CA.Location: *c:recorded at * <p>Indicates the facility/location where the patient note * was recorded.</p> <p>Important for performing follow-up and * is therefore mandatory.</p> PORX_MT980020CA.Location: * *b:dispensed at <p>Indicates the facility where the * implicated dispense event was performed</p> * <p>A_DetectedMedicationIssue</p> <p>Used for contacting the * pharmacy or pharmacist involved in the dispense.</p><p>The * association is only marked as 'populated' because it may be * masked.</p> <p>Used for contacting the pharmacy or * pharmacist involved in the dispense.</p><p>The association * is only marked as 'populated' because it may be masked.</p> * PORX_MT060060CA.Location2: *c:targeted to pharmacy * <p>Indicates the pharmacy to which the prescription has been * directed or which has currently assumed responsibility for * dispensing the prescription.</p> <p>Allows prescriptions to * be directed on the request of the patient or by legal * requirement. Also allows indication of which pharmacy is the * current 'custodian' of the prescription.</p><p>This should * always be known or should have an explicit null flavor of * 'NA' (non-assigned) or 'UNK' (paper prescription). Thus the * association is 'populated'.</p> <p>Allows prescriptions to * be directed on the request of the patient or by legal * requirement. Also allows indication of which pharmacy is the * current 'custodian' of the prescription.</p><p>This should * always be known or should have an explicit null flavor of * 'NA' (non-assigned) or 'UNK' (paper prescription). Thus the * association is 'populated'.</p> PORX_MT030040CA.Location2: * *c:targeted to pharmacy <p>Indicates the pharmacy to which * the prescription has been directed or which has currently * assumed responsibility for dispensing the prescription.</p> * <p>Allows prescriptions to be directed on the request of the * patient or by legal requirement. Also allows indication of * which pharmacy is the current 'custodian' of the * prescription.</p><p>This should always be known or should * have an explicit null flavor of 'NA' (non-assigned) or 'UNK' * (paper prescription). Thus the association is * 'populated'.</p> <p>Allows prescriptions to be directed on * the request of the patient or by legal requirement. Also * allows indication of which pharmacy is the current * 'custodian' of the prescription.</p><p>This should always be * known or should have an explicit null flavor of 'NA' * (non-assigned) or 'UNK' (paper prescription). Thus the * association is 'populated'.</p> PORX_MT060190CA.Location2: * *recorded at <p>Identification of the service delivery * location where the other active medication was recorded</p> * <p>Used for follow-up communication on the dispensed * product, and therefore mandatory.</p> * PORX_MT060190CA.Location4: *prescribed at <p>Indicates the * clinic or facility which originally issued the * prescription.</p> <p>Identifies where paper records are * likely located for follow-up. This is marked as 'populated' * because it won't always be known for 'inferred * prescriptions.</p> PORX_MT060190CA.Location3: *c:targeted to * pharmacy <p>Indicates the pharmacy to which the prescription * has been directed or which has currently assumed * responsibility for dispensing the prescription.</p> * <p>Allows prescriptions to be directed on the request of the * patient or by legal requirement. Also allows indication of * which pharmacy is the current 'custodian' of the * prescription.</p><p>This should always be known or should * have an explicit null flavor of 'NA' (non-assigned) or 'UNK' * (paper prescription). Thus the association is * 'populated'.</p> <p>Allows prescriptions to be directed on * the request of the patient or by legal requirement. Also * allows indication of which pharmacy is the current * 'custodian' of the prescription.</p><p>This should always be * known or should have an explicit null flavor of 'NA' * (non-assigned) or 'UNK' (paper prescription). Thus the * association is 'populated'.</p> PORX_MT980010CA.Location: * *b:dispensed at <p>Indicates the facility where the dispense * event was performed</p> <p>A_DetectedMedicationIssue</p> * <p>Used for contacting the pharmacy or pharmacist involved * in the dispense.</p><p>The association is marked as * populated because it may be masked.</p> <p>Used for * contacting the pharmacy or pharmacist involved in the * dispense.</p><p>The association is marked as populated * because it may be masked.</p> REPC_MT000010CA.Location: * *g:recorded at <p>Indicates the service delivery location * where the medical condition was recorded.</p> <p>Indicates * where records are likely kept for follow-up. May also be * useful in understanding the context in which the medical * condition recorded.</p><p>The location of entry should * always exist, and is therefore mandatory.</p> <p>Indicates * where records are likely kept for follow-up. May also be * useful in understanding the context in which the medical * condition recorded.</p><p>The location of entry should * always exist, and is therefore mandatory.</p> * REPC_MT000007CA.Location: *recorded at <p>Indicates the * service delivery location where the medical condition was * recorded.</p> <p>Indicates where records are likely kept for * follow-up. May also be useful in understanding the context * in which the medical condition was recorded. The location of * entry should always be known, and is therefore * mandatory.</p> PORX_MT060340CA.Location: *d:dispensed from * Service Delivery Location <p>Indicates the facility/location * where the dispensing was performed.</p> <p>Important for * performing follow-up and therefore mandatory.</p> * MCAI_MT700221CA.Location: *a1:created at <p>Indicates the * facility where the event occurred.</p> <p>Indicates where * paper records may be located, and may be important to * determining authorization. The association is therefore * mandatory.</p> REPC_MT000009CA.Location: *i:recorded at * <p>Indicates the service delivery location where the allergy * was recorded.</p> <p>Indicates where records are likely kept * for follow-up. May also be useful in understanding the * context in which the allergy/intolerance was recorded. The * location of entry should always be known, and is therefore * mandatory.</p> MCAI_MT700223CA.Location: *a1:created at * <p>Indicates the facility where the event occurred.</p> * <p>Indicates where paper records may be located, and may be * important to determining authorization. The association is * therefore mandatory.</p> PORX_MT060160CA.Location: * *d:dispensed from <p>Indicates the facility/location where * the dispensing was performed.</p> <p>Important for * performing follow-up and therefore mandatory.</p> * REPC_MT000005CA.Location: *i:recorded at <p>Indicates the * service delivery location where the allergy was * recorded.</p> <p>Indicates where records are likely kept for * follow-up. May also be useful in understanding the context * in which the allergy/intolerance was recorded. The location * of entry should always be known, and is therefore * mandatory.</p> PORX_MT010120CA.Location2: *c:targeted to * pharmacy <p>Indicates the pharmacy to which the prescription * has been directed or which has currently assumed * responsibility for dispensing the prescription.</p> * <p>Allows prescriptions to be directed on the request of the * patient or by legal requirement. Also allows indication of * which pharmacy is the current 'custodian' of the * prescription.</p><p>This should always be known or should * have an explicit null flavor of 'NA' (non-assigned) or 'UNK' * (paper prescription). Thus the association is * 'populated'.</p> <p>Allows prescriptions to be directed on * the request of the patient or by legal requirement. Also * allows indication of which pharmacy is the current * 'custodian' of the prescription.</p><p>This should always be * known or should have an explicit null flavor of 'NA' * (non-assigned) or 'UNK' (paper prescription). Thus the * association is 'populated'.</p> PORX_MT060020CA.Location: * *dispensed from <p>Identification of the service delivery * location where the device was dispensed.</p> <p>Used for * follow-up communication on the dispensed product, and * therefore mandatory.</p> PORX_MT060210CA.Location2: * *c:recorded at <p>Indicates the facility/location where the * other medication was recorded.</p> <p>Important for * p * ... [rest of documentation truncated due to excessive length] */ [Hl7PartTypeMappingAttribute(new string[] {"COMT_MT300003CA.Location","MCAI_MT700210CA.Location","MCAI_MT700221CA.Location","MCAI_MT700223CA.Location","POIZ_MT060150CA.Location","PORX_MT010110CA.Location2","PORX_MT010120CA.Location2","PORX_MT010140CA.Location","PORX_MT030040CA.Location","PORX_MT030040CA.Location2","PORX_MT060010CA.Location","PORX_MT060020CA.Location","PORX_MT060040CA.Location","PORX_MT060040CA.Location2","PORX_MT060040CA.Location3","PORX_MT060040CA.Location4","PORX_MT060060CA.Location2","PORX_MT060090CA.Location","PORX_MT060100CA.Location","PORX_MT060160CA.Location","PORX_MT060160CA.Location2","PORX_MT060160CA.Location3","PORX_MT060160CA.Location4","PORX_MT060160CA.Location5","PORX_MT060190CA.Location2","PORX_MT060190CA.Location3","PORX_MT060190CA.Location4","PORX_MT060210CA.Location2","PORX_MT060340CA.Location","PORX_MT060340CA.Location2","PORX_MT060340CA.Location3","PORX_MT060340CA.Location4","PORX_MT980010CA.Location","PORX_MT980020CA.Location","PORX_MT980030CA.Location","QUQI_MT020000CA.Location","REPC_MT000005CA.Location","REPC_MT000006CA.Location","REPC_MT000007CA.Location","REPC_MT000009CA.Location","REPC_MT000010CA.Location","REPC_MT100001CA.Location","REPC_MT100002CA.Location"})] public class RecordedAt : MessagePartBean { private Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Coct_mt240003ca.ServiceLocation serviceDeliveryLocation; private CV substitutionConditionCode; private IVL<TS, Interval<PlatformDate>> time; public RecordedAt() { this.substitutionConditionCode = new CVImpl(); this.time = new IVLImpl<TS, Interval<PlatformDate>>(); } /** * <summary>Un-merged Business Name: (no business name * specified)</summary> * * <remarks>Relationship: * PORX_MT980030CA.Location.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: RecordedAt Relationship: * COMT_MT300003CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) <div>Indicates the * service delivery location where the</div> <div>note was * recorded.</div> Un-merged Business Name: DispensedAt * Relationship: * PORX_MT980020CA.Location.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) <div>Indicates the * facility where the implicated</div> <div>dispense event was * performed.</div> Un-merged Business Name: (no business name * specified) Relationship: * PORX_MT060060CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT030040CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060190CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060190CA.Location4.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060190CA.Location3.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT980010CA.Location.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * REPC_MT000007CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * REPC_MT000010CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060340CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * MCAI_MT700221CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: RecordedAt Relationship: * REPC_MT000009CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) <div>Indicates the * service delivery location where the&nbsp;allergy was * recorded.&nbsp;</div> Un-merged Business Name: (no business * name specified) Relationship: * MCAI_MT700223CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060160CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: RecordedAt Relationship: * REPC_MT000005CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) <p>&nbsp;Indicates * the service delivery location where the&nbsp;allergy was * recorded.</p> Un-merged Business Name: (no business name * specified) Relationship: * PORX_MT010120CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060020CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060210CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT010110CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * REPC_MT000006CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: CreatedAt Relationship: * MCAI_MT700210CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) <p>&nbsp;Indicates * the location where the event occurred.</p> Un-merged * Business Name: (no business name specified) Relationship: * PORX_MT060100CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * REPC_MT100001CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060090CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060160CA.Location5.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060160CA.Location4.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * POIZ_MT060150CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060160CA.Location3.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060010CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060160CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: CreatedAt Relationship: * QUQI_MT020000CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) <p>&nbsp;Indicates * the service delivery location where the</p> <div>query * occurred.</div> Un-merged Business Name: (no business name * specified) Relationship: * PORX_MT060040CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060040CA.Location4.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060040CA.Location3.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT030040CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060340CA.Location4.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060040CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060340CA.Location2.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT060340CA.Location3.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: (no business name specified) Relationship: * PORX_MT010140CA.Location.serviceDeliveryLocation * Conformance/Cardinality: POPULATED (1) Un-merged Business * Name: RecordedAt Relationship: * REPC_MT100002CA.Location.serviceDeliveryLocation * Conformance/Cardinality: MANDATORY (1) <div>Indicates the * service delivery location where the</div> <p>patient * measurement was recorded.&nbsp;</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"serviceDeliveryLocation"})] public Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Coct_mt240003ca.ServiceLocation ServiceDeliveryLocation { get { return this.serviceDeliveryLocation; } set { this.serviceDeliveryLocation = value; } } /** * <summary>Un-merged Business Name: * DispenseFacilityNotAssignableIndicator</summary> * * <remarks>Relationship: * PORX_MT060060CA.Location2.substitutionConditionCode * Conformance/Cardinality: REQUIRED (0-1) <p>Indicates whether * a dispenser to whom the prescription is targeted is a * mandated or patient-preferred pharmacy.</p> <p>Influences * whether the prescription may be transferred to a service * delivery location other than the targeted dispenser.</p> * Un-merged Business Name: * DispenseFacilityNotAssignableIndicator Relationship: * PORX_MT030040CA.Location2.substitutionConditionCode * Conformance/Cardinality: REQUIRED (0-1) <p>Indicates a * 'hard' or 'soft' assignment of dispensing priviledged to the * targetted facility.</p><p>'Hard' assignment (mandated * facility) indicates that the prescription can be dispensed * only at that facility.</p><p>'Soft' assignment (usually as a * patient directive) indicates that the prescription may be * dispensed at facilities other than the targeted * facility.</p> <p>Indicates a 'hard' or 'soft' assignment of * dispensing priviledged to the targetted * facility.</p><p>'Hard' assignment (mandated facility) * indicates that the prescription can be dispensed only at * that facility.</p><p>'Soft' assignment (usually as a patient * directive) indicates that the prescription may be dispensed * at facilities other than the targeted facility.</p> * <p>Indicates a 'hard' or 'soft' assignment of dispensing * priviledged to the targetted facility.</p><p>'Hard' * assignment (mandated facility) indicates that the * prescription can be dispensed only at that * facility.</p><p>'Soft' assignment (usually as a patient * directive) indicates that the prescription may be dispensed * at facilities other than the targeted facility.</p> * <p>Influences whether the prescription may be transferred to * a service delivery location other than the targeted * dispenser.</p> Un-merged Business Name: * AssignedFacilityNotReassignableIndicator Relationship: * PORX_MT060340CA.Location4.substitutionConditionCode * Conformance/Cardinality: REQUIRED (0-1) <p>Indicates whether * a dispenser to whom the prescription is targeted is a * mandated or patient-preferred pharmacy.</p> <p>Influences * whether the prescription may be transferred to a service * delivery location other than the targeted dispenser.</p> * Un-merged Business Name: * AssignedFacilityNotReassignableIndicator Relationship: * PORX_MT060160CA.Location5.substitutionConditionCode * Conformance/Cardinality: REQUIRED (0-1) <p>Indicates whether * a dispenser to whom the prescription is targeted is a * mandated or patient-preferred pharmacy.</p> <p>Influences * whether the prescription may be transferred to a service * delivery location other than the targeted dispenser.</p> * Un-merged Business Name: * DispenseFacilityNotAssignableIndicator Relationship: * PORX_MT060190CA.Location3.substitutionConditionCode * Conformance/Cardinality: REQUIRED (0-1) <p>Indicates a * 'hard' or 'soft' assignment of dispensing priviledged to the * targeted facility.</p><p>'Hard' assignment (mandated * facility) indicates that the prescription can be dispensed * only at that facility.</p><p>'Soft' assignment (usually as a * patient directive) indicates that the prescription may be * dispensed at facilities other than the targeted * facility.</p> <p>Indicates a 'hard' or 'soft' assignment of * dispensing priviledged to the targeted * facility.</p><p>'Hard' assignment (mandated facility) * indicates that the prescription can be dispensed only at * that facility.</p><p>'Soft' assignment (usually as a patient * directive) indicates that the prescription may be dispensed * at facilities other than the targeted facility.</p> * <p>Indicates a 'hard' or 'soft' assignment of dispensing * priviledged to the targeted facility.</p><p>'Hard' * assignment (mandated facility) indicates that the * prescription can be dispensed only at that * facility.</p><p>'Soft' assignment (usually as a patient * directive) indicates that the prescription may be dispensed * at facilities other than the targeted facility.</p> * <p>Influences whether the prescription may be transferred to * a service delivery location other than the targeted * dispenser.</p> Un-merged Business Name: * DispenseFacilityNotReassignable Relationship: * PORX_MT010120CA.Location2.substitutionConditionCode * Conformance/Cardinality: REQUIRED (0-1) <p>Indicates a * 'hard' or 'soft' assignment of dispensing priviledged to the * targetted facility.</p><p>'Hard' assignment (mandated * facility) indicates that the prescription can be dispensed * only at that facility.</p><p>'Soft' assignment (usually as a * patient directive) indicates that the prescription may be * dispensed at facilities other than the targeted * facility.</p> <p>Indicates a 'hard' or 'soft' assignment of * dispensing priviledged to the targetted * facility.</p><p>'Hard' assignment (mandated facility) * indicates that the prescription can be dispensed only at * that facility.</p><p>'Soft' assignment (usually as a patient * directive) indicates that the prescription may be dispensed * at facilities other than the targeted facility.</p> * <p>Indicates a 'hard' or 'soft' assignment of dispensing * priviledged to the targetted facility.</p><p>'Hard' * assignment (mandated facility) indicates that the * prescription can be dispensed only at that * facility.</p><p>'Soft' assignment (usually as a patient * directive) indicates that the prescription may be dispensed * at facilities other than the targeted facility.</p> * <p>Influences whether the prescription may be transferred to * a service delivery location other than the targeted * dispenser.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"substitutionConditionCode"})] public x_SubstitutionConditionNoneOrUnconditional SubstitutionConditionCode { get { return (x_SubstitutionConditionNoneOrUnconditional) this.substitutionConditionCode.Value; } set { this.substitutionConditionCode.Value = value; } } /** * <summary>Business Name: ToBePickedUpWhen</summary> * * <remarks>Un-merged Business Name: ToBePickedUpWhen * Relationship: PORX_MT010110CA.Location2.time * Conformance/Cardinality: REQUIRED (0-1) <p>The date and time * on which the dispense is expected to be picked up.</p> * <p>Allows a prescriber to indicate to the targeted pharmacy, * when patient will be expecting to pick up the dispensed * device.</p> Un-merged Business Name: ToBePickedUpWhen * Relationship: PORX_MT060040CA.Location4.time * Conformance/Cardinality: REQUIRED (0-1) <p>The date and time * on which the dispense is expected to be picked up.</p> * <p>Allows a prescriber to indicate to the targeted pharmacy, * when patient will be expecting to pick up the dispensed * device.</p> Un-merged Business Name: ToBePickedUpWhen * Relationship: PORX_MT060340CA.Location4.time * Conformance/Cardinality: REQUIRED (0-1) <p>The date and time * on which the dispense is expected to be picked up.</p> * <p>Allows a prescriber to indicate to the targeted pharmacy, * when patient will be expecting to pick up the dispensed * medication.</p> Un-merged Business Name: ToBePickedUpWhen * Relationship: PORX_MT060160CA.Location5.time * Conformance/Cardinality: REQUIRED (0-1) <p>The date and time * on which the dispense is expected to be picked up.</p> * <p>Allows a prescriber to indicate to the targeted pharmacy, * when patient will be expecting to pick up the dispensed * medication.</p> Un-merged Business Name: ToBePickedUpWhen * Relationship: PORX_MT010120CA.Location2.time * Conformance/Cardinality: REQUIRED (0-1) <p>The date and time * on which the dispense is expected to be picked up.</p> * <p>Allows a prescriber to indicate to the targeted pharmacy, * when patient will be expecting to pick up the dispensed * medication.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"time"})] public Interval<PlatformDate> Time { get { return this.time.Value; } set { this.time.Value = value; } } } }
63.345098
1,229
0.67749
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-sk-v01_r04_3/Main/Ca/Infoway/Messagebuilder/Model/Sk_cerx_v01_r04_2/Merged/RecordedAt.cs
32,306
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace nslookup2csv.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.7.0.0")] public sealed partial class StringFormat : global::System.Configuration.ApplicationSettingsBase { private static StringFormat defaultInstance = ((StringFormat)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new StringFormat()))); public static StringFormat Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("==============================\r\n nslookup2csv\r\n Copyright (C) 2018 mamori" + "017\r\n==============================")] public string Title { get { return ((string)(this["Title"])); } set { this["Title"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Parameter error")] public string ParameterError { get { return ((string)(this["ParameterError"])); } set { this["ParameterError"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Target : {0}")] public string Target { get { return ((string)(this["Target"])); } set { this["Target"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Finish")] public string Finish { get { return ((string)(this["Finish"])); } set { this["Finish"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Output : {0}")] public string Output { get { return ((string)(this["Output"])); } set { this["Output"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute(".\\{0}.csv\"")] public string FileName { get { return ((string)(this["FileName"])); } set { this["FileName"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Target\\tServer\\tAddress\\tName\\tAddress")] public string OutputHeader { get { return ((string)(this["OutputHeader"])); } set { this["OutputHeader"] = value; } } } }
37.535714
158
0.540676
[ "MIT" ]
mamori017/nslookup2csv
nslookup2csv/Properties/StringFormat.Designer.cs
4,378
C#
using Simplic.AdaptiveTesting; using Simplic.CommandShell; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SAT.Shell { /// <summary> /// Class which contains all commands for testing purpose /// </summary> public static class TestingCommands { #region [Test] [ParameterDescription("path", true, "Path to the scripts, containg all test information and configurtion")] [CommandDescription("Execute a test-script and create a report")] public static string Test(string command, CommandShellParameterCollection parameter) { string path = parameter.GetParameterValueAsString("path"); if (File.Exists(path)) { Console.WriteLine("Execute test-file: {0}", path); var process = new Simplic.AdaptiveTesting.TestProcess(File.ReadAllText(path), new MessageListener()); process.Start(); } else { using (var _error = new ConsoleError()) { Console.WriteLine("Could not find configuration '{0}'", path); } } return ""; } #endregion } /// <summary> /// Listener for message output /// </summary> public class MessageListener : IListener { /// <summary> /// Print error /// </summary> /// <param name="area">Area where the error occured</param> /// <param name="message">Detail message text</param> public void Error(string area, string message) { using (ConsoleError _error = new ConsoleError()) { Write(area, message); } } /// <summary> /// Write success message /// </summary> /// <param name="area"></param> /// <param name="message"></param> public void Success(string area, string message) { using (ConsoleSuccess _success = new ConsoleSuccess()) { Write(area, message); } } /// <summary> /// Write warning /// </summary> /// <param name="area"></param> /// <param name="message"></param> public void Warning(string area, string message) { using (ConsoleWarning _success = new ConsoleWarning()) { Write(area, message); } } /// <summary> /// Write simple message /// </summary> /// <param name="area"></param> /// <param name="message"></param> public void Write(string area, string message) { Console.WriteLine((area ?? "NULL") + "-> " + (message ?? "NULL")); } } }
29.561224
117
0.527787
[ "MIT" ]
simplicbe/Simplic.AdaptiveTesting
src/SAT.Shell/Commands/TestingCommands.cs
2,899
C#
using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace application.API.Models { public class JwtIssuerOptions { /// <summary> /// 4.1.1. "iss" (Issuer) Claim - The "iss" (issuer) claim identifies the principal that issued the JWT. /// </summary> public string Issuer { get; set; } /// <summary> /// 4.1.2. "sub" (Subject) Claim - The "sub" (subject) claim identifies the principal that is the subject of the JWT. /// </summary> public string Subject { get; set; } /// <summary> /// 4.1.3. "aud" (Audience) Claim - The "aud" (audience) claim identifies the recipients that the JWT is intended for. /// </summary> public string Audience { get; set; } /// <summary> /// 4.1.4. "exp" (Expiration Time) Claim - The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. /// </summary> public DateTime Expiration => IssuedAt.Add(ValidFor); /// <summary> /// 4.1.5. "nbf" (Not Before) Claim - The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. /// </summary> public DateTime NotBefore => DateTime.UtcNow; /// <summary> /// 4.1.6. "iat" (Issued At) Claim - The "iat" (issued at) claim identifies the time at which the JWT was issued. /// </summary> public DateTime IssuedAt => DateTime.UtcNow; /// <summary> /// Set the timespan the token will be valid for (default is 120 min) /// </summary> public TimeSpan ValidFor { get; set; } = TimeSpan.FromMinutes(1500); /// <summary> /// "jti" (JWT ID) Claim (default ID is a GUID) /// </summary> public Func<Task<string>> JtiGenerator => () => Task.FromResult(Guid.NewGuid().ToString()); /// <summary> /// The signing key to use when generating tokens. /// </summary> public SigningCredentials SigningCredentials { get; set; } } }
37.423729
179
0.595109
[ "MIT" ]
sebash1992/MakingSense
application.API/Models/JwtIssuerOptions.cs
2,210
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestModels.InheritanceModel; using Xunit; using Xunit.Abstractions; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query { public class IncompleteMappingInheritanceQuerySqlServerTest : InheritanceRelationalQueryTestBase< IncompleteMappingInheritanceQuerySqlServerFixture> { #pragma warning disable IDE0060 // Remove unused parameter public IncompleteMappingInheritanceQuerySqlServerTest( IncompleteMappingInheritanceQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper) #pragma warning restore IDE0060 // Remove unused parameter : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); //Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } [ConditionalFact] public virtual void Common_property_shares_column() { using var context = CreateContext(); var liltType = context.Model.FindEntityType(typeof(Lilt)); var cokeType = context.Model.FindEntityType(typeof(Coke)); var teaType = context.Model.FindEntityType(typeof(Tea)); Assert.Equal("SugarGrams", cokeType.FindProperty("SugarGrams").GetColumnBaseName()); Assert.Equal("CaffeineGrams", cokeType.FindProperty("CaffeineGrams").GetColumnBaseName()); Assert.Equal("CokeCO2", cokeType.FindProperty("Carbonation").GetColumnBaseName()); Assert.Equal("SugarGrams", liltType.FindProperty("SugarGrams").GetColumnBaseName()); Assert.Equal("LiltCO2", liltType.FindProperty("Carbonation").GetColumnBaseName()); Assert.Equal("CaffeineGrams", teaType.FindProperty("CaffeineGrams").GetColumnBaseName()); Assert.Equal("HasMilk", teaType.FindProperty("HasMilk").GetColumnBaseName()); } public override async Task Can_query_when_shared_column(bool async) { await base.Can_query_when_shared_column(async); AssertSql( @"SELECT TOP(2) [d].[Id], [d].[Discriminator], [d].[CaffeineGrams], [d].[CokeCO2], [d].[SugarGrams] FROM [Drinks] AS [d] WHERE [d].[Discriminator] = N'Coke'", // @"SELECT TOP(2) [d].[Id], [d].[Discriminator], [d].[LiltCO2], [d].[SugarGrams] FROM [Drinks] AS [d] WHERE [d].[Discriminator] = N'Lilt'", // @"SELECT TOP(2) [d].[Id], [d].[Discriminator], [d].[CaffeineGrams], [d].[HasMilk] FROM [Drinks] AS [d] WHERE [d].[Discriminator] = N'Tea'"); } public override void FromSql_on_root() { base.FromSql_on_root(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM ( select * from ""Animals"" ) AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi')"); } public override void FromSql_on_derived() { base.FromSql_on_derived(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group] FROM ( select * from ""Animals"" ) AS [a] WHERE [a].[Discriminator] = N'Eagle'"); } public override async Task Can_query_all_types_when_shared_column(bool async) { await base.Can_query_all_types_when_shared_column(async); AssertSql( @"SELECT [d].[Id], [d].[Discriminator], [d].[CaffeineGrams], [d].[CokeCO2], [d].[SugarGrams], [d].[LiltCO2], [d].[HasMilk] FROM [Drinks] AS [d] WHERE [d].[Discriminator] IN (N'Drink', N'Coke', N'Lilt', N'Tea')"); } public override async Task Can_use_of_type_animal(bool async) { await base.Can_use_of_type_animal(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') ORDER BY [a].[Species]"); } public override async Task Can_use_is_kiwi(bool async) { await base.Can_use_is_kiwi(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[Discriminator] = N'Kiwi')"); } public override async Task Can_use_is_kiwi_with_other_predicate(bool async) { await base.Can_use_is_kiwi_with_other_predicate(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') AND (([a].[Discriminator] = N'Kiwi') AND ([a].[CountryId] = 1))"); } public override async Task Can_use_is_kiwi_in_projection(bool async) { await base.Can_use_is_kiwi_in_projection(async); AssertSql( @"SELECT CASE WHEN [a].[Discriminator] = N'Kiwi' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi')"); } public override async Task Can_use_of_type_bird(bool async) { await base.Can_use_of_type_bird(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') ORDER BY [a].[Species]"); } public override async Task Can_use_of_type_bird_predicate(bool async) { await base.Can_use_of_type_bird_predicate(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE ([a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[CountryId] = 1)) AND [a].[Discriminator] IN (N'Eagle', N'Kiwi') ORDER BY [a].[Species]"); } public override async Task Can_use_of_type_bird_with_projection(bool async) { await base.Can_use_of_type_bird_with_projection(async); AssertSql( @"SELECT [a].[EagleId] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi')"); } public override async Task Can_use_of_type_bird_first(bool async) { await base.Can_use_of_type_bird_first(async); AssertSql( @"SELECT TOP(1) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') ORDER BY [a].[Species]"); } public override async Task Can_use_of_type_kiwi(bool async) { await base.Can_use_of_type_kiwi(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[Discriminator] = N'Kiwi')"); } public override async Task Can_use_of_type_rose(bool async) { await base.Can_use_of_type_rose(async); AssertSql( @"SELECT [p].[Species], [p].[CountryId], [p].[Genus], [p].[Name], [p].[HasThorns] FROM [Plants] AS [p] WHERE [p].[Genus] IN (1, 0) AND ([p].[Genus] = 0)"); } public override async Task Can_query_all_animals(bool async) { await base.Can_query_all_animals(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') ORDER BY [a].[Species]"); } public override async Task Can_query_all_animal_views(bool async) { await base.Can_query_all_animal_views(async); AssertSql( @"SELECT [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM ( SELECT * FROM Animals ) AS [a] ORDER BY [a].[CountryId]"); } public override async Task Can_query_all_plants(bool async) { await base.Can_query_all_plants(async); AssertSql( @"SELECT [p].[Species], [p].[CountryId], [p].[Genus], [p].[Name], [p].[HasThorns] FROM [Plants] AS [p] WHERE [p].[Genus] IN (1, 0) ORDER BY [p].[Species]"); } public override async Task Can_filter_all_animals(bool async) { await base.Can_filter_all_animals(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[Name] = N'Great spotted kiwi') ORDER BY [a].[Species]"); } public override async Task Can_query_all_birds(bool async) { await base.Can_query_all_birds(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') ORDER BY [a].[Species]"); } public override async Task Can_query_just_kiwis(bool async) { await base.Can_query_just_kiwis(async); AssertSql( @"SELECT TOP(2) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] = N'Kiwi'"); } public override async Task Can_query_just_roses(bool async) { await base.Can_query_just_roses(async); AssertSql( @"SELECT TOP(2) [p].[Species], [p].[CountryId], [p].[Genus], [p].[Name], [p].[HasThorns] FROM [Plants] AS [p] WHERE [p].[Genus] = 0" ); } public override async Task Can_include_prey(bool async) { await base.Can_include_prey(async); AssertSql( @"SELECT [t].[Species], [t].[CountryId], [t].[Discriminator], [t].[Name], [t].[EagleId], [t].[IsFlightless], [t].[Group], [t0].[Species], [t0].[CountryId], [t0].[Discriminator], [t0].[Name], [t0].[EagleId], [t0].[IsFlightless], [t0].[Group], [t0].[FoundOn] FROM ( SELECT TOP(2) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group] FROM [Animals] AS [a] WHERE [a].[Discriminator] = N'Eagle' ) AS [t] LEFT JOIN ( SELECT [a0].[Species], [a0].[CountryId], [a0].[Discriminator], [a0].[Name], [a0].[EagleId], [a0].[IsFlightless], [a0].[Group], [a0].[FoundOn] FROM [Animals] AS [a0] WHERE [a0].[Discriminator] IN (N'Eagle', N'Kiwi') ) AS [t0] ON [t].[Species] = [t0].[EagleId] ORDER BY [t].[Species], [t0].[Species]"); } public override async Task Can_include_animals(bool async) { await base.Can_include_animals(async); AssertSql( @"SELECT [c].[Id], [c].[Name], [t].[Species], [t].[CountryId], [t].[Discriminator], [t].[Name], [t].[EagleId], [t].[IsFlightless], [t].[Group], [t].[FoundOn] FROM [Countries] AS [c] LEFT JOIN ( SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') ) AS [t] ON [c].[Id] = [t].[CountryId] ORDER BY [c].[Name], [c].[Id], [t].[Species]"); } public override async Task Can_use_of_type_kiwi_where_north_on_derived_property(bool async) { await base.Can_use_of_type_kiwi_where_north_on_derived_property(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE ([a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[Discriminator] = N'Kiwi')) AND ([a].[FoundOn] = CAST(0 AS tinyint))"); } public override async Task Can_use_of_type_kiwi_where_south_on_derived_property(bool async) { await base.Can_use_of_type_kiwi_where_south_on_derived_property(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE ([a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[Discriminator] = N'Kiwi')) AND ([a].[FoundOn] = CAST(1 AS tinyint))"); } public override async Task Discriminator_used_when_projection_over_derived_type(bool async) { await base.Discriminator_used_when_projection_over_derived_type(async); AssertSql( @"SELECT [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] = N'Kiwi'"); } public override async Task Discriminator_used_when_projection_over_derived_type2(bool async) { await base.Discriminator_used_when_projection_over_derived_type2(async); AssertSql( @"SELECT [a].[IsFlightless], [a].[Discriminator] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi')"); } public override async Task Discriminator_used_when_projection_over_of_type(bool async) { await base.Discriminator_used_when_projection_over_of_type(async); AssertSql( @"SELECT [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[Discriminator] = N'Kiwi')"); } public override void Can_insert_update_delete() { base.Can_insert_update_delete(); AssertSql( @"SELECT TOP(2) [c].[Id], [c].[Name] FROM [Countries] AS [c] WHERE [c].[Id] = 1", // @"@p0='Apteryx owenii' (Nullable = false) (Size = 100) @p1='1' @p2='Kiwi' (Nullable = false) (Size = 4000) @p3=NULL (Size = 100) @p4='0' (Nullable = true) (Size = 1) @p5='True' (Nullable = true) @p6='Little spotted kiwi' (Size = 4000) SET NOCOUNT ON; INSERT INTO [Animals] ([Species], [CountryId], [Discriminator], [EagleId], [FoundOn], [IsFlightless], [Name]) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6);", // @"SELECT TOP(2) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE ([a].[Discriminator] = N'Kiwi') AND ([a].[Species] LIKE N'%owenii')", // @"@p1='Apteryx owenii' (Nullable = false) (Size = 100) @p0='Aquila chrysaetos canadensis' (Size = 100) SET NOCOUNT ON; UPDATE [Animals] SET [EagleId] = @p0 WHERE [Species] = @p1; SELECT @@ROWCOUNT;", // @"SELECT TOP(2) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE ([a].[Discriminator] = N'Kiwi') AND ([a].[Species] LIKE N'%owenii')", // @"@p0='Apteryx owenii' (Nullable = false) (Size = 100) SET NOCOUNT ON; DELETE FROM [Animals] WHERE [Species] = @p0; SELECT @@ROWCOUNT;", // @"SELECT COUNT(*) FROM [Animals] AS [a] WHERE ([a].[Discriminator] = N'Kiwi') AND ([a].[Species] LIKE N'%owenii')"); } public override async Task Byte_enum_value_constant_used_in_projection(bool async) { await base.Byte_enum_value_constant_used_in_projection(async); AssertSql( @"SELECT CASE WHEN [a].[IsFlightless] = CAST(1 AS bit) THEN CAST(0 AS tinyint) ELSE CAST(1 AS tinyint) END FROM [Animals] AS [a] WHERE [a].[Discriminator] = N'Kiwi'"); } public override async Task Union_siblings_with_duplicate_property_in_subquery(bool async) { await base.Union_siblings_with_duplicate_property_in_subquery(async); AssertSql( @"SELECT [t].[Id], [t].[Discriminator], [t].[CaffeineGrams], [t].[CokeCO2], [t].[SugarGrams], [t].[Carbonation], [t].[SugarGrams0], [t].[CaffeineGrams0], [t].[HasMilk] FROM ( SELECT [d].[Id], [d].[Discriminator], [d].[CaffeineGrams], [d].[CokeCO2], [d].[SugarGrams], NULL AS [CaffeineGrams0], NULL AS [HasMilk], NULL AS [Carbonation], NULL AS [SugarGrams0] FROM [Drinks] AS [d] WHERE [d].[Discriminator] = N'Coke' UNION SELECT [d0].[Id], [d0].[Discriminator], NULL AS [CaffeineGrams], NULL AS [CokeCO2], NULL AS [SugarGrams], [d0].[CaffeineGrams] AS [CaffeineGrams0], [d0].[HasMilk], NULL AS [Carbonation], NULL AS [SugarGrams0] FROM [Drinks] AS [d0] WHERE [d0].[Discriminator] = N'Tea' ) AS [t] WHERE [t].[Id] > 0"); } public override async Task OfType_Union_subquery(bool async) { await base.OfType_Union_subquery(async); AssertSql( @"SELECT [t].[Species], [t].[CountryId], [t].[Discriminator], [t].[Name], [t].[EagleId], [t].[IsFlightless], [t].[FoundOn] FROM ( SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a].[Discriminator] = N'Kiwi') UNION SELECT [a0].[Species], [a0].[CountryId], [a0].[Discriminator], [a0].[Name], [a0].[EagleId], [a0].[IsFlightless], [a0].[FoundOn] FROM [Animals] AS [a0] WHERE [a0].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a0].[Discriminator] = N'Kiwi') ) AS [t] WHERE ([t].[FoundOn] = CAST(0 AS tinyint)) AND [t].[FoundOn] IS NOT NULL"); } public override async Task OfType_Union_OfType(bool async) { await base.OfType_Union_OfType(async); AssertSql(" "); } public override async Task Subquery_OfType(bool async) { await base.Subquery_OfType(async); AssertSql( @"@__p_0='5' SELECT DISTINCT [t].[Species], [t].[CountryId], [t].[Discriminator], [t].[Name], [t].[EagleId], [t].[IsFlightless], [t].[FoundOn] FROM ( SELECT TOP(@__p_0) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') ORDER BY [a].[Species] ) AS [t] WHERE [t].[Discriminator] = N'Kiwi'"); } public override async Task Union_entity_equality(bool async) { await base.Union_entity_equality(async); AssertSql( @"SELECT [t].[Species], [t].[CountryId], [t].[Discriminator], [t].[Name], [t].[EagleId], [t].[IsFlightless], [t].[Group], [t].[FoundOn] FROM ( SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn], NULL AS [Group] FROM [Animals] AS [a] WHERE [a].[Discriminator] = N'Kiwi' UNION SELECT [a0].[Species], [a0].[CountryId], [a0].[Discriminator], [a0].[Name], [a0].[EagleId], [a0].[IsFlightless], NULL AS [FoundOn], [a0].[Group] FROM [Animals] AS [a0] WHERE [a0].[Discriminator] = N'Eagle' ) AS [t] WHERE 0 = 1"); } public override void Member_access_on_intermediate_type_works() { base.Member_access_on_intermediate_type_works(); AssertSql( @"SELECT [a].[Name] FROM [Animals] AS [a] WHERE [a].[Discriminator] = N'Kiwi' ORDER BY [a].[Name]"); } public override void Casting_to_base_type_joining_with_query_type_works() { base.Casting_to_base_type_joining_with_query_type_works(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a0].[CountryId], [a0].[Discriminator], [a0].[Name], [a0].[EagleId], [a0].[IsFlightless], [a0].[Group], [a0].[FoundOn] FROM [Animals] AS [a] INNER JOIN ( Select * from ""Animals"" ) AS [a0] ON [a].[Name] = [a0].[Name] WHERE [a].[Discriminator] = N'Eagle'"); } public override async Task Is_operator_on_result_of_FirstOrDefault(bool async) { await base.Is_operator_on_result_of_FirstOrDefault(async); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi') AND (( SELECT TOP(1) [a0].[Discriminator] FROM [Animals] AS [a0] WHERE [a0].[Discriminator] IN (N'Eagle', N'Kiwi') AND ([a0].[Name] = N'Great spotted kiwi')) = N'Kiwi') ORDER BY [a].[Species]"); } public override async Task Selecting_only_base_properties_on_base_type(bool async) { await base.Selecting_only_base_properties_on_base_type(async); AssertSql( @"SELECT [a].[Name] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi')"); } public override async Task Selecting_only_base_properties_on_derived_type(bool async) { await base.Selecting_only_base_properties_on_derived_type(async); AssertSql( @"SELECT [a].[Name] FROM [Animals] AS [a] WHERE [a].[Discriminator] IN (N'Eagle', N'Kiwi')"); } private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); } }
39.634921
272
0.58973
[ "Apache-2.0" ]
BradBarnich/EntityFramework
test/EFCore.SqlServer.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqlServerTest.cs
22,473
C#
// <auto-generated /> using System; using EFWebAPI.EFContext; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace EFWebAPI.Migrations { [DbContext(typeof(EFWebAPIContext))] [Migration("20190509202422_InitialMigration")] partial class InitialMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.8-servicing-32085") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("EFWebAPI.Entities.Author", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("name"); b.HasKey("ID"); b.ToTable("Authors"); }); modelBuilder.Entity("EFWebAPI.Entities.Book", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("AuthorID"); b.Property<string>("Title"); b.HasKey("ID"); b.HasIndex("AuthorID"); b.ToTable("Books"); }); modelBuilder.Entity("EFWebAPI.Entities.Book", b => { b.HasOne("EFWebAPI.Entities.Author", "Author") .WithMany("Books") .HasForeignKey("AuthorID"); }); #pragma warning restore 612, 618 } } }
34.109375
125
0.573981
[ "MIT" ]
jo3l17/CodiGo3
Backend/Semana 12/Dia4/EFWebAPI/EFWebAPI/Migrations/20190509202422_InitialMigration.Designer.cs
2,185
C#
// OData .NET Libraries ver. 5.6.3 // Copyright (c) Microsoft Corporation // All rights reserved. // MIT License // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace Microsoft.Data.OData { #region Namespaces using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Data.Edm; using Microsoft.Data.OData.Metadata; #endregion Namespaces /// <summary> /// Class responsible for determining the type name that should be written on the wire for entries and values in the ATOM and Verbose JSON formats. /// </summary> internal sealed class AtomAndVerboseJsonTypeNameOracle : TypeNameOracle { /// <summary> /// Determines the type name for the given entry to write to the payload. /// </summary> /// <param name="entry">The ODataEntry whose type name is to be written</param> /// <returns>Type name to write to the payload, or null if no type name should be written.</returns> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This method will eventually become an override of a method in the base class, but more refactoring work needs to happen first.")] internal string GetEntryTypeNameForWriting(ODataEntry entry) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(entry != null, "entry != null"); SerializationTypeNameAnnotation typeNameAnnotation = entry.GetAnnotation<SerializationTypeNameAnnotation>(); if (typeNameAnnotation != null) { return typeNameAnnotation.TypeName; } return entry.TypeName; } /// <summary> /// Determines the type name for the given value to write to the payload. /// </summary> /// <param name="value">The value whose type name is to be written. This can be an ODataPrimitiveValue, an ODataComplexValue, an ODataCollectionValue or a Clr primitive object.</param> /// <param name="typeReferenceFromValue">The type resolved from the value.</param> /// <param name="typeNameAnnotation">The serialization type name annotation.</param> /// <param name="collectionValidator">true if the type name belongs to an open property, false otherwise.</param> /// <param name="collectionItemTypeName">Returns the item type name of the collection type if <paramref name="value"/> is a collection value and its type name can be determined.</param> /// <returns>Type name to write to the payload, or null if no type should be written.</returns> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This method will eventually become an override of a method in the base class, but more refactoring work needs to happen first.")] internal string GetValueTypeNameForWriting( object value, IEdmTypeReference typeReferenceFromValue, SerializationTypeNameAnnotation typeNameAnnotation, CollectionWithoutExpectedTypeValidator collectionValidator, out string collectionItemTypeName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(value != null, "value != null"); collectionItemTypeName = null; // if no type name is specified we will use the type name inferred from metadata string typeName = GetTypeNameFromValue(value); if (typeName == null && typeReferenceFromValue != null) { typeName = typeReferenceFromValue.ODataFullName(); } if (typeName != null) { // If the type is the same as the one specified by the parent collection, omit the type name, since it's not needed. if (collectionValidator != null && string.CompareOrdinal(collectionValidator.ItemTypeNameFromCollection, typeName) == 0) { typeName = null; } // If value is a collection value, get the item type name. if (typeName != null && value is ODataCollectionValue) { collectionItemTypeName = ValidationUtils.ValidateCollectionTypeName(typeName); } } if (typeNameAnnotation != null) { // If the value of TypeName is null, we'll flow it through here, thereby instructing the caller to write no type name. typeName = typeNameAnnotation.TypeName; } return typeName; } } }
52.718182
227
0.653561
[ "Apache-2.0" ]
tapika/choco
lib/Microsoft.Data.Services.Client/ODataLib/OData/Desktop/.Net4.0/Microsoft/Data/OData/AtomAndVerboseJsonTypeNameOracle.cs
5,799
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; //using Microsoft.Owin.Security; using Sistrategia.SAT.Resources; namespace Sistrategia.SAT.CFDiWebSite.Models { public enum AccountIndexMessageId { AddPhoneSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } public class AccountIndexViewModel { public AccountIndexViewModel() { } public string UserName { get; set; } public string FullName { get; set; } public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } public class LoginViewModel { [Required] [Display(ResourceType = typeof(LocalizedStrings), Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(ResourceType = typeof(LocalizedStrings), Name = "Password")] public string Password { get; set; } //[Display(Name = "Remember me?")] [Display(ResourceType = typeof(LocalizedStrings), Name = "Account_RememberMe")] public bool RememberMe { get; set; } } public class RegisterViewModel { [Required(ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "FullNameRequired")] [Display(ResourceType = typeof(LocalizedStrings), Name = "FullNameField")] public string FullName { get; set; } [Required(ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "EmailRequired")] [EmailAddress] [Display(ResourceType = typeof(LocalizedStrings), Name = "Email")] public string Email { get; set; } [Required(ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "PasswordRequired")] [StringLength(100, MinimumLength = 6, ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "Account_PasswordValidationError" //ErrorMessage = "The {0} must be at least {2} characters long." )] [DataType(DataType.Password)] [Display(ResourceType = typeof(LocalizedStrings), Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(ResourceType = typeof(LocalizedStrings), Name = "Account_ConfirmPassword")] [Compare("Password", ErrorMessageResourceType = typeof(LocalizedStrings), //ErrorMessage = "The password and confirmation password do not match." ErrorMessageResourceName = "Account_ConfirmPasswordDoesNotMatchError" )] public string ConfirmPassword { get; set; } //[Display(Name = "Hometown")] //public string Hometown { get; set; } } public class ForgotPasswordViewModel { [Required(ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "EmailRequired")] [EmailAddress] [Display(ResourceType = typeof(LocalizedStrings), Name = "Email")] public string Email { get; set; } } public class ResetPasswordViewModel { [Required(ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "EmailRequired")] [EmailAddress] [Display(ResourceType = typeof(LocalizedStrings), Name = "Email")] public string Email { get; set; } [Required(ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "PasswordRequired")] [StringLength(100, MinimumLength = 6, ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "Account_PasswordValidationError" //ErrorMessage = "The {0} must be at least {2} characters long." )] [DataType(DataType.Password)] [Display(ResourceType = typeof(LocalizedStrings), Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(ResourceType = typeof(LocalizedStrings), Name = "Account_ConfirmPassword")] [Compare("Password", ErrorMessageResourceType = typeof(LocalizedStrings), //ErrorMessage = "The password and confirmation password do not match." ErrorMessageResourceName = "Account_ConfirmPasswordDoesNotMatchError" )] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, MinimumLength = 6, ErrorMessageResourceType = typeof(LocalizedStrings), ErrorMessageResourceName = "Account_PasswordValidationError" //ErrorMessage = "The {0} must be at least {2} characters long." )] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
38.406667
118
0.648499
[ "Apache-2.0" ]
Alejandro-SA/SistrategiaCFDi
src/Sistrategia.SAT.CFDiWebSite/Models/AccountViewModels.cs
5,763
C#
using Gtk; namespace MonoGame.Tools.Pipeline { public partial class CollectionEditorDialog { private VBox vbox1; private HBox hbox1; private Button buttonAdd, buttonRemove; private ScrolledWindow scrollView1; private TreeView treeView1; protected virtual void Build () { this.Title = "Reference Editor"; this.WindowPosition = WindowPosition.CenterOnParent; this.DefaultWidth = 400; this.DefaultHeight = 350; #if GTK3 var geom = new Gdk.Geometry(); geom.MinWidth = this.DefaultWidth; geom.MinHeight = 200; this.SetGeometryHints(this, geom, Gdk.WindowHints.MinSize); #endif hbox1 = new HBox(); scrollView1 = new ScrolledWindow(); treeView1 = new TreeView(); treeView1.HeadersVisible = false; treeView1.Selection.Changed += SelectionChanged; scrollView1.Add(treeView1); hbox1.PackStart(scrollView1, true, true, 0); vbox1 = new VBox(); buttonAdd = new Button("Add"); buttonAdd.Clicked += AddFileEvent; vbox1.PackStart(buttonAdd, false, true, 0); buttonRemove = new Button("Remove"); buttonRemove.Sensitive = false; buttonRemove.Clicked += RemoveFileEvent; vbox1.PackStart(buttonRemove, false, true, 0); hbox1.PackStart(vbox1, false, true, 1); #if GTK3 this.ContentArea.PackStart(hbox1, true, true, 0); #else this.VBox.PackStart(hbox1, true, true, 0); #endif this.AddButton("Ok", ResponseType.Ok); this.AddButton("Cancel", ResponseType.Cancel); this.DefaultResponse = ResponseType.Ok; this.ShowAll (); this.Response += this.OnResponse; } } }
28.358209
71
0.584737
[ "MIT" ]
nanexcool/MonoGame
Tools/Pipeline/Gtk/Dialogs/CollectionEditorDialog.GUI.cs
1,900
C#
using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using System.Diagnostics; [assembly: ExportRenderer(typeof(ViewCell), typeof(MyContacts.iOS.StandardViewCellRenderer))] namespace MyContacts.iOS { public class StandardViewCellRenderer : ViewCellRenderer { public override UIKit.UITableViewCell GetCell (Cell item, UIKit.UITableViewCell reusableCell, UIKit.UITableView tv) { var cell = base.GetCell (item, reusableCell, tv); Debug.WriteLine ("Style Id" + item.StyleId); switch (item.StyleId) { case "checkmark": cell.Accessory = UIKit.UITableViewCellAccessory.Checkmark; break; case "detail-button": cell.Accessory = UIKit.UITableViewCellAccessory.DetailButton; break; case "detail-disclosure-button": cell.Accessory = UIKit.UITableViewCellAccessory.DetailDisclosureButton; break; case "disclosure": cell.Accessory = UIKit.UITableViewCellAccessory.DisclosureIndicator; break; default: cell.Accessory = UIKit.UITableViewCellAccessory.None; break; } return cell; } } }
36.810811
123
0.580029
[ "MIT" ]
bloomz189/app-contacts
src/MyContacts.iOS/Renderers/StandardViewCellRenderer.cs
1,364
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL { public interface ITickerService { Task<TickerInfo> GetTickerInformation(string ticker); Task<IEnumerable<TickerInfos>> GetTickerInformations(); } }
20.666667
63
0.73871
[ "MIT" ]
KarimLjung/StockHistory
BLL/ITickerService.cs
312
C#
using Measurement.Grpc.Context; using Measurement.Grpc.Repositories; using Measurement.Grpc.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Measurement.Grpc { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMeasurementContext, MeasurementContext>(); services.AddScoped<IReadOnlyTemperatureRepository, ReadOnlyTemperatureRepository>(); services.AddAutoMapper(typeof(Startup)); services.AddGrpc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService<MeasurementService>(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); }); }); } } }
37.586957
215
0.657027
[ "MIT" ]
krystianrebzda/ModernBuildingServices
modernbuilding-services/Services/Measurement/Measurement.Grpc/Startup.cs
1,731
C#
using HotChocolate.Data.Projections.Expressions; namespace HotChocolate.Data.Projections { public static class ProjectionConventionDescriptorExtensions { public static IProjectionConventionDescriptor AddDefaults( this IProjectionConventionDescriptor descriptor) => descriptor.Provider(new QueryableProjectionProvider(x => x.AddDefaults())); } }
32.5
87
0.758974
[ "MIT" ]
RohrerF/hotchocolate
src/HotChocolate/Data/src/Data/Projections/Convention/Extensions/ProjectionConventionDescriptorExtensions.cs
390
C#
using System.Collections.Generic; using SimplCommerce.Infrastructure.Models; namespace SimplCommerce.Module.Localization.Models { public class Culture : Entity { public string Name { get; set; } public IList<Resource> Resources { get; set; } } }
21.307692
54
0.696751
[ "Apache-2.0" ]
SAPIENZAE/SimplCommerce
src/Modules/SimplCommerce.Module.Localization/Models/Culture.cs
279
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class HUDSignalProgressBarController : gameuiHUDGameController { [Ordinal(0)] [RED("AnimOptions")] public inkanimPlaybackOptions AnimOptions { get; set; } [Ordinal(1)] [RED("AnimProxy")] public CHandle<inkanimProxy> AnimProxy { get; set; } [Ordinal(2)] [RED("IntroAnimation")] public CHandle<inkanimProxy> IntroAnimation { get; set; } [Ordinal(3)] [RED("OutroAnimation")] public CHandle<inkanimProxy> OutroAnimation { get; set; } [Ordinal(4)] [RED("SignalLostAnimation")] public CHandle<inkanimProxy> SignalLostAnimation { get; set; } [Ordinal(5)] [RED("alphaInterpolator")] public CHandle<inkanimTransparencyInterpolator> AlphaInterpolator { get; set; } [Ordinal(6)] [RED("alpha_fadein")] public CHandle<inkanimDefinition> Alpha_fadein { get; set; } [Ordinal(7)] [RED("bar")] public inkWidgetReference Bar { get; set; } [Ordinal(8)] [RED("completed")] public inkWidgetReference Completed { get; set; } [Ordinal(9)] [RED("data")] public HUDProgressBarData Data { get; set; } [Ordinal(10)] [RED("percent")] public inkTextWidgetReference Percent { get; set; } [Ordinal(11)] [RED("progressBBID")] public CUInt32 ProgressBBID { get; set; } [Ordinal(12)] [RED("progressBarBB")] public CHandle<gameIBlackboard> ProgressBarBB { get; set; } [Ordinal(13)] [RED("progressBarDef")] public CHandle<UI_HUDSignalProgressBarDef> ProgressBarDef { get; set; } [Ordinal(14)] [RED("rootWidget")] public wCHandle<inkWidget> RootWidget { get; set; } [Ordinal(15)] [RED("signalBars")] public CArray<inkWidgetReference> SignalBars { get; set; } [Ordinal(16)] [RED("signalLost")] public inkWidgetReference SignalLost { get; set; } [Ordinal(17)] [RED("signalStrengthBBID")] public CUInt32 SignalStrengthBBID { get; set; } [Ordinal(18)] [RED("stateBBID")] public CUInt32 StateBBID { get; set; } [Ordinal(19)] [RED("tick")] public CFloat Tick { get; set; } public HUDSignalProgressBarController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
62.714286
123
0.705695
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/HUDSignalProgressBarController.cs
2,161
C#
//------------------------------------------------------------------------------ // <auto-generated> // Generado por la clase WriteCodeFragment de MSBuild. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("mantri-web-api.Views")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute("2.1")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute("MVC-2.1")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute("MVC-2.1", "Microsoft.AspNetCore.Mvc.Razor.Extensions")]
51.357143
138
0.625869
[ "MIT" ]
jesus-abz/mantri-web-api
obj/Debug/netcoreapp2.1/mantri-web-api.RazorAssemblyInfo.cs
719
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _07.User_logins { class Program { static void Main(string[] args) { var dict = new Dictionary<string, string>();var counter = 0; while (true) { var inputs = Console.ReadLine().Split(new string[] { "->", " " }, StringSplitOptions.RemoveEmptyEntries).ToArray(); if (inputs[0].Equals("login")) { break; } var username = inputs[0]; var password = inputs[1]; dict[username] = password; } while (true) { var input = Console.ReadLine().Split(new string[] { "->", " " }, StringSplitOptions.RemoveEmptyEntries).ToArray(); if (input[0].Equals("end")) { break; } var username = input[0]; var passwords = input[1]; if (!dict.ContainsKey(username)) { Console.WriteLine($"{username}: login failed"); counter++; }else if(dict.ContainsKey(username)) { if (passwords == dict[username]) { Console.WriteLine($"{username}: logged in successfully"); } else { Console.WriteLine($"{username}: login failed"); counter++; } } } Console.WriteLine($"unsuccessful login attempts: {counter}"); } } }
32.796296
131
0.435347
[ "MIT" ]
TsvetomirNikolov/Softuni---Technology-Fundamentals
09. Dictionaries/07. User logins/Program.cs
1,773
C#
using System; using NUnit.Framework; using SFA.DAS.Payments.FundingSource.Messages.Events; namespace SFA.DAS.Payments.Audit.Application.UnitTests.FundingSource { [TestFixture] public class SfaFullyFundedFundingSourcePaymentEventTests : FundingSourceMappingTests<SfaFullyFundedFundingSourcePaymentEvent> { protected override SfaFullyFundedFundingSourcePaymentEvent CreatePaymentEvent() { return new SfaFullyFundedFundingSourcePaymentEvent { RequiredPaymentEventId = Guid.NewGuid() }; } } }
32.333333
130
0.725086
[ "MIT" ]
PJChamley/das-payments-V2
src/SFA.DAS.Payments.Audit.Application.UnitTests/FundingSource/SfaFullyFundedFundingSourcePaymentEventTests.cs
584
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Zell.UiPathAutomation.Orchestrator.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// A trigger for resuming a job /// </summary> public partial class JobTriggerDto { /// <summary> /// Initializes a new instance of the JobTriggerDto class. /// </summary> public JobTriggerDto() { CustomInit(); } /// <summary> /// Initializes a new instance of the JobTriggerDto class. /// </summary> /// <param name="triggerType">Resume type (job, queue, task etc). /// Possible values include: 'None', 'QueueItem', 'Job', 'Task', /// 'Timer'</param> /// <param name="status">Job trigger status (new, ready, fired etc). /// Possible values include: 'New', 'Ready', 'Fired'</param> /// <param name="itemId">item Id (queue item id, task id, job id /// etc)</param> /// <param name="timer">Resume timer (for time trigger)</param> /// <param name="triggerMessage">Workflow provided resume trigger /// description/message</param> public JobTriggerDto(long? jobId = default(long?), JobTriggerDtoTriggerType? triggerType = default(JobTriggerDtoTriggerType?), JobTriggerDtoStatus? status = default(JobTriggerDtoStatus?), long? itemId = default(long?), System.DateTime? timer = default(System.DateTime?), string triggerMessage = default(string), long? id = default(long?)) { JobId = jobId; TriggerType = triggerType; Status = status; ItemId = itemId; Timer = timer; TriggerMessage = triggerMessage; Id = id; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "JobId")] public long? JobId { get; set; } /// <summary> /// Gets or sets resume type (job, queue, task etc). Possible values /// include: 'None', 'QueueItem', 'Job', 'Task', 'Timer' /// </summary> [JsonProperty(PropertyName = "TriggerType")] public JobTriggerDtoTriggerType? TriggerType { get; set; } /// <summary> /// Gets or sets job trigger status (new, ready, fired etc). Possible /// values include: 'New', 'Ready', 'Fired' /// </summary> [JsonProperty(PropertyName = "Status")] public JobTriggerDtoStatus? Status { get; set; } /// <summary> /// Gets or sets item Id (queue item id, task id, job id etc) /// </summary> [JsonProperty(PropertyName = "ItemId")] public long? ItemId { get; set; } /// <summary> /// Gets or sets resume timer (for time trigger) /// </summary> [JsonProperty(PropertyName = "Timer")] public System.DateTime? Timer { get; set; } /// <summary> /// Gets or sets workflow provided resume trigger description/message /// </summary> [JsonProperty(PropertyName = "TriggerMessage")] public string TriggerMessage { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Id")] public long? Id { get; set; } } }
36.383838
346
0.577735
[ "MIT" ]
zell12/MondayAppOne
Zell.UiPathAutomation/Orchestrator/Models/JobTriggerDto.cs
3,602
C#
/// <summary> /// Represents some arbitrary user state that can optionally accompany a parsing /// operation. /// </summary> public interface ParserUserState { /// <summary> /// Returns a new deep copy of the current state. /// </summary> ParserUserState Clone(); }
22.5
80
0.7
[ "MIT" ]
exodrifter/unity-rumor
Parser/Types/ParserUserState.cs
270
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace BlazorDemo.Models.Survey { public class SurveyAddEdit { [ValidateComplexType] public SurveyAddEditBasicInfo BasicInfo { get; set; } = new SurveyAddEditBasicInfo(); [ValidateComplexType] public SurveyAddEditContactInfo ContactInfo { get; set; } = new SurveyAddEditContactInfo(); [ValidateComplexType] public IEnumerable<SurveyAddEditAnswer> Answers { get; set; } = new List<SurveyAddEditAnswer>(); } }
30.777778
104
0.718412
[ "MIT" ]
WojciechPszonak/BlazorDemo
BlazorDemo.Models/Survey/SurveyAddEdit.cs
556
C#
namespace Poderosa { partial class EditDisplayDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // EditDisplayDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(408, 363); this.Name = "EditDisplayDialog"; this.Text = "EditDisplayDialog"; this.ResumeLayout(false); } #endregion } }
30.543478
107
0.551601
[ "MIT" ]
bosima/RDManager
Terminal Control/EditDisplayDialog.Designer.cs
1,405
C#
/* * Original author: Yuval Boss <yuval .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2014 University of Washington - Seattle, WA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace MPP_Export { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // There should only be one argument from skyline which is the file path to the report file. if (args.Length != 1) { Console.Error.WriteLine(MppExportResources.Program_Main_Argument_was_invalid__MPP_Export_requires_one_argument__the_path_to_the_Skyline_report_file_); return; } using (var saveFileDialog = new SaveFileDialog { FileName = "MPPReport.txt", // Not L10N Filter = MppExportResources.Program_Main_Text_files____txt____txt_All_files__________, }) { if (saveFileDialog.ShowDialog() != DialogResult.OK) { return; } ParseCsv(args[0], saveFileDialog.FileName); } } public static void ParseCsv(string csvFilePathName, string outputFile) { string[] lines = File.ReadAllLines(csvFilePathName); string[] csvFields = GetFields(lines[0], ','); // Not L10N int colCount = csvFields.Length; var dt = new DataTable(); foreach (string csvField in csvFields) { dt.Columns.Add(csvField, typeof(string)); } var dtOut = new DataTable(); const int nonPivotCols = 10; // Number of columns before replicate columns begin. const int newCols = 5; // Number of columns before accession column in export csv. int rowCount = 1; // Row counter used for RT and Mass values. int numOfReplicates = dt.Columns.Count - nonPivotCols; dtOut.Columns.Add("RT"); // Not L10N dtOut.Columns.Add("Mass"); // Not L10N dtOut.Columns.Add("Compound Name"); // Not L10N dtOut.Columns.Add("Formula"); // Not L10N dtOut.Columns.Add("CAS ID"); // Not L10N dtOut.Columns.Add("Swiss-Prot ID"); // Not L10N // Column headers for replicate area columns generated here. for (int i = 0; i < numOfReplicates; i++) { if (csvFields[i + nonPivotCols].Contains(" Area")) // Not L10N { dtOut.Columns.Add(csvFields[i + nonPivotCols].Replace(" Area", ""), typeof(string)); // Not L10N } else { dtOut.Columns.Add(csvFields[i + nonPivotCols], typeof(string)); } } foreach (string line in lines) { if (line == lines[0]) // Skips column headers. { continue; } csvFields = GetFields(line, ','); var row = dt.NewRow(); for (int f = 0; f < colCount; f++) { row[f] = csvFields[f]; } dt.Rows.Add(row); } var proteinAccessions = dt.AsEnumerable() .Select(dr => dr.Field<string>("ProteinAccession")) // Not L10N .Distinct().ToArray(); Console.WriteLine(MppExportResources.Program_ParseCsv_Unique_Accessions_); foreach (var proteinAccession in proteinAccessions) { Console.WriteLine("# " + proteinAccession); // Not L10N var dataRows = dt.Select(string.Format("ProteinAccession = '{0}'", proteinAccession)); // Not L10N var replicateRowValues = new double[numOfReplicates]; var replicateRowDescription = ""; // Not L10N foreach (var row in dataRows) { for (int a = 0; a < numOfReplicates; a++) { double cellValue; if (!double.TryParse(row[a + nonPivotCols].ToString(), out cellValue)) cellValue = 0; replicateRowValues[a] += cellValue; } replicateRowDescription = row[1].ToString(); } var newRow = dtOut.NewRow(); newRow[newCols] = proteinAccession; newRow[0] = rowCount; newRow[1] = rowCount; newRow[2] = replicateRowDescription; rowCount = rowCount + 1; for (int r = 0; r < replicateRowValues.Length; r++) { newRow[r + newCols + 1] = replicateRowValues[r]; } dtOut.Rows.Add(newRow); } var sb = new StringBuilder(); string[] columnNames = dtOut.Columns.Cast<DataColumn>(). Select(column => column.ColumnName). ToArray(); sb.AppendLine(SetFields(columnNames)); foreach (DataRow row in dtOut.Rows) { string[] fields = row.ItemArray.Select(field => field.ToString()). ToArray(); sb.AppendLine(SetFields(fields)); } try { File.WriteAllText(outputFile.ToString(CultureInfo.InvariantCulture), sb.ToString()); Console.WriteLine(MppExportResources.Program_ParseCsv_Location__ + outputFile); Console.WriteLine(MppExportResources.Program_ParseCsv_File_saved_successfully_); Console.WriteLine(MppExportResources.Program_ParseCsv_Finished_); } // If file MPPReport.csv can't be accessed program will throw IOException. catch (IOException ex) { Console.WriteLine(ex); Console.WriteLine(MppExportResources.Program_ParseCsv_System_IO_Exception__cannot_access__0_, outputFile); Console.WriteLine(MppExportResources.Program_ParseCsv_Double_check_that__0__is_not_open_in_another_program_, outputFile); Console.WriteLine(MppExportResources.Program_ParseCsv_Finished___Run_Failed_); } } // CSV Parsing to deal with commas. private static string[] GetFields(string line, char separator) { var listFields = new List<string>(); var sbField = new StringBuilder(); bool inQuotes = false; char chLast = '\0'; // Not L10N foreach (char ch in line) { if (inQuotes) { if (ch == '"') // Not L10N inQuotes = false; else sbField.Append(ch); } else if (ch == '"') // Not L10N { inQuotes = true; // Add quote character, for "" inside quotes. if (chLast == '"') // Not L10N sbField.Append(ch); } else if (ch == separator) { listFields.Add(sbField.ToString()); sbField.Remove(0, sbField.Length); } else { sbField.Append(ch); } chLast = ch; } listFields.Add(sbField.ToString()); return listFields.ToArray(); } private static string SetFields(string[] row) { String csvLine = String.Join("\t", row.Select(field => ToDsvField(field, ','))); // Not L10N return csvLine; } public static string ToDsvField(string text, char separator) { if (text == null) return string.Empty; if (text.IndexOfAny(new[] { '"', separator, '\r', '\n' }) == -1) // Not L10N return text; return '"' + text.Replace("\"", "\"\"") + '"'; // Not L10N } } }
40.21097
167
0.504932
[ "Apache-2.0" ]
CSi-Studio/pwiz
pwiz_tools/Skyline/Executables/Tools/MPPExport/src/Program.cs
9,532
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SettingAppliedRoutedEventArgs.cs" company="Orcomp development team"> // Copyright (c) 2008 - 2014 Orcomp development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Orc.GraphExplorer { using System.Windows; public class SettingAppliedRoutedEventArgs : RoutedEventArgs { #region Fields private readonly bool _needRefresh; #endregion #region Constructors public SettingAppliedRoutedEventArgs(RoutedEvent routedEvent, object source, bool needRefresh) : base(routedEvent, source) { _needRefresh = needRefresh; } #endregion #region Properties public bool NeedRefresh { get { return _needRefresh; } } #endregion } }
31.484848
120
0.489894
[ "MIT" ]
Orcomp/Orc.GraphExplorer
src/Orc.GraphExplorer/Events/SettingAppliedRoutedEventArgs.cs
1,041
C#
/* * Prime Developer Trial * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = FactSet.SDK.StocksAPIforDigitalPortals.Client.OpenAPIDateConverter; namespace FactSet.SDK.StocksAPIforDigitalPortals.Model { /// <summary> /// Currency of the attributes representing a monetary value. See endpoint &#x60;/basic/valueUnit/currency/main/list&#x60; for possible values. /// </summary> [DataContract(Name = "inline_response_200_4_reportedKeyFigures_firstFiscalYear_currencyDependentKeyFigures_currency")] public partial class InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency : IEquatable<InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency" /> class. /// </summary> /// <param name="id">Identifier of the currency..</param> /// <param name="isoCode">ISO 4217 code of the currency..</param> public InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency(decimal id = default(decimal), string isoCode = default(string)) { this.Id = id; this.IsoCode = isoCode; } /// <summary> /// Identifier of the currency. /// </summary> /// <value>Identifier of the currency.</value> [DataMember(Name = "id", EmitDefaultValue = false)] public decimal Id { get; set; } /// <summary> /// ISO 4217 code of the currency. /// </summary> /// <value>ISO 4217 code of the currency.</value> [DataMember(Name = "isoCode", EmitDefaultValue = false)] public string IsoCode { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" IsoCode: ").Append(IsoCode).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency); } /// <summary> /// Returns true if InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency instances are equal /// </summary> /// <param name="input">Instance of InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency to be compared</param> /// <returns>Boolean</returns> public bool Equals(InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency input) { if (input == null) { return false; } return ( this.Id == input.Id || this.Id.Equals(input.Id) ) && ( this.IsoCode == input.IsoCode || (this.IsoCode != null && this.IsoCode.Equals(input.IsoCode)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.IsoCode != null) { hashCode = (hashCode * 59) + this.IsoCode.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
38.986207
232
0.626747
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/StocksAPIforDigitalPortals/v2/src/FactSet.SDK.StocksAPIforDigitalPortals/Model/InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresCurrency.cs
5,653
C#
#if OS_LINUX || OS_OSX using System; using System.IO; using System.Security.Cryptography; using System.Threading; using Microsoft.VisualStudio.Services.Agent.Util; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { public class RSAFileKeyManager : AgentService, IRSAKeyManager { private string _keyFile; private IHostContext _context; public RSACryptoServiceProvider CreateKey() { RSACryptoServiceProvider rsa = null; if (!File.Exists(_keyFile)) { Trace.Info("Creating new RSA key using 2048-bit key length"); rsa = new RSACryptoServiceProvider(2048); // Now write the parameters to disk IOUtil.SaveObject(new RSAParametersSerializable(rsa.ExportParameters(true)), _keyFile); Trace.Info("Successfully saved RSA key parameters to file {0}", _keyFile); // Try to lock down the credentials_key file to the owner/group var whichUtil = _context.GetService<IWhichUtil>(); var chmodPath = whichUtil.Which("chmod"); if (!String.IsNullOrEmpty(chmodPath)) { var arguments = $"600 {new FileInfo(_keyFile).FullName}"; using (var invoker = _context.CreateService<IProcessInvoker>()) { var exitCode = invoker.ExecuteAsync(IOUtil.GetRootPath(), chmodPath, arguments, null, default(CancellationToken)).GetAwaiter().GetResult(); if (exitCode == 0) { Trace.Info("Successfully set permissions for RSA key parameters file {0}", _keyFile); } else { Trace.Warning("Unable to succesfully set permissions for RSA key parameters file {0}. Received exit code {1} from {2}", _keyFile, exitCode, chmodPath); } } } else { Trace.Warning("Unable to locate chmod to set permissions for RSA key parameters file {0}.", _keyFile); } } else { Trace.Info("Found existing RSA key parameters file {0}", _keyFile); rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(IOUtil.LoadObject<RSAParametersSerializable>(_keyFile).RSAParameters); } return rsa; } public void DeleteKey() { if (File.Exists(_keyFile)) { Trace.Info("Deleting RSA key parameters file {0}", _keyFile); File.Delete(_keyFile); } } public RSACryptoServiceProvider GetKey() { if (!File.Exists(_keyFile)) { throw new CryptographicException(StringUtil.Loc("RSAKeyFileNotFound", _keyFile)); } Trace.Info("Loading RSA key parameters from file {0}", _keyFile); var parameters = IOUtil.LoadObject<RSAParametersSerializable>(_keyFile).RSAParameters; var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(parameters); return rsa; } void IAgentService.Initialize(IHostContext context) { base.Initialize(context); _context = context; _keyFile = IOUtil.GetRSACredFilePath(); } } } #endif
36.969072
179
0.553263
[ "MIT" ]
mizho/vsts-agent
src/Agent.Listener/Configuration/RSAFileKeyManager.cs
3,588
C#
using SSDCPortal.Infrastructure.Storage.DataInterfaces; using SSDCPortal.Shared.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; namespace SSDCPortal.Storage { public static class ChangeTrackerExtensions { public static void SetShadowProperties(this ChangeTracker changeTracker, IUserSession userSession) { changeTracker.DetectChanges(); Guid? userId = null; DateTime timestamp = DateTime.UtcNow; if (userSession.UserId != Guid.Empty) userId = userSession.UserId; foreach (EntityEntry entry in changeTracker.Entries()) { //Auditable Entity Model if (entry.Entity is IAuditable) { if (entry.State == EntityState.Added) { entry.Property("CreatedOn").CurrentValue = timestamp; entry.Property("CreatedById").CurrentValue = userId; } if (entry.State == EntityState.Deleted || entry.State == EntityState.Modified) { entry.Property("ModifiedOn").CurrentValue = timestamp; entry.Property("ModifiedById").CurrentValue = userId; } } //Soft Delete Entity Model if (entry.State == EntityState.Deleted && entry.Entity is ISoftDelete) { entry.State = EntityState.Modified; entry.Property("IsDeleted").CurrentValue = true; } } } } }
36.361702
106
0.549444
[ "MIT" ]
slicksys/blazorboilerplate
src/Server/SSDCPortal.Storage/ChangeTrackerExtensions.cs
1,711
C#
////====================================================== //// Create by @Peng Guang Hui //// 2015/12/12 16:22:24 ////====================================================== //using System; //using System.Collections.Generic; //using UnityEngine; //using UnityEngine.UI; //namespace LogicEngine.Unity.Toolkit //{ // /// <summary> // /// Labels are graphics that display text. // /// </summary> // [AddComponentMenu("UI/Text", 10)] // public class Text : MaskableGraphic, ILayoutElement // { // [SerializeField] // private FontData m_FontData = FontData.defaultFontData; // [TextArea(3, 10)] // [SerializeField] // protected string m_Text = String.Empty; // private TextGenerator m_TextCache; // private TextGenerator m_TextCacheForLayout; // static protected Material s_DefaultText = null; // // We use this flag instead of Unregistering/Registering the callback to avoid allocation. // [NonSerialized] // protected bool m_DisableFontTextureRebuiltCallback = false; // protected Text() // { // //useLegacyMeshGeneration = false; // } // /// <summary> // /// Get or set the material used by this Text. // /// </summary> // public TextGenerator cachedTextGenerator // { // get { return m_TextCache ?? (m_TextCache = (m_Text.Length != 0 ? new TextGenerator(m_Text.Length) : new TextGenerator())); } // } // public TextGenerator cachedTextGeneratorForLayout // { // get { return m_TextCacheForLayout ?? (m_TextCacheForLayout = new TextGenerator()); } // } // /// <summary> // /// Text's texture comes from the font. // /// </summary> // public override Texture mainTexture // { // get // { // if (font != null && font.material != null && font.material.mainTexture != null) // return font.material.mainTexture; // if (m_Material != null) // return m_Material.mainTexture; // return base.mainTexture; // } // } // public void FontTextureChanged() // { // // Only invoke if we are not destroyed. // if (!this) // { // //FontUpdateTracker.UntrackText(this); // return; // } // if (m_DisableFontTextureRebuiltCallback) // return; // cachedTextGenerator.Invalidate(); // if (!IsActive()) // return; // // this is a bit hacky, but it is currently the // // cleanest solution.... // // if we detect the font texture has changed and are in a rebuild loop // // we just regenerate the verts for the new UV's // if (CanvasUpdateRegistry.IsRebuildingGraphics() || CanvasUpdateRegistry.IsRebuildingLayout()) // UpdateGeometry(); // else // SetAllDirty(); // } // public Font font // { // get // { // return m_FontData.font; // } // set // { // if (m_FontData.font == value) // return; // //FontUpdateTracker.UntrackText(this); // m_FontData.font = value; // //FontUpdateTracker.TrackText(this); // SetAllDirty(); // } // } // /// <summary> // /// Text that's being displayed by the Text. // /// </summary> // public virtual string text // { // get // { // return m_Text; // } // set // { // if (String.IsNullOrEmpty(value)) // { // if (String.IsNullOrEmpty(m_Text)) // return; // m_Text = ""; // SetVerticesDirty(); // } // else if (m_Text != value) // { // m_Text = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // } // /// <summary> // /// Whether this Text will support rich text. // /// </summary> // public bool supportRichText // { // get // { // return m_FontData.richText; // } // set // { // if (m_FontData.richText == value) // return; // m_FontData.richText = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // /// <summary> // /// Wrap mode used by the text. // /// </summary> // public bool resizeTextForBestFit // { // get // { // return m_FontData.bestFit; // } // set // { // if (m_FontData.bestFit == value) // return; // m_FontData.bestFit = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // public int resizeTextMinSize // { // get // { // return m_FontData.minSize; // } // set // { // if (m_FontData.minSize == value) // return; // m_FontData.minSize = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // public int resizeTextMaxSize // { // get // { // return m_FontData.maxSize; // } // set // { // if (m_FontData.maxSize == value) // return; // m_FontData.maxSize = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // /// <summary> // /// Alignment anchor used by the text. // /// </summary> // public TextAnchor alignment // { // get // { // return m_FontData.alignment; // } // set // { // if (m_FontData.alignment == value) // return; // m_FontData.alignment = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // public int fontSize // { // get // { // return m_FontData.fontSize; // } // set // { // if (m_FontData.fontSize == value) // return; // m_FontData.fontSize = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // public HorizontalWrapMode horizontalOverflow // { // get // { // return m_FontData.horizontalOverflow; // } // set // { // if (m_FontData.horizontalOverflow == value) // return; // m_FontData.horizontalOverflow = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // public VerticalWrapMode verticalOverflow // { // get // { // return m_FontData.verticalOverflow; // } // set // { // if (m_FontData.verticalOverflow == value) // return; // m_FontData.verticalOverflow = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // public float lineSpacing // { // get // { // return m_FontData.lineSpacing; // } // set // { // if (m_FontData.lineSpacing == value) // return; // m_FontData.lineSpacing = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // /// <summary> // /// Font style used by the Text's text. // /// </summary> // public FontStyle fontStyle // { // get // { // return m_FontData.fontStyle; // } // set // { // if (m_FontData.fontStyle == value) // return; // m_FontData.fontStyle = value; // SetVerticesDirty(); // SetLayoutDirty(); // } // } // public float pixelsPerUnit // { // get // { // var localCanvas = canvas; // if (!localCanvas) // return 1; // // For dynamic fonts, ensure we use one pixel per pixel on the screen. // if (!font || font.dynamic) // return localCanvas.scaleFactor; // // For non-dynamic fonts, calculate pixels per unit based on specified font size relative to font object's own font size. // if (m_FontData.fontSize <= 0 || font.fontSize <= 0) // return 1; // return font.fontSize / (float)m_FontData.fontSize; // } // } // protected override void OnEnable() // { // base.OnEnable(); // cachedTextGenerator.Invalidate(); // //FontUpdateTracker.TrackText(this); // } // protected override void OnDisable() // { // //FontUpdateTracker.UntrackText(this); // base.OnDisable(); // } // protected override void UpdateGeometry() // { // if (font != null) // { // base.UpdateGeometry(); // } // } //#if UNITY_EDITOR // protected override void Reset() // { // font = Resources.GetBuiltinResource<Font>("Arial.ttf"); // } //#endif // public TextGenerationSettings GetGenerationSettings(Vector2 extents) // { // var settings = new TextGenerationSettings(); // settings.generationExtents = extents; // if (font != null && font.dynamic) // { // settings.fontSize = m_FontData.fontSize; // settings.resizeTextMinSize = m_FontData.minSize; // settings.resizeTextMaxSize = m_FontData.maxSize; // } // // Other settings // settings.textAnchor = m_FontData.alignment; // settings.scaleFactor = pixelsPerUnit; // settings.color = color; // settings.font = font; // settings.pivot = rectTransform.pivot; // settings.richText = m_FontData.richText; // settings.lineSpacing = m_FontData.lineSpacing; // settings.fontStyle = m_FontData.fontStyle; // settings.resizeTextForBestFit = m_FontData.bestFit; // settings.updateBounds = false; // settings.horizontalOverflow = m_FontData.horizontalOverflow; // settings.verticalOverflow = m_FontData.verticalOverflow; // return settings; // } // static public Vector2 GetTextAnchorPivot(TextAnchor anchor) // { // switch (anchor) // { // case TextAnchor.LowerLeft: return new Vector2(0, 0); // case TextAnchor.LowerCenter: return new Vector2(0.5f, 0); // case TextAnchor.LowerRight: return new Vector2(1, 0); // case TextAnchor.MiddleLeft: return new Vector2(0, 0.5f); // case TextAnchor.MiddleCenter: return new Vector2(0.5f, 0.5f); // case TextAnchor.MiddleRight: return new Vector2(1, 0.5f); // case TextAnchor.UpperLeft: return new Vector2(0, 1); // case TextAnchor.UpperCenter: return new Vector2(0.5f, 1); // case TextAnchor.UpperRight: return new Vector2(1, 1); // default: return Vector2.zero; // } // } // readonly UIVertex[] m_TempVerts = new UIVertex[4]; // protected override void OnPopulateMesh(VertexHelper toFill) // { // if (font == null) // return; // // We don't care if we the font Texture changes while we are doing our Update. // // The end result of cachedTextGenerator will be valid for this instance. // // Otherwise we can get issues like Case 619238. // m_DisableFontTextureRebuiltCallback = true; // Vector2 extents = rectTransform.rect.size; // var settings = GetGenerationSettings(extents); // cachedTextGenerator.Populate(text, settings); // Rect inputRect = rectTransform.rect; // // get the text alignment anchor point for the text in local space // Vector2 textAnchorPivot = GetTextAnchorPivot(m_FontData.alignment); // Vector2 refPoint = Vector2.zero; // refPoint.x = (textAnchorPivot.x == 1 ? inputRect.xMax : inputRect.xMin); // refPoint.y = (textAnchorPivot.y == 0 ? inputRect.yMin : inputRect.yMax); // // Determine fraction of pixel to offset text mesh. // Vector2 roundingOffset = PixelAdjustPoint(refPoint) - refPoint; // // Apply the offset to the vertices // IList<UIVertex> verts = cachedTextGenerator.verts; // float unitsPerPixel = 1 / pixelsPerUnit; // //Last 4 verts are always a new line... // int vertCount = verts.Count - 4; // toFill.Clear(); // if (roundingOffset != Vector2.zero) // { // for (int i = 0; i < vertCount; ++i) // { // int tempVertsIndex = i & 3; // m_TempVerts[tempVertsIndex] = verts[i]; // m_TempVerts[tempVertsIndex].position *= unitsPerPixel; // m_TempVerts[tempVertsIndex].position.x += roundingOffset.x; // m_TempVerts[tempVertsIndex].position.y += roundingOffset.y; // if (tempVertsIndex == 3) // toFill.AddUIVertexQuad(m_TempVerts); // } // } // else // { // for (int i = 0; i < vertCount; ++i) // { // int tempVertsIndex = i & 3; // m_TempVerts[tempVertsIndex] = verts[i]; // m_TempVerts[tempVertsIndex].position *= unitsPerPixel; // if (tempVertsIndex == 3) // toFill.AddUIVertexQuad(m_TempVerts); // } // } // m_DisableFontTextureRebuiltCallback = false; // } // public virtual void CalculateLayoutInputHorizontal() { } // public virtual void CalculateLayoutInputVertical() { } // public virtual float minWidth // { // get { return 0; } // } // public virtual float preferredWidth // { // get // { // var settings = GetGenerationSettings(Vector2.zero); // return cachedTextGeneratorForLayout.GetPreferredWidth(m_Text, settings) / pixelsPerUnit; // } // } // public virtual float flexibleWidth { get { return -1; } } // public virtual float minHeight // { // get { return 0; } // } // public virtual float preferredHeight // { // get // { // var settings = GetGenerationSettings(new Vector2(rectTransform.rect.size.x, 0.0f)); // return cachedTextGeneratorForLayout.GetPreferredHeight(m_Text, settings) / pixelsPerUnit; // } // } // public virtual float flexibleHeight { get { return -1; } } // public virtual int layoutPriority { get { return 0; } } //#if UNITY_EDITOR // public override void OnRebuildRequested() // { // // After a Font asset gets re-imported the managed side gets deleted and recreated, // // that means the delegates are not persisted. // // so we need to properly enforce a consistent state here. // FontUpdateTracker.UntrackText(this); // FontUpdateTracker.TrackText(this); // // Also the textgenerator is no longer valid. // cachedTextGenerator.Invalidate(); // base.OnRebuildRequested(); // } //#endif // if UNITY_EDITOR // } //}
32.445269
140
0.453511
[ "MIT" ]
corefan/LogicEngine
LogicEngine/LogicEngine.Unity/Toolkit/TextFont.cs
17,490
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; using Xamarin.Forms; using PartlyNewsy.Core; namespace PartlyNewsy.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental"); global::Xamarin.Forms.Forms.Init(); FormsMaterial.Init(); LoadApplication(new App()); var authService = DependencyService.Get<IAuthenticationService>(); authService.SetParent(null); return base.FinishedLaunching(app, options); } } }
31.545455
98
0.676513
[ "MIT" ]
codemillmatt/xam-dev-summit
demos/demo-1/PartlyNewsy.iOS/AppDelegate.cs
1,390
C#
using CoreJWT.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; namespace CoreJWT.Concretes { public class JWSPayload { public string Issuer { get; set; } public string Subject { get; set; } public string Audience { get; set; } public DateTime? ExpirationTime { get; set; } public DateTime? NotBefore { get; set; } public DateTime? IssuedAt { get; set; } public string ID { get; set; } public Dictionary<string, dynamic> ClaimsSet { get; set; } = new Dictionary<string, dynamic>(); public string Serialize() { var tempClaims = new Dictionary<string, dynamic>(ClaimsSet); if (!string.IsNullOrEmpty(Issuer)) tempClaims.Add("iss", Issuer); if (!string.IsNullOrEmpty(Subject)) tempClaims.Add("sub", Subject); if (!string.IsNullOrEmpty(ID)) tempClaims.Add("jti", ID); if (!string.IsNullOrEmpty(Audience)) tempClaims.Add("aud", Audience); if (ExpirationTime != null) tempClaims.Add("exp", ExpirationTime.Value.Encode()); if (NotBefore != null) tempClaims.Add("nbf", NotBefore.Value.Encode()); if (IssuedAt != null) tempClaims.Add("iat", IssuedAt.Value.Encode()); return JsonConvert.SerializeObject(tempClaims); } public static JWSPayload Deserialize(string json) { var result = new JWSPayload(); try { var process = (JObject)JsonConvert.DeserializeObject(json); foreach (JToken child in process.Children()) { var key = ((JProperty)child).Name; var value = ((JProperty)child).Value; switch (key) { case "iss": { result.Issuer = (string)value; break; } case "sub": { result.Subject = (string)value; break; } case "jti": { result.ID = (string)value; break; } case "aud": { result.Audience = (string)value; break; } case "exp": { result.ExpirationTime = ((int)value).Decode(); break; } case "nbf": { result.NotBefore = ((int)value).Decode(); break; } case "iat": { result.IssuedAt = ((int)value).Decode(); break; } default: { result.ClaimsSet.Add(key, value); break; } } } } catch { // no matter what error is raised this means that // the token is not ok so throw the invalid error throw new Exception("Token is invalid!"); } return result; } } }
34.80531
103
0.387999
[ "MIT" ]
GZidar/CoreJWT
src/Concretes/JWSPayload.cs
3,935
C#
namespace SecondMonitor.Rating.Common.DataModel { using System.Collections.Generic; using System.Xml.Serialization; using Player; public class ClassRating { public ClassRating() { AiRatings = new List<DriverWithoutRating>(); } [XmlAttribute] public string ClassName { get; set; } public DriversRating PlayersRating { get; set; } public DriversRating DifficultyRating { get; set; } public DifficultySettings DifficultySettings { get; set; } public List<DriverWithoutRating> AiRatings { get; set; } } }
25.56
67
0.616588
[ "MIT" ]
plkumar/SecondMonitor
Rating/Rating.Common/DataModel/ClassRating.cs
641
C#
using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Imgur.API")] [assembly: AssemblyDescription("Imgur.API is a .NET implementation of Imgur's v3 API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Damien Dennehy")] [assembly: AssemblyProduct("Imgur.API")] [assembly: AssemblyCopyright("Copyright © 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Imgur.API.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
43.352941
88
0.784261
[ "MIT" ]
drasticactions/AwfulRedux
Imgur/Properties/AssemblyInfo.cs
740
C#
using Unity.DataFlowGraph; using Unity.Entities; using Unity.NetCode; using Unity.Sample.Core; public static class AnimSource { [ConfigVar(Name = "animsource.show.lifetime", DefaultValue = "0", Description = "Show animsource lifetime")] public static ConfigVar ShowLifetime; public struct HasValidRig : IComponentData { } public struct Data : IComponentData { public Entity animStateEntity; public NodeHandle outputNode; public NodeHandle inputNode; public OutputPortID outputPortID; public InputPortID inputPortID; } // Component put on animsources that are allowed to update state of animStateEntity public struct AllowWrite : IComponentData { public static AllowWrite Default => new AnimSource.AllowWrite {FirstUpdate = true}; public bool FirstUpdate; } public static bool ShouldPredict(ComponentDataFromEntity<PredictedGhostComponent> predictedGhostComponentFromEntity, in Data animSource, uint predictTick) { if (!predictedGhostComponentFromEntity.HasComponent(animSource.animStateEntity)) return false; var predictEntity = predictedGhostComponentFromEntity[animSource.animStateEntity]; return GhostPredictionSystemGroup.ShouldPredict(predictTick, predictEntity); } public static void SetAnimStateEntityOnPrefab(EntityManager entityManager, Entity prefabEntity, Entity animStateEntity, EntityCommandBuffer cmdBuffer) { // Set AnimSource animStateEntity var linkedEntityBuffer = entityManager.GetBuffer<LinkedEntityGroup>(prefabEntity); for (int j = 0; j < linkedEntityBuffer.Length; j++) { var e = linkedEntityBuffer[j].Value; if (!entityManager.HasComponent<Data>(e)) continue; var animSource = entityManager.GetComponentData<Data>(e); animSource.animStateEntity = animStateEntity; cmdBuffer.SetComponent(e, animSource); } } public static void SetAnimStateEntityOnPrefab(EntityManager entityManager, Entity prefabEntity, Entity animStateEntity) { // Set AnimSource animStateEntity var linkedEntityBuffer = entityManager.GetBuffer<LinkedEntityGroup>(prefabEntity); for (int j = 0; j < linkedEntityBuffer.Length; j++) { var e = linkedEntityBuffer[j].Value; if (!entityManager.HasComponent<Data>(e)) continue; var animSource = entityManager.GetComponentData<Data>(e); animSource.animStateEntity = animStateEntity; entityManager.SetComponentData(e, animSource); } } }
36.767123
158
0.697466
[ "MIT" ]
The-ULTIMATE-MULTIPLAYER-EXPERIENCE/Ultimate-Archery-Multiplayer-Unity-Game
DOTSSample-master/Assets/Unity.Sample.Game/AnimSource/AnimSource.cs
2,686
C#
using JSC_LMS.Application.Features.Gallary.Commands.UploadImage; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JSC_LSM.UI.ResponseModels.GallaryResponseModel { public class AddGallaryResponseModel { public bool Succeeded { get; set; } public string message { get; set; } public string statusCode { get; set; } public UploadImageDto data { get; set; } } }
27.176471
65
0.71645
[ "Apache-2.0" ]
ashishneosoftmail/JSC_LMS
src/UI/JSC_LSM.UI/ResponseModels/GallaryResponseModel/AddGallaryResponseModel.cs
464
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Xml; using System.Linq; using System.Collections.Generic; using Trifolia.Shared; using Trifolia.Shared.ImportExport; using ExportTemplate = Trifolia.Shared.ImportExport.Model.TrifoliaTemplate; using ExportConformanceTypes = Trifolia.Shared.ImportExport.Model.ConstraintTypeConformance; using Trifolia.DB; using Trifolia.Export.Native; namespace Trifolia.Test.Generation.XML { /// <summary> ///This is a test class for TemplateExportFactoryTest and is intended ///to contain all TemplateExportFactoryTest Unit Tests ///</summary> [TestClass()] public class TemplateExportTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion [TestMethod] public void ExportTemplatesModelTest1() { MockObjectRepository tdb = new MockObjectRepository(); tdb.InitializeCDARepository(); Organization org = tdb.FindOrAddOrganization("LCG Test"); ImplementationGuide ig = tdb.FindOrAddImplementationGuide(tdb.FindImplementationGuideType(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME), "Test Implementation Guide"); IGSettingsManager igSettings = new IGSettingsManager(tdb, ig.Id); Template template = tdb.GenerateTemplate("1.2.3.4", "Document", "Test Template", ig, "observation", "Observation", "Test Description", "Test Notes", org); var tc1 = tdb.GenerateConstraint(template, null, null, "entryRelationship", "SHALL", "1..1"); var tc2 = tdb.GenerateConstraint(template, tc1, null, "observation", "SHOULD", "0..1"); var tc3 = tdb.GenerateConstraint(template, tc2, null, "value", "SHALL", "1..1", "CD", value: "4321", displayName: "Test"); tc3.Description = "Test description"; tc3.Label = "Test Label"; var tc4 = tdb.GeneratePrimitive(template, null, "SHALL", "This is a test"); ExportTemplate export = template.Export(tdb, igSettings); Assert.IsNotNull(export); Assert.AreEqual(template.Oid, export.identifier); Assert.AreEqual(template.Name, export.title); Assert.AreEqual(template.TemplateType.Name, export.templateType); Assert.AreEqual(template.PrimaryContext, export.context); Assert.AreEqual(template.PrimaryContextType, export.contextType); Assert.AreEqual(template.Description, export.Description); Assert.AreEqual(template.Notes, export.Notes); // Assert constraints Assert.IsNotNull(export.Constraint); Assert.AreEqual(2, export.Constraint.Count); // tc1 Assert.AreEqual(tc1.Context, export.Constraint[0].context); Assert.AreEqual(ExportConformanceTypes.SHALL, export.Constraint[0].conformance); Assert.AreEqual(tc1.Cardinality, export.Constraint[0].cardinality); // tc4 Assert.IsNull(export.Constraint[1].context); Assert.AreEqual(true, export.Constraint[1].isPrimitive); Assert.AreEqual(tc4.PrimitiveText, export.Constraint[1].NarrativeText); // tc2 Assert.AreEqual(1, export.Constraint[0].Constraint.Count); Assert.AreEqual(tc2.Context, export.Constraint[0].Constraint[0].context); Assert.AreEqual(ExportConformanceTypes.SHOULD, export.Constraint[0].Constraint[0].conformance); Assert.AreEqual(tc2.Cardinality, export.Constraint[0].Constraint[0].cardinality); // tc3 Assert.AreEqual(1, export.Constraint[0].Constraint[0].Constraint.Count); Assert.AreEqual(tc3.Context, export.Constraint[0].Constraint[0].Constraint[0].context); Assert.AreEqual(ExportConformanceTypes.SHALL, export.Constraint[0].Constraint[0].Constraint[0].conformance); Assert.AreEqual(tc3.Cardinality, export.Constraint[0].Constraint[0].Constraint[0].cardinality); Assert.AreEqual(tc3.Description, export.Constraint[0].Constraint[0].Constraint[0].Description); Assert.AreEqual(tc3.Label, export.Constraint[0].Constraint[0].Constraint[0].Label); Assert.IsFalse(string.IsNullOrEmpty(export.Constraint[0].Constraint[0].Constraint[0].Description)); } [TestMethod] public void ExportTemplatesModelTest2() { MockObjectRepository tdb = new MockObjectRepository(); tdb.InitializeCDARepository(); Organization org = tdb.FindOrAddOrganization("LCG Test"); ImplementationGuide ig = tdb.FindOrAddImplementationGuide(tdb.FindImplementationGuideType(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME), "Test Implementation Guide"); IGSettingsManager igSettings = new IGSettingsManager(tdb, ig.Id); Template template = tdb.GenerateTemplate("1.2.3.4", "Document", "Test Template", ig, "observation", "Observation", "Test Description", "Test Notes"); ExportTemplate export = template.Export(tdb, igSettings); Assert.IsNotNull(export); Assert.AreEqual(template.Oid, export.identifier); Assert.AreEqual(template.Name, export.title); Assert.AreEqual(template.TemplateType.Name, export.templateType); Assert.AreEqual(template.PrimaryContext, export.context); Assert.AreEqual(template.PrimaryContextType, export.contextType); Assert.AreEqual(template.Description, export.Description); Assert.AreEqual(template.Notes, export.Notes); Assert.AreEqual(template.OwningImplementationGuide.Name, export.ImplementationGuide.name); } /// <summary> /// Generates mock dataset 1 and exports the templates from the dataset into XML format. /// Tests that the resulting XML contains the correct number templates, that the attributes on the first template /// are set properly, and lastly tests the number of constraints output for the first exported template. ///</summary> [TestMethod()] public void ExportTemplatesTest() { MockObjectRepository tdb = TestDataGenerator.GenerateMockDataset1(); List<Template> templates = tdb.Templates.ToList(); IGSettingsManager igSettings = new IGSettingsManager(tdb); TemplateExporter exporter = new TemplateExporter(tdb, templates, igSettings); string actual = exporter.GenerateXMLExport(); Assert.IsNotNull(actual, "Export should have produced content."); Assert.AreNotEqual(string.Empty, actual, "Export should have produced content."); XmlDocument exportDoc = new XmlDocument(); exportDoc.LoadXml(actual); XmlNamespaceManager nsManager = new XmlNamespaceManager(exportDoc.NameTable); nsManager.AddNamespace("lcg", "http://www.lantanagroup.com"); XmlNodeList templateNodes = exportDoc.DocumentElement.SelectNodes("lcg:Template", nsManager); Assert.IsNotNull(templateNodes, "Did not find any templates in export."); Assert.AreEqual(4, templateNodes.Count, "Export should have produced three (4) Template elements."); XmlAttribute identifierAttribute = templateNodes[0].Attributes["identifier"]; XmlAttribute implementationGuideTypeAttribute = templateNodes[0].Attributes["implementationGuideType"]; XmlAttribute templateTypeAttribute = templateNodes[0].Attributes["templateType"]; XmlAttribute titleAttribute = templateNodes[0].Attributes["title"]; XmlAttribute bookmarkAttribute = templateNodes[0].Attributes["bookmark"]; Assert.IsNotNull(identifierAttribute, "Couldn't find identifier attribute on Template."); Assert.AreEqual("1.2.3.4.5", identifierAttribute.Value, "Template's identifier has an incorrect value."); Assert.IsNotNull(implementationGuideTypeAttribute, "Couldn't find implementationGuideType attribute on Template."); Assert.AreEqual(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME, implementationGuideTypeAttribute.Value, "Template's implementationGuideType has an incorrect value."); Assert.IsNotNull(templateTypeAttribute, "Couldn't find templateType attribute on Template."); Assert.AreEqual("Document", templateTypeAttribute.Value, "Template's templateType has an incorrect value."); Assert.IsNotNull(titleAttribute, "Couldn't find title attribute on Template."); Assert.AreEqual("Test Template 1", titleAttribute.Value, "Template's title has an incorrect value."); Assert.IsNotNull(bookmarkAttribute, "Couldn't find bookmark attribute on Template."); Assert.AreEqual("D_Test_Template_1", bookmarkAttribute.Value, "Template's bookmark has an incorrect value."); XmlNodeList constraintNodes = templateNodes[0].SelectNodes("lcg:Constraint", nsManager); Assert.IsNotNull(constraintNodes, "Did not find any constraints in the first template."); Assert.AreEqual(3, constraintNodes.Count, "Did not find the correct number of root-level constraints in the first exported template."); XmlNodeList childConstraintNodes = constraintNodes[1].SelectNodes("lcg:Constraint", nsManager); Assert.IsNotNull(childConstraintNodes, "Did not find any grand-child constraints in the first template."); Assert.AreEqual(1, childConstraintNodes.Count, "Did not find the correct number of grand-child constraints in the first exported template."); } } }
50.141553
179
0.671068
[ "Apache-2.0" ]
BOBO41/trifolia
Trifolia.Test/Generation/XML/TemplateExportTest.cs
10,983
C#
/******************************************************************************* * Copyright (c) 2011 Rylan Cottrell. iCottrell.com. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Rylan Cottrell - initial API and implementation and/or initial documentation *******************************************************************************/ using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace com.iCottrell.IronChariots { public static class SearchResultsContainer { public static ObservableCollection<SearchResults> SearchResultItems = new ObservableCollection<SearchResults>(); } public class SearchResults { public String Href { get; set; } public String Title { get; set; } public String Description { get; set; } public String Category { get; set; } public SearchResults() { Href = ""; Title = ""; Description = ""; Category = ""; } } }
30.75
118
0.610434
[ "EPL-1.0" ]
rylan/Iron-Chariots
wp7/com.iCottrell.IronChariots/SearchResults.cs
1,478
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 02.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableDECIMAL_6_1.Int64{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Decimal>; using T_DATA2 =System.Int64; using T_DATA1_U=System.Decimal; using T_DATA2_U=System.Int64; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__01__VV public static class TestSet_001__fields__01__VV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_DEC_6_1"; private const string c_NameOf__COL_DATA2 ="COL2_BIGINT"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1,TypeName="DECIMAL(6,1)")] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=3; const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ < /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" < ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableDECIMAL_6_1.Int64
30.033113
151
0.567365
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/LessThan/Complete/NullableDECIMAL_6_1/Int64/TestSet_001__fields__01__VV.cs
4,537
C#
// ----------------------------------------------------------------------------- // 让 .NET 开发更简单,更通用,更流行。 // Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd. // // 框架名称:Furion // 框架作者:百小僧 // 框架版本:2.8.3 // 源码地址:Gitee: https://gitee.com/dotnetchina/Furion // Github:https://github.com/monksoul/Furion // 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE) // ----------------------------------------------------------------------------- using System; namespace Furion.DependencyInjection { /// <summary> /// 设置依赖注入方式 /// </summary> [SkipScan, AttributeUsage(AttributeTargets.Class)] public class InjectionAttribute : Attribute { /// <summary> /// 构造函数 /// </summary> /// <param name="expectInterfaces"></param> public InjectionAttribute(params Type[] expectInterfaces) { Action = InjectionActions.Add; Pattern = InjectionPatterns.SelfWithFirstInterface; ExpectInterfaces = expectInterfaces ?? Array.Empty<Type>(); Order = 0; } /// <summary> /// 构造函数 /// </summary> /// <param name="action"></param> /// <param name="expectInterfaces"></param> public InjectionAttribute(InjectionActions action, params Type[] expectInterfaces) { Action = action; Pattern = InjectionPatterns.SelfWithFirstInterface; ExpectInterfaces = expectInterfaces ?? Array.Empty<Type>(); Order = 0; } /// <summary> /// 添加服务方式,存在不添加,或继续添加 /// </summary> public InjectionActions Action { get; set; } /// <summary> /// 注册选项 /// </summary> public InjectionPatterns Pattern { get; set; } /// <summary> /// 注册别名 /// </summary> /// <remarks>多服务时使用</remarks> public string Named { get; set; } /// <summary> /// 排序,排序越大,则在后面注册 /// </summary> public int Order { get; set; } /// <summary> /// 排除接口 /// </summary> public Type[] ExpectInterfaces { get; set; } /// <summary> /// 代理类型,必须继承 DispatchProxy、IDispatchProxy /// </summary> public Type Proxy { get; set; } } }
29.227848
90
0.508012
[ "Apache-2.0" ]
dannylincn/Furion
framework/Furion/DependencyInjection/Attributes/InjectionAttribute.cs
2,564
C#
using System.Collections.Generic; using System.Linq; using Jint.Native.Array; using Jint.Native.Global; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; namespace Jint.Native.Json { public class JsonSerializer { private readonly Engine _engine; public JsonSerializer(Engine engine) { _engine = engine; } Stack<object> _stack; string _indent, _gap; List<JsValue> _propertyList; JsValue _replacerFunction = Undefined.Instance; public JsValue Serialize(JsValue value, JsValue replacer, JsValue space) { _stack = new Stack<object>(); // for JSON.stringify(), any function passed as the first argument will return undefined // if the replacer is not defined. The function is not called either. if (value is ICallable callable && ReferenceEquals(replacer, Undefined.Instance)) { return Undefined.Instance; } if (replacer.IsObject()) { if (replacer is ICallable) { _replacerFunction = replacer; } else { var replacerObj = replacer.AsObject(); if (replacerObj.Class == ObjectClass.Array) { _propertyList = new List<JsValue>(); } foreach (var property in replacerObj.GetOwnProperties().Select(x => x.Value)) { JsValue v = _engine.GetValue(property, false); string item = null; if (v.IsString()) { item = v.ToString(); } else if (v.IsNumber()) { item = TypeConverter.ToString(v); } else if (v.IsObject()) { var propertyObj = v.AsObject(); if (propertyObj.Class == ObjectClass.String || propertyObj.Class == ObjectClass.Number) { item = TypeConverter.ToString(v); } } if (item != null && !_propertyList.Contains(item)) { _propertyList.Add(item); } } } } if (space.IsObject()) { var spaceObj = space.AsObject(); if (spaceObj.Class == ObjectClass.Number) { space = TypeConverter.ToNumber(spaceObj); } else if (spaceObj.Class == ObjectClass.String) { space = TypeConverter.ToJsString(spaceObj); } } // defining the gap if (space.IsNumber()) { var number = ((JsNumber) space)._value; if (number > 0) { _gap = new string(' ', (int) System.Math.Min(10, number)); } else { _gap = string.Empty; } } else if (space.IsString()) { var stringSpace = space.ToString(); _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10); } else { _gap = string.Empty; } var wrapper = _engine.Object.Construct(Arguments.Empty); wrapper.DefineOwnProperty(JsString.Empty, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable)); return Str(JsString.Empty, wrapper); } private JsValue Str(JsValue key, ObjectInstance holder) { var value = holder.Get(key, holder); if (value.IsObject()) { var toJson = value.AsObject().Get("toJSON", value); if (toJson.IsObject()) { if (toJson.AsObject() is ICallable callableToJson) { value = callableToJson.Call(value, Arguments.From(key)); } } } if (!ReferenceEquals(_replacerFunction, Undefined.Instance)) { var replacerFunctionCallable = (ICallable)_replacerFunction.AsObject(); value = replacerFunctionCallable.Call(holder, Arguments.From(key, value)); } if (value.IsObject()) { var valueObj = value.AsObject(); switch (valueObj.Class) { case ObjectClass.Number: value = TypeConverter.ToNumber(value); break; case ObjectClass.String: value = TypeConverter.ToString(value); break; case ObjectClass.Boolean: value = TypeConverter.ToPrimitive(value); break; case ObjectClass.Array: value = SerializeArray(value.As<ArrayInstance>()); return value; case ObjectClass.Object: value = SerializeObject(value.AsObject()); return value; } } if (ReferenceEquals(value, Null.Instance)) { return "null"; } if (value.IsBoolean()) { return ((JsBoolean) value)._value ? "true" : "false"; } if (value.IsString()) { return Quote(value.ToString()); } if (value.IsNumber()) { var isFinite = GlobalObject.IsFinite(Undefined.Instance, Arguments.From(value)); if (((JsBoolean) isFinite)._value) { return TypeConverter.ToJsString(value); } return "null"; } var isCallable = value.IsObject() && value.AsObject() is ICallable; if (value.IsObject() && isCallable == false) { if (value.AsObject().Class == ObjectClass.Array) { return SerializeArray(value.As<ArrayInstance>()); } return SerializeObject(value.AsObject()); } return JsValue.Undefined; } private static string Quote(string value) { var sb = new System.Text.StringBuilder("\""); foreach (char c in value) { switch (c) { case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; default: if (c < 0x20) { sb.Append("\\u"); sb.Append(((int) c).ToString("x4")); } else sb.Append(c); break; } } sb.Append("\""); return sb.ToString(); } private string SerializeArray(ArrayInstance value) { EnsureNonCyclicity(value); _stack.Push(value); var stepback = _indent; _indent = _indent + _gap; var partial = new List<string>(); var len = TypeConverter.ToUint32(value.Get(CommonProperties.Length, value)); for (int i = 0; i < len; i++) { var strP = Str(TypeConverter.ToString(i), value); if (strP.IsUndefined()) strP = "null"; partial.Add(strP.ToString()); } if (partial.Count == 0) { _stack.Pop(); return "[]"; } string final; if (_gap == "") { var separator = ","; var properties = System.String.Join(separator, partial.ToArray()); final = "[" + properties + "]"; } else { var separator = ",\n" + _indent; var properties = System.String.Join(separator, partial.ToArray()); final = "[\n" + _indent + properties + "\n" + stepback + "]"; } _stack.Pop(); _indent = stepback; return final; } private void EnsureNonCyclicity(object value) { if (value == null) { ExceptionHelper.ThrowArgumentNullException(nameof(value)); } if (_stack.Contains(value)) { ExceptionHelper.ThrowTypeError(_engine, "Cyclic reference detected."); } } private string SerializeObject(ObjectInstance value) { string final; EnsureNonCyclicity(value); _stack.Push(value); var stepback = _indent; _indent += _gap; var k = _propertyList ?? value.GetOwnProperties() .Where(x => x.Value.Enumerable) .Select(x => x.Key) .ToList(); var partial = new List<string>(); foreach (var p in k) { var strP = Str(p, value); if (!strP.IsUndefined()) { var member = Quote(p.ToString()) + ":"; if (_gap != "") { member += " "; } member += strP.AsString(); // TODO:This could be undefined partial.Add(member); } } if (partial.Count == 0) { final = "{}"; } else { if (_gap == "") { var separator = ","; var properties = System.String.Join(separator, partial.ToArray()); final = "{" + properties + "}"; } else { var separator = ",\n" + _indent; var properties = System.String.Join(separator, partial.ToArray()); final = "{\n" + _indent + properties + "\n" + stepback + "}"; } } _stack.Pop(); _indent = stepback; return final; } } }
33.368421
131
0.39208
[ "MIT" ]
Bargest/LogicExtensions
Jint/Native/Json/JsonSerializer.cs
12,048
C#
using MediatR; using System.Collections.Generic; namespace Application.Comments.Queries.GetPhotoComments { public class GetPhotoCommentsQuery : IRequest<IEnumerable<PhotoCommentsList>> { public System.Guid PhotoId { get; set; } } }
21.916667
81
0.718631
[ "MIT" ]
iamprovidence/Lama
src/backend/LamaAPI/Application/Comments/Queries/GetPhotoComments/GetPhotoCommentsQuery.cs
265
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Academy.Models.Enums { public enum ResourseType { Video, Presentation, Homework, Demo } }
15.411765
33
0.660305
[ "MIT" ]
iliyaST/TelericAcademy
OOP/7-Exams/FinalExam/Academy/Models/Enums/ResourseType.cs
264
C#
#pragma checksum "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\Shared\_CookieConsentPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5c18f8c7ec540a446e15b225511cfa1a006e3ec3" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__CookieConsentPartial), @"mvc.1.0.view", @"/Views/Shared/_CookieConsentPartial.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/_CookieConsentPartial.cshtml", typeof(AspNetCore.Views_Shared__CookieConsentPartial))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\_ViewImports.cshtml" using MultasTransito; #line default #line hidden #line 2 "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\_ViewImports.cshtml" using MultasTransito.Models; #line default #line hidden #line 1 "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\Shared\_CookieConsentPartial.cshtml" using Microsoft.AspNetCore.Http.Features; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5c18f8c7ec540a446e15b225511cfa1a006e3ec3", @"/Views/Shared/_CookieConsentPartial.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"71c63bbded5c51ccab2361d7644f35dd7e9119b9", @"/Views/_ViewImports.cshtml")] public class Views_Shared__CookieConsentPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Home", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Privacy", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-info navbar-btn"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(43, 2, true); WriteLiteral("\r\n"); EndContext(); #line 3 "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\Shared\_CookieConsentPartial.cshtml" var consentFeature = Context.Features.Get<ITrackingConsentFeature>(); var showBanner = !consentFeature?.CanTrack ?? false; var cookieString = consentFeature?.CreateConsentCookie(); #line default #line hidden BeginContext(248, 2, true); WriteLiteral("\r\n"); EndContext(); #line 9 "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\Shared\_CookieConsentPartial.cshtml" if (showBanner) { #line default #line hidden BeginContext(271, 963, true); WriteLiteral(@" <nav id=""cookieConsent"" class=""navbar navbar-default navbar-fixed-top"" role=""alert""> <div class=""container""> <div class=""navbar-header""> <button type=""button"" class=""navbar-toggle"" data-toggle=""collapse"" data-target=""#cookieConsent .navbar-collapse""> <span class=""sr-only"">Toggle cookie consent banner</span> <span class=""icon-bar""></span> <span class=""icon-bar""></span> <span class=""icon-bar""></span> </button> <span class=""navbar-brand""><span class=""glyphicon glyphicon-info-sign"" aria-hidden=""true""></span></span> </div> <div class=""collapse navbar-collapse""> <p class=""navbar-text""> Use this space to summarize your privacy and cookie use policy. </p> <div class=""navbar-right""> "); EndContext(); BeginContext(1234, 92, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c18f8c7ec540a446e15b225511cfa1a006e3ec36190", async() => { BeginContext(1312, 10, true); WriteLiteral("Learn More"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1326, 99, true); WriteLiteral("\r\n <button type=\"button\" class=\"btn btn-default navbar-btn\" data-cookie-string=\""); EndContext(); BeginContext(1426, 12, false); #line 28 "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\Shared\_CookieConsentPartial.cshtml" Write(cookieString); #line default #line hidden EndContext(); BeginContext(1438, 456, true); WriteLiteral(@""">Accept</button> </div> </div> </div> </nav> <script> (function () { document.querySelector(""#cookieConsent button[data-cookie-string]"").addEventListener(""click"", function (el) { document.cookie = el.target.dataset.cookieString; document.querySelector(""#cookieConsent"").classList.add(""hidden""); }, false); })(); </script> "); EndContext(); #line 41 "C:\Users\Jonathan Villeda\Documents\Propuesta BDG\MultasBot\Views\Shared\_CookieConsentPartial.cshtml" } #line default #line hidden } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
58.311377
361
0.702916
[ "Apache-2.0" ]
johnsvill/MultasBot
obj/Debug/netcoreapp2.1/Razor/Views/Shared/_CookieConsentPartial.cshtml.g.cs
9,738
C#
using java.lang; using java.util; using stab.query; public class ToTFloatMap2 { public static bool test() { var map = Query.asIterable(new[] { 1f, 2f, 3f, 4f, 5f }).toMap(p => "K" + p); return map.getValue("K3.0") == 3f; } }
21.090909
79
0.633621
[ "Apache-2.0" ]
monoman/cnatural-language
tests/resources/LibraryTest/sources/ToTFloatMap2.stab.cs
232
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CrewChiefV3.RaceRoom.RaceRoomData; using System.Threading; using CrewChiefV3.Events; namespace CrewChiefV3.PCars { class PCarsSpotterv2 : Spotter { private NoisyCartesianCoordinateSpotter internalSpotter; private Boolean paused = false; private Boolean checkCarSpeedsForNetworkSpotter = true; // don't activate the spotter unless this many seconds have elapsed (race starts are messy) private int timeAfterRaceStartToActivate = UserSettings.GetUserSettings().getInt("time_after_race_start_for_spotter"); // how long is a car? we use 3.5 meters by default here. Too long and we'll get 'hold your line' messages // when we're clearly directly behind the car private float carLength = UserSettings.GetUserSettings().getFloat("pcars_spotter_car_length"); private Boolean enabled; private Boolean initialEnabledState; private AudioPlayer audioPlayer; private DateTime timeToStartSpotting = DateTime.Now; private Dictionary<String, List<float>> previousOpponentSpeeds = new Dictionary<String, List<float>>(); private float maxClosingSpeed = 30; private float trackWidth = 10f; private float carWidth = 1.8f; private float udpMaxClosingSpeed = 60; private float udpTrackWidth = 7f; private float udpCarWidth = 1.5f; public PCarsSpotterv2(AudioPlayer audioPlayer, Boolean initialEnabledState) { this.audioPlayer = audioPlayer; this.enabled = initialEnabledState; this.initialEnabledState = initialEnabledState; if (CrewChief.gameDefinition.gameEnum == GameEnum.PCARS_NETWORK) { this.internalSpotter = new NoisyCartesianCoordinateSpotter(audioPlayer, initialEnabledState, carLength, udpCarWidth, udpTrackWidth, udpMaxClosingSpeed); } else { this.internalSpotter = new NoisyCartesianCoordinateSpotter(audioPlayer, initialEnabledState, carLength, carWidth, trackWidth, maxClosingSpeed); } } public void clearState() { timeToStartSpotting = DateTime.Now; audioPlayer.closeChannel(); } public void pause() { paused = true; } public void unpause() { paused = false; } public void trigger(Object lastStateObj, Object currentStateObj) { if (paused) { audioPlayer.closeChannel(); return; } CrewChiefV3.PCars.PCarsSharedMemoryReader.PCarsStructWrapper currentWrapper = (CrewChiefV3.PCars.PCarsSharedMemoryReader.PCarsStructWrapper)currentStateObj; pCarsAPIStruct currentState = currentWrapper.data; // game state is 3 for paused, 5 for replay. No idea what 4 is... if (currentState.mGameState == (uint)eGameState.GAME_FRONT_END || (currentState.mGameState == (uint)eGameState.GAME_INGAME_PAUSED && !System.Diagnostics.Debugger.IsAttached) || currentState.mGameState == (uint)eGameState.GAME_VIEWING_REPLAY || currentState.mGameState == (uint)eGameState.GAME_EXITED) { // don't ignore the paused game updates if we're in debug mode audioPlayer.closeChannel(); return; } CrewChiefV3.PCars.PCarsSharedMemoryReader.PCarsStructWrapper previousWrapper = (CrewChiefV3.PCars.PCarsSharedMemoryReader.PCarsStructWrapper)lastStateObj; pCarsAPIStruct lastState = previousWrapper.data; DateTime now = new DateTime(currentWrapper.ticksWhenRead); float interval = (float)(((double)currentWrapper.ticksWhenRead - (double)previousWrapper.ticksWhenRead) / (double)TimeSpan.TicksPerSecond); if (currentState.mRaceState == (int)eRaceState.RACESTATE_RACING && lastState.mRaceState != (int)eRaceState.RACESTATE_RACING) { timeToStartSpotting = now.Add(TimeSpan.FromSeconds(timeAfterRaceStartToActivate)); } // this check looks a bit funky... whe we start a practice session, the raceState is not_started // until we cross the line for the first time. Which is retarded really. if (currentState.mRaceState == (int)eRaceState.RACESTATE_INVALID || now < timeToStartSpotting || (currentState.mSessionState == (int)eSessionState.SESSION_RACE && currentState.mRaceState == (int) eRaceState.RACESTATE_NOT_STARTED)) { return; } if (enabled && currentState.mParticipantData.Count() > 1) { Tuple<int, pCarsAPIParticipantStruct> playerDataWithIndex = PCarsGameStateMapper.getPlayerDataStruct(currentState.mParticipantData, currentState.mViewedParticipantIndex); int playerIndex = playerDataWithIndex.Item1; pCarsAPIParticipantStruct playerData = playerDataWithIndex.Item2; float[] currentPlayerPosition = new float[] { playerData.mWorldPosition[0], playerData.mWorldPosition[2] }; if (currentState.mPitMode == (uint)ePitMode.PIT_MODE_NONE) { List<float[]> currentOpponentPositions = new List<float[]>(); List<float> opponentSpeeds = new List<float>(); float playerSpeed = currentState.mSpeed; for (int i = 0; i < currentState.mParticipantData.Count(); i++) { if (i == playerIndex) { continue; } pCarsAPIParticipantStruct opponentData = currentState.mParticipantData[i]; if (opponentData.mIsActive) { float[] currentPositions = new float[] { opponentData.mWorldPosition[0], opponentData.mWorldPosition[2] }; currentOpponentPositions.Add(currentPositions); try { pCarsAPIParticipantStruct previousOpponentData = PCarsGameStateMapper.getParticipantDataForName(lastState.mParticipantData, opponentData.mName, i); float[] previousPositions = new float[] { previousOpponentData.mWorldPosition[0], previousOpponentData.mWorldPosition[2] }; float opponentSpeed; // TODO: check that the network data are up to the task of calculating opponent speeds if (CrewChief.gameDefinition.gameEnum == GameEnum.PCARS_NETWORK && !checkCarSpeedsForNetworkSpotter) { opponentSpeed = playerSpeed; } else { opponentSpeed = getSpeed(currentPositions, previousPositions, interval); } if (previousOpponentSpeeds.ContainsKey(opponentData.mName)) { List<float> speeds = previousOpponentSpeeds[opponentData.mName]; speeds.Add(opponentSpeed); if (speeds.Count == 5) { speeds.RemoveAt(0); opponentSpeed = speeds.Average(); } } else { List<float> speeds = new List<float>(); speeds.Add(opponentSpeed); previousOpponentSpeeds.Add(opponentData.mName, speeds); } opponentSpeeds.Add(opponentSpeed); } catch (Exception) { opponentSpeeds.Add(playerSpeed); } } } float playerRotation = currentState.mOrientation[1]; if (playerRotation < 0) { playerRotation = (float)(2 * Math.PI) + playerRotation; } playerRotation = (float)(2 * Math.PI) - playerRotation; internalSpotter.triggerInternal(playerRotation, currentPlayerPosition, playerSpeed, opponentSpeeds, currentOpponentPositions); } } } public void enableSpotter() { enabled = true; audioPlayer.playClipImmediately(new QueuedMessage(AudioPlayer.folderEnableSpotter, 0, null), false); audioPlayer.closeChannel(); } public void disableSpotter() { enabled = false; audioPlayer.playClipImmediately(new QueuedMessage(AudioPlayer.folderDisableSpotter, 0, null), false); audioPlayer.closeChannel(); } private float getSpeed(float[] current, float[] previous, float timeInterval) { return (float)(Math.Sqrt(Math.Pow(current[0] - previous[0], 2) + Math.Pow(current[1] - previous[1], 2))) / timeInterval; } } }
46.690476
186
0.562366
[ "MIT" ]
mrbelowski/r3e_crewchief_v3
CrewChiefV3/PCars/PCarsSpotterv2.cs
9,807
C#
using Abp.Application.Services; using Abp.Domain.Repositories; namespace Abp.TestBase.SampleApplication.Crm { public class CompanyAppService : CrudAppService<Company, CompanyDto, int> { public CompanyAppService(IRepository<Company, int> repository) : base(repository) { GetPermissionName = "GetCompanyPermission"; GetAllPermissionName = "GetAllCompaniesPermission"; CreatePermissionName = "CreateCompanyPermission"; UpdatePermissionName = "UpdateCompanyPermission"; DeletePermissionName = "DeleteCompanyPermission"; } } }
34.444444
89
0.7
[ "MIT" ]
12321/aspnetboilerplate
test/Abp.TestBase.SampleApplication/Crm/CompanyAppService.cs
622
C#
// <copyright file="SendMessageResponse.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // </copyright> namespace Amdocs.Teams.App.Communicator.Common.Services.Teams { /// <summary> /// Send message response object. /// </summary> public class SendMessageResponse { /// <summary> /// Gets or sets the status code. /// </summary> public int StatusCode { get; set; } /// <summary> /// Gets or sets the result type. /// </summary> public SendMessageResult ResultType { get; set; } /// <summary> /// Gets or sets a comma separated list representing all of the status code responses received when trying /// to send the notification to the recipient. These results can include success, failure, and throttle /// status codes. /// </summary> public string AllSendStatusCodes { get; set; } /// <summary> /// Gets or sets the number of throttle responses. /// </summary> public int TotalNumberOfSendThrottles { get; set; } /// <summary> /// Gets or sets the error message when trying to send the notification. /// </summary> public string ErrorMessage { get; set; } } }
32.195122
114
0.604545
[ "MIT" ]
v-haalam/local-ARM
Source/AmdocsCommunicator.Common/Services/Teams/Messages/SendMessageResponse.cs
1,322
C#
using System; using Newtonsoft.Json; using System.Xml.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AlipayTradeCloseModel Data Structure. /// </summary> [Serializable] public class AlipayTradeCloseModel : AlipayObject { /// <summary> /// 卖家端自定义的的操作员 ID /// </summary> [JsonProperty("operator_id")] [XmlElement("operator_id")] public string OperatorId { get; set; } /// <summary> /// 订单支付时传入的商户订单号,和支付宝交易号不能同时为空。 trade_no,out_trade_no如果同时存在优先取trade_no /// </summary> [JsonProperty("out_trade_no")] [XmlElement("out_trade_no")] public string OutTradeNo { get; set; } /// <summary> /// 该交易在支付宝系统中的交易流水号。最短 16 位,最长 64 位。和out_trade_no不能同时为空,如果同时传了 out_trade_no和 trade_no,则以 trade_no为准。 /// </summary> [JsonProperty("trade_no")] [XmlElement("trade_no")] public string TradeNo { get; set; } } }
28.714286
109
0.61592
[ "MIT" ]
Aosir/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayTradeCloseModel.cs
1,191
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Associate/Disassociate an access device instance to the user's Shared Call Appearance. /// /// The following elements are only used in AS data mode and ignored in XS data mode: /// useHotline /// hotlineContact /// /// The response is either a SuccessResponse or an ErrorResponse. /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""524e0d071a229a44af2f953d6b50db35:184""}]")] public class UserSharedCallAppearanceModifyEndpointRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.C.SuccessResponse> { private string _userId; [XmlElement(ElementName = "userId", IsNullable = false, Namespace = "")] [Group(@"524e0d071a229a44af2f953d6b50db35:184")] [MinLength(1)] [MaxLength(161)] public string UserId { get => _userId; set { UserIdSpecified = true; _userId = value; } } [XmlIgnore] protected bool UserIdSpecified { get; set; } private BroadWorksConnector.Ocip.Models.AccessDeviceEndpointKey _accessDeviceEndpoint; [XmlElement(ElementName = "accessDeviceEndpoint", IsNullable = false, Namespace = "")] [Group(@"524e0d071a229a44af2f953d6b50db35:184")] public BroadWorksConnector.Ocip.Models.AccessDeviceEndpointKey AccessDeviceEndpoint { get => _accessDeviceEndpoint; set { AccessDeviceEndpointSpecified = true; _accessDeviceEndpoint = value; } } [XmlIgnore] protected bool AccessDeviceEndpointSpecified { get; set; } private bool _isActive; [XmlElement(ElementName = "isActive", IsNullable = false, Namespace = "")] [Optional] [Group(@"524e0d071a229a44af2f953d6b50db35:184")] public bool IsActive { get => _isActive; set { IsActiveSpecified = true; _isActive = value; } } [XmlIgnore] protected bool IsActiveSpecified { get; set; } private bool _allowOrigination; [XmlElement(ElementName = "allowOrigination", IsNullable = false, Namespace = "")] [Optional] [Group(@"524e0d071a229a44af2f953d6b50db35:184")] public bool AllowOrigination { get => _allowOrigination; set { AllowOriginationSpecified = true; _allowOrigination = value; } } [XmlIgnore] protected bool AllowOriginationSpecified { get; set; } private bool _allowTermination; [XmlElement(ElementName = "allowTermination", IsNullable = false, Namespace = "")] [Optional] [Group(@"524e0d071a229a44af2f953d6b50db35:184")] public bool AllowTermination { get => _allowTermination; set { AllowTerminationSpecified = true; _allowTermination = value; } } [XmlIgnore] protected bool AllowTerminationSpecified { get; set; } private bool _useHotline; [XmlElement(ElementName = "useHotline", IsNullable = false, Namespace = "")] [Optional] [Group(@"524e0d071a229a44af2f953d6b50db35:184")] public bool UseHotline { get => _useHotline; set { UseHotlineSpecified = true; _useHotline = value; } } [XmlIgnore] protected bool UseHotlineSpecified { get; set; } private string _hotlineContact; [XmlElement(ElementName = "hotlineContact", IsNullable = true, Namespace = "")] [Optional] [Group(@"524e0d071a229a44af2f953d6b50db35:184")] [MinLength(1)] [MaxLength(161)] public string HotlineContact { get => _hotlineContact; set { HotlineContactSpecified = true; _hotlineContact = value; } } [XmlIgnore] protected bool HotlineContactSpecified { get; set; } } }
29.828025
160
0.580611
[ "MIT" ]
cwmiller/broadworks-connector-net
BroadworksConnector/Ocip/Models/UserSharedCallAppearanceModifyEndpointRequest.cs
4,683
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Computers.Data.Data { using System; using System.Collections.Generic; public partial class ComputerVendors { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public ComputerVendors() { this.Computers = new HashSet<Computers>(); } public int Id { get; set; } public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Computers> Computers { get; set; } } }
36.333333
128
0.578899
[ "MIT" ]
pavelhristov/CSharpDatabases
Exam-8Nov2016/05. Database-first/Computers/Computers.Data/Data/ComputerVendors.cs
1,090
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class Combo { public Hit[] hits; } [Serializable] public class Hit { public string animation; public string inputButton; public float animationTime; public float resetTime; public float damage; public AudioClip hitSound; public bool slowDown; }
18.666667
33
0.742347
[ "MIT" ]
FelipeBachetti/FelipeBachetti.github.io
2021/CSharp/Nights Edge Ragnarok/Combo.cs
392
C#
// Copyright Epic Games, Inc. All Rights Reserved. // This file is automatically generated. Changes to this file may be overwritten. namespace Epic.OnlineServices.Sessions { /// <summary> /// Function prototype definition for callbacks passed to <see cref="SessionsInterface.UpdateSession" /> /// </summary> /// <param name="data">A <see cref="UpdateSessionCallbackInfo" /> containing the output information and result</param> public delegate void OnUpdateSessionCallback(UpdateSessionCallbackInfo data); internal delegate void OnUpdateSessionCallbackInternal(System.IntPtr data); }
45.384615
119
0.784746
[ "MIT" ]
Liam-Harrison/EpicOnlineTransport
EOSSDK/Generated/Sessions/OnUpdateSessionCallback.cs
590
C#
using Headstart.API.Commands; using Headstart.Common.Models; using Headstart.Models.Attributes; using Headstart.Models.Headstart; using Microsoft.AspNetCore.Mvc; using ordercloud.integrations.library; using OrderCloud.Catalyst; using OrderCloud.SDK; using System.Collections.Generic; using System.Threading.Tasks; namespace Headstart.Common.Controllers { [DocComments("\"Headstart Orders\" for handling payment commands in Headstart")] [HSSection.Headstart(ListOrder = 2)] [Route("payments")] public class PaymentController : BaseController { private readonly IPaymentCommand _command; private readonly AppSettings _settings; public PaymentController(IPaymentCommand command, AppSettings settings) { _command = command; _settings = settings; } [DocName("Save payments")] [DocComments("Creates or updates payments as needed for this order")] [HttpPut, Route("{orderID}/update"), OrderCloudUserAuth(ApiRole.Shopper)] public async Task<IList<HSPayment>> SavePayments(string orderID, [FromBody] PaymentUpdateRequest request) { return await _command.SavePayments(orderID, request.Payments, UserContext.AccessToken); } } }
34.27027
113
0.718454
[ "MIT" ]
Labedlam/headstart
src/Middleware/src/Headstart.API/Controllers/PaymentController.cs
1,268
C#
// File: IEmbeddedResource.cs // Project Name: NCmdLiner // Project Home: https://github.com/trondr/NCmdLiner/blob/master/README.md // License: New BSD License (BSD) https://github.com/trondr/NCmdLiner/blob/master/License.md // Credits: See the Credit folder in this project // Copyright © <github.com/trondr> 2013 // All rights reserved. using System.IO; using System.Reflection; namespace NMultiTool.Library.Module.Common.Resources { /// <summary> Interface for embedded resource. </summary> public interface IEmbeddedResource { /// <summary> /// Extract embedded resource to stream /// </summary> /// <param name="name">Name of embedded resource to extracted from assembly. Example: "My.Name.Space.MyPicture.bmp"</param> /// <param name="assembly">Assembly where resource is embedded</param> Stream ExtractToStream(string name, Assembly assembly); /// <summary> Extracts embedded resource to file. </summary> /// /// <param name="name"> Name of embedded resource to extracted from assembly. Example: /// "My.Name.Space.MyPicture.bmp". </param> /// <param name="assembly"> Assembly where resource is embedded. </param> /// <param name="fileName"> Filename of the file. </param> void ExtractToFile(string name, Assembly assembly, string fileName); } }
44.4375
131
0.656821
[ "BSD-3-Clause" ]
trondr/NMultiTool
src/NMultiTool.Library/Module/Common/Resources/IEmbeddedResource.cs
1,425
C#
using System; using System.Collections.Generic; using System.Linq; namespace SqlKata { public partial class Query { public Query AsUpdate(IEnumerable<string> columns, IEnumerable<object> values) { if ((columns?.Count() ?? 0) == 0 || (values?.Count() ?? 0) == 0) { throw new InvalidOperationException("Columns and Values cannot be null or empty"); } if (columns.Count() != values.Count()) { throw new InvalidOperationException("Columns count should be equal to Values count"); } Method = "update"; ClearComponent("update").AddComponent("update", new InsertClause { Columns = columns.ToList(), Values = values.Select(BackupNullValues).ToList() }); return this; } public Query AsUpdate(IReadOnlyDictionary<string, object> data) { if (data == null || data.Count == 0) { throw new InvalidOperationException("Values dictionary cannot be null or empty"); } Method = "update"; ClearComponent("update").AddComponent("update", new InsertClause { Columns = data.Keys.ToList(), Values = data.Values.Select(BackupNullValues).ToList(), }); return this; } } }
26.509091
101
0.528121
[ "MIT" ]
Happi-cat/querybuilder
QueryBuilder/Query.Update.cs
1,458
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Buffers; using System.IO.Pipelines; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { public sealed partial class HttpResponseHeaders : HttpHeaders { private static readonly byte[] _CrLf = new[] { (byte)'\r', (byte)'\n' }; private static readonly byte[] _colonSpace = new[] { (byte)':', (byte)' ' }; public Enumerator GetEnumerator() { return new Enumerator(this); } protected override IEnumerator<KeyValuePair<string, StringValues>> GetEnumeratorFast() { return GetEnumerator(); } internal void CopyTo(ref BufferWriter<PipeWriter> buffer) { CopyToFast(ref buffer); if (MaybeUnknown != null) { foreach (var kv in MaybeUnknown) { foreach (var value in kv.Value) { if (value != null) { buffer.Write(_CrLf); buffer.WriteAsciiNoValidation(kv.Key); buffer.Write(_colonSpace); buffer.WriteAsciiNoValidation(value); } } } } } private static long ParseContentLength(string value) { if (!HeaderUtilities.TryParseNonNegativeInt64(value, out var parsed)) { ThrowInvalidContentLengthException(value); } return parsed; } [MethodImpl(MethodImplOptions.NoInlining)] private void SetValueUnknown(string key, in StringValues value) { ValidateHeaderNameCharacters(key); Unknown[key] = value; } private static void ThrowInvalidContentLengthException(string value) { throw new InvalidOperationException(CoreStrings.FormatInvalidContentLength_InvalidNumber(value)); } public partial struct Enumerator : IEnumerator<KeyValuePair<string, StringValues>> { private readonly HttpResponseHeaders _collection; private readonly long _bits; private int _state; private KeyValuePair<string, StringValues> _current; private readonly bool _hasUnknown; private Dictionary<string, StringValues>.Enumerator _unknownEnumerator; internal Enumerator(HttpResponseHeaders collection) { _collection = collection; _bits = collection._bits; _state = 0; _current = default; _hasUnknown = collection.MaybeUnknown != null; _unknownEnumerator = _hasUnknown ? collection.MaybeUnknown.GetEnumerator() : default; } public KeyValuePair<string, StringValues> Current => _current; object IEnumerator.Current => _current; public void Dispose() { } public void Reset() { _state = 0; } } } }
32.345455
111
0.562114
[ "Apache-2.0" ]
HeMinzhang/AspNetCore
src/Servers/Kestrel/Core/src/Internal/Http/HttpResponseHeaders.cs
3,558
C#
/* _BEGIN_TEMPLATE_ { "id": "CFM_671", "name": [ "凛风巫师", "Cryomancer" ], "text": [ "<b>战吼:</b>如果有敌人被<b>冻结</b>,便获得+2/+2。", "<b>Battlecry:</b> If an enemy is <b>Frozen</b>, gain +2/+2." ], "cardClass": "MAGE", "type": "MINION", "cost": 5, "rarity": "COMMON", "set": "GANGS", "collectible": true, "dbfId": 40988 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_CFM_671 : SimTemplate //* Cryomancer { // Battlecry: Gain +2/+2 if an enemy is Frozen. public override void getBattlecryEffect(Playfield p, Minion m, Minion target, int choice) { var temp = m.own ? p.enemyMinions : p.ownMinions; foreach (var mnn in temp) { if (mnn.frozen) { p.minionGetBuffed(m, 2, 2); break; } } } } }
21.116279
97
0.486784
[ "MIT" ]
chi-rei-den/Silverfish
cards/GANGS/CFM/Sim_CFM_671.cs
948
C#
using System; namespace Omnius.Core.RocketPack { // https://github.com/google/protobuf/blob/master/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs public readonly struct Timestamp : IEquatable<Timestamp>, IComparable<Timestamp> { public Timestamp(long seconds, int nanos) { this.Seconds = seconds; this.Nanos = nanos; } public static Timestamp Zero { get; } = new Timestamp(0, 0); public long Seconds { get; } public int Nanos { get; } public static bool operator ==(Timestamp x, Timestamp y) { return x.Equals(y); } public static bool operator !=(Timestamp x, Timestamp y) { return !x.Equals(y); } public static bool operator <(Timestamp x, Timestamp y) { return x.CompareTo(y) < 0; } public static bool operator >(Timestamp x, Timestamp y) { return x.CompareTo(y) > 0; } public static bool operator <=(Timestamp x, Timestamp y) { return x.CompareTo(y) <= 0; } public static bool operator >=(Timestamp x, Timestamp y) { return x.CompareTo(y) >= 0; } public override int GetHashCode() { return (int)(this.Seconds ^ this.Nanos); } public override bool Equals(object? obj) { if (obj is not Timestamp) return false; return this.Equals((Timestamp)obj); } public bool Equals(Timestamp other) { return (this.Seconds == other.Seconds && this.Nanos == other.Nanos); } public int CompareTo(Timestamp other) { int result; result = this.Seconds.CompareTo(other.Seconds); if (result != 0) return result; result = this.Nanos.CompareTo(other.Nanos); if (result != 0) return result; return 0; } public DateTime ToDateTime() { return DateTime.UnixEpoch.AddSeconds(this.Seconds).AddTicks(this.Nanos / 100); } public static Timestamp FromDateTime(DateTime dateTime) { if (dateTime.Kind != DateTimeKind.Utc) throw new ArgumentException("Conversion from DateTime to Timestamp requires the DateTime kind to be Utc", "dateTime"); long ticks = dateTime.Ticks - DateTime.UnixEpoch.Ticks; long seconds = ticks / TimeSpan.TicksPerSecond; int nanos = (int)(ticks % TimeSpan.TicksPerSecond) * 100; return new Timestamp(seconds, nanos); } } }
27.731959
169
0.562454
[ "MIT" ]
KeitoTobi1/core
src/Omnius.Core.RocketPack/Timestamp.cs
2,690
C#
using System.Collections.Generic; namespace Adyen.Service.Resource.Payout { public class SubmitThirdParty : ServiceResource { public SubmitThirdParty(AbstractService abstractService) : base(abstractService, abstractService.Client.Config.Endpoint + "/pal/servlet/Payout/" + abstractService.Client.ApiVersion + "/submitThirdParty",null) { } } }
30.153846
163
0.711735
[ "MIT" ]
Ganesh-Chavan/adyen-dotnet-api-library
Adyen/Service/Resource/Payout/SubmitThirdParty.cs
392
C#
using BLD.Helpers; using UnityEngine; namespace BLD.Rendering { public static class CullingControllerUtils { /// <summary> /// Computes the rule used for toggling skinned meshes updateWhenOffscreen param. /// Skinned meshes should be always updated if near the camera to avoid false culling positives on screen edges. /// </summary> /// <param name="settings">Any settings object to use thresholds for computing the rule.</param> /// <param name="distanceToCamera">Mesh distance from camera used for computing the rule.</param> /// <returns>True if mesh should be updated when offscreen, false if otherwise.</returns> internal static bool TestSkinnedRendererOffscreenRule(CullingControllerSettings settings, float distanceToCamera) { bool finalValue = true; if (settings.enableAnimationCulling) { if (distanceToCamera > settings.enableAnimationCullingDistance) finalValue = false; } return finalValue; } /// <summary> /// Computes the rule used for toggling renderers visibility. /// </summary> /// <param name="profile">Profile used for size and distance thresholds needed for the rule.</param> /// <param name="viewportSize">Diagonal viewport size of the renderer.</param> /// <param name="distanceToCamera">Distance to camera of the renderer.</param> /// <param name="boundsContainsCamera">Renderer bounds contains camera?</param> /// <param name="isOpaque">Renderer is opaque?</param> /// <param name="isEmissive">Renderer is emissive?</param> /// <returns>True if renderer should be visible, false if otherwise.</returns> internal static bool TestRendererVisibleRule(CullingControllerProfile profile, float viewportSize, float distanceToCamera, bool boundsContainsCamera, bool isOpaque, bool isEmissive) { bool shouldBeVisible = distanceToCamera < profile.visibleDistanceThreshold || boundsContainsCamera; if (isEmissive) shouldBeVisible |= viewportSize > profile.emissiveSizeThreshold; if (isOpaque) shouldBeVisible |= viewportSize > profile.opaqueSizeThreshold; return shouldBeVisible; } /// <summary> /// Computes the rule used for toggling renderer shadow casting. /// </summary> /// <param name="profile">Profile used for size and distance thresholds needed for the rule.</param> /// <param name="viewportSize">Diagonal viewport size of the renderer.</param> /// <param name="distanceToCamera">Distance from renderer to camera.</param> /// <param name="shadowMapTexelSize">Shadow map bounding box size in texels.</param> /// <returns>True if renderer should have shadow, false otherwise.</returns> internal static bool TestRendererShadowRule(CullingControllerProfile profile, float viewportSize, float distanceToCamera, float shadowMapTexelSize) { bool shouldHaveShadow = distanceToCamera < profile.shadowDistanceThreshold; shouldHaveShadow |= viewportSize > profile.shadowRendererSizeThreshold; shouldHaveShadow &= shadowMapTexelSize > profile.shadowMapProjectionSizeThreshold; return shouldHaveShadow; } internal static bool TestAvatarShadowRule(CullingControllerProfile profile, float avatarDistance) { return avatarDistance < profile.maxShadowDistanceForAvatars; } /// <summary> /// Determines if the given renderer is going to be enqueued at the opaque section of the rendering pipeline. /// </summary> /// <param name="renderer">Renderer to be checked.</param> /// <returns>True if its opaque</returns> internal static bool IsOpaque(Renderer renderer) { Material firstMat = renderer.sharedMaterials[0]; if (firstMat == null) return true; if (firstMat.HasProperty(ShaderUtils.ZWrite) && (int) firstMat.GetFloat(ShaderUtils.ZWrite) == 0) { return false; } return true; } /// <summary> /// Determines if the given renderer has emissive material traits. /// </summary> /// <param name="renderer">Renderer to be checked.</param> /// <returns>True if the renderer is emissive.</returns> internal static bool IsEmissive(Renderer renderer) { Material firstMat = renderer.sharedMaterials[0]; if (firstMat == null) return false; if (firstMat.HasProperty(ShaderUtils.EmissionMap) && firstMat.GetTexture(ShaderUtils.EmissionMap) != null) return true; if (firstMat.HasProperty(ShaderUtils.EmissionColor) && firstMat.GetColor(ShaderUtils.EmissionColor) != Color.clear) return true; return false; } /// <summary> /// ComputeShadowMapTexelSize computes the shadow-map bounding box diagonal texel size /// for the given bounds size. /// </summary> /// <param name="boundsSize">Diagonal bounds size of the object</param> /// <param name="shadowDistance">Shadow distance as set in the quality settings</param> /// <param name="shadowMapRes">Shadow map resolution as set in the quality settings (128, 256, etc)</param> /// <returns>The computed shadow map diagonal texel size for the object.</returns> /// <remarks> /// This is calculated by doing the following: /// /// - We get the boundsSize to a normalized viewport size. /// - We multiply the resulting value by the shadow map resolution. /// /// To get the viewport size, we assume the shadow distance value is directly correlated by /// the orthogonal projection size used for rendering the shadow map. /// /// We can use the bounds size and shadow distance to obtain the normalized shadow viewport /// value because both are expressed in world units. /// /// After getting the normalized size, we scale it by the shadow map resolution to get the /// diagonal texel size of the bounds shadow. /// /// This leaves us with: /// <c>shadowTexelSize = boundsSize / shadow dist * shadow res</c> /// /// This is a lazy approximation and most likely will need some refinement in the future. /// </remarks> internal static float ComputeShadowMapTexelSize(float boundsSize, float shadowDistance, float shadowMapRes) { return boundsSize / shadowDistance * shadowMapRes; } public static void DrawBounds(Bounds b, Color color, float delay = 0) { // bottom var p1 = new Vector3(b.min.x, b.min.y, b.min.z); var p2 = new Vector3(b.max.x, b.min.y, b.min.z); var p3 = new Vector3(b.max.x, b.min.y, b.max.z); var p4 = new Vector3(b.min.x, b.min.y, b.max.z); Debug.DrawLine(p1, p2, color, delay); Debug.DrawLine(p2, p3, color, delay); Debug.DrawLine(p3, p4, color, delay); Debug.DrawLine(p4, p1, color, delay); // top var p5 = new Vector3(b.min.x, b.max.y, b.min.z); var p6 = new Vector3(b.max.x, b.max.y, b.min.z); var p7 = new Vector3(b.max.x, b.max.y, b.max.z); var p8 = new Vector3(b.min.x, b.max.y, b.max.z); Debug.DrawLine(p5, p6, color, delay); Debug.DrawLine(p6, p7, color, delay); Debug.DrawLine(p7, p8, color, delay); Debug.DrawLine(p8, p5, color, delay); // sides Debug.DrawLine(p1, p5, color, delay); Debug.DrawLine(p2, p6, color, delay); Debug.DrawLine(p3, p7, color, delay); Debug.DrawLine(p4, p8, color, delay); } } }
47.116279
189
0.623519
[ "Apache-2.0" ]
belandproject/unity-renderer
unity-renderer/Assets/Rendering/Culling/CullingControllerUtils.cs
8,106
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder.Embedded v9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq.Expressions; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Core; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.PublishedModels { /// <summary>Member</summary> [PublishedModel("Member")] public partial class Member : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] public new const string ModelTypeAlias = "Member"; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] public new const PublishedItemType ModelItemType = PublishedItemType.Member; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor) => PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<Member, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector); #pragma warning restore 0109 private IPublishedValueFallback _publishedValueFallback; // ctor public Member(IPublishedContent content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback) { _publishedValueFallback = publishedValueFallback; } // properties ///<summary> /// Is Approved ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] [ImplementPropertyType("umbracoMemberApproved")] public virtual bool UmbracoMemberApproved => this.Value<bool>(_publishedValueFallback, "umbracoMemberApproved"); ///<summary> /// Comments ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] [ImplementPropertyType("umbracoMemberComments")] public virtual string UmbracoMemberComments => this.Value<string>(_publishedValueFallback, "umbracoMemberComments"); ///<summary> /// Failed Password Attempts ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] [ImplementPropertyType("umbracoMemberFailedPasswordAttempts")] public virtual int UmbracoMemberFailedPasswordAttempts => this.Value<int>(_publishedValueFallback, "umbracoMemberFailedPasswordAttempts"); ///<summary> /// Last Lockout Date ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] [ImplementPropertyType("umbracoMemberLastLockoutDate")] public virtual global::System.DateTime UmbracoMemberLastLockoutDate => this.Value<global::System.DateTime>(_publishedValueFallback, "umbracoMemberLastLockoutDate"); ///<summary> /// Last Login Date ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] [ImplementPropertyType("umbracoMemberLastLogin")] public virtual global::System.DateTime UmbracoMemberLastLogin => this.Value<global::System.DateTime>(_publishedValueFallback, "umbracoMemberLastLogin"); ///<summary> /// Last Password Change Date ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] [ImplementPropertyType("umbracoMemberLastPasswordChangeDate")] public virtual global::System.DateTime UmbracoMemberLastPasswordChangeDate => this.Value<global::System.DateTime>(_publishedValueFallback, "umbracoMemberLastPasswordChangeDate"); ///<summary> /// Is Locked Out ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "9.0.0-beta004+c41d05f6a67e1d217d565d055a85231792520f88")] [ImplementPropertyType("umbracoMemberLockedOut")] public virtual bool UmbracoMemberLockedOut => this.Value<bool>(_publishedValueFallback, "umbracoMemberLockedOut"); } }
52.5
180
0.781905
[ "MIT" ]
ManiPeralta/Umbraco9-Mano-a-mano-Template
umbraco/models/Member.generated.cs
5,250
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorioIP { [DebuggerDisplay("{value,nq}")] [Serializable] public struct VarInt { UInt32 value; public override string ToString() => value.ToString(); public VarInt(UInt32 u) { value = u; } static public implicit operator UInt32(VarInt v) => v.value; static public implicit operator VarInt(UInt32 u) => new VarInt(u); static public implicit operator byte(VarInt v) => (byte)v.value; static public implicit operator VarInt(byte b) => new VarInt((UInt32)b); static public implicit operator Int32(VarInt v) => (Int32)v.value; static public implicit operator VarInt(Int32 i) => new VarInt((UInt32)i); public IEnumerable<byte> Encode() { byte prefix = 0; byte firstmask = 0; byte startshift = 0; if (value < 0x80) { //--[[1 byte]] yield return (byte)value; yield break; } else if (value < 0x0800) { //--[[2 bytes]] prefix = 0xc0; firstmask = 0x1f; startshift = 6; } else if (value < 0x10000) { //--[[3 bytes]] prefix = 0xe0; firstmask = 0x0f; startshift = 12; } else if (value < 0x200000) { //--[[4 bytes]] prefix = 0xf0; firstmask = 0x07; startshift = 18; } else if (value < 0x4000000) { //--[[5 bytes]] prefix = 0xf8; firstmask = 0x03; startshift = 24; } else { //--[[6 bytes]] prefix = 0xfc; firstmask = 0x03; startshift = 30; } yield return (byte)((prefix | ((value >> startshift) & firstmask))); for (int shift = startshift - 6; shift >= 0; shift -= 6) { yield return (byte)((0x80u | ((value >> shift) & 0x3fu))); } } public static (VarInt, ArraySegment<byte>) Take(ArraySegment<byte> data) { if (data.Count == 0) { return (0, data); } var first = data.Array[data.Offset]; if (first == 0) { return (0, new ArraySegment<byte>(data.Array, data.Offset + 1, data.Count - 1)); } var seq = first < 0x80 ? 1 : first < 0xE0 ? 2 : first < 0xF0 ? 3 : first < 0xF8 ? 4 : first < 0xFC ? 5 : 6; if (seq == 1) { return (first, new ArraySegment<byte>(data.Array, data.Offset + 1, data.Count - 1)); } else { UInt32 val = (first & ((1u << (8 - seq)) - 1u)); for (int i = 1; i < seq; i++) { val = (val << 6) | (data.Array[data.Offset+i] & 0x3Fu); } return (val, new ArraySegment<byte>(data.Array, data.Offset + seq, data.Count - seq)); } } public static IEnumerable<VarInt> TakeAll(ArraySegment<byte> data) { while (data.Count > 0) { VarInt val = 0; (val, data) = VarInt.Take(data); if (val == 0) { yield break; } yield return val; } } public static bool operator ==(VarInt left, VarInt right) => left.value == right.value; public static bool operator !=(VarInt left, VarInt right) => left.value != right.value; public static bool operator ==(VarInt left, UInt32 right) => left.value == right; public static bool operator !=(VarInt left, UInt32 right) => left.value != right; public static bool operator ==(VarInt left, Int32 right) => left.value == (UInt32)right; public static bool operator !=(VarInt left, Int32 right) => left.value != (UInt32)right; public override bool Equals(object obj) { return obj is VarInt vi ? this == vi : obj is UInt32 u ? this == u : obj is Int32 i ? this == i : false; } public override int GetHashCode() { return value.GetHashCode(); } } static class VarIntUtil { public static IEnumerable<byte> Pack(this IEnumerable<VarInt> data) => data.SelectMany(d => d.Encode()); public static string Print(this IEnumerable<VarInt> data) => string.Join(", ", data.Select(d => $"{(UInt32)d:X8}")); } }
30.08982
124
0.465672
[ "MIT" ]
justarandomgeek/FactorioIP
FactorioIP/VarInt.cs
5,027
C#
using System; using System.Text.Json; using System.Threading.Tasks; using GraphQL; using GraphQL.Instrumentation; using GraphQL.Types; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; namespace Example { public class GraphQLMiddleware { private readonly RequestDelegate _next; private readonly GraphQLSettings _settings; private readonly IDocumentExecuter _executer; private readonly IDocumentWriter _writer; public GraphQLMiddleware( RequestDelegate next, IOptions<GraphQLSettings> options, IDocumentExecuter executer, IDocumentWriter writer) { _next = next; _settings = options.Value; _executer = executer; _writer = writer; } public async Task Invoke(HttpContext context, ISchema schema) { if (!IsGraphQLRequest(context)) { await _next(context); return; } await ExecuteAsync(context, schema); } private bool IsGraphQLRequest(HttpContext context) { return context.Request.Path.StartsWithSegments(_settings.GraphQLPath) && string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase); } private async Task ExecuteAsync(HttpContext context, ISchema schema) { var start = DateTime.UtcNow; var request = await JsonSerializer.DeserializeAsync<GraphQLRequest> ( context.Request.Body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true } ); var result = await _executer.ExecuteAsync(options => { options.Schema = schema; options.Query = request.Query; options.OperationName = request.OperationName; options.Inputs = request.Variables.ToInputs(); options.UserContext = _settings.BuildUserContext?.Invoke(context); options.EnableMetrics = _settings.EnableMetrics; options.ExposeExceptions = _settings.ExposeExceptions; if (_settings.EnableMetrics) { options.FieldMiddleware .Use<CountFieldMiddleware>() .Use<InstrumentFieldsMiddleware>(); } }); if (_settings.EnableMetrics) { result.EnrichWithApolloTracing(start); } await WriteResponseAsync(context, result); } private async Task WriteResponseAsync(HttpContext context, ExecutionResult result) { context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; // OK await _writer.WriteAsync(context.Response.Body, result); } } }
32.304348
101
0.590175
[ "MIT" ]
GrangerAts/graphql-dotnet
src/GraphQL.Harness/GraphQLMiddleware.cs
2,972
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20181201 { /// <summary> /// NetworkSecurityGroup resource. /// </summary> [AzureNativeResourceType("azure-native:network/v20181201:NetworkSecurityGroup")] public partial class NetworkSecurityGroup : Pulumi.CustomResource { /// <summary> /// The default security rules of network security group. /// </summary> [Output("defaultSecurityRules")] public Output<ImmutableArray<Outputs.SecurityRuleResponse>> DefaultSecurityRules { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string?> Etag { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// A collection of references to network interfaces. /// </summary> [Output("networkInterfaces")] public Output<ImmutableArray<Outputs.NetworkInterfaceResponse>> NetworkInterfaces { get; private set; } = null!; /// <summary> /// The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [Output("provisioningState")] public Output<string?> ProvisioningState { get; private set; } = null!; /// <summary> /// The resource GUID property of the network security group resource. /// </summary> [Output("resourceGuid")] public Output<string?> ResourceGuid { get; private set; } = null!; /// <summary> /// A collection of security rules of the network security group. /// </summary> [Output("securityRules")] public Output<ImmutableArray<Outputs.SecurityRuleResponse>> SecurityRules { get; private set; } = null!; /// <summary> /// A collection of references to subnets. /// </summary> [Output("subnets")] public Output<ImmutableArray<Outputs.SubnetResponse>> Subnets { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a NetworkSecurityGroup resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public NetworkSecurityGroup(string name, NetworkSecurityGroupArgs args, CustomResourceOptions? options = null) : base("azure-native:network/v20181201:NetworkSecurityGroup", name, args ?? new NetworkSecurityGroupArgs(), MakeResourceOptions(options, "")) { } private NetworkSecurityGroup(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:network/v20181201:NetworkSecurityGroup", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20150501preview:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20150615:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20160330:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20160601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20160901:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20161201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20170301:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20170601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20170801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20170901:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20171001:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20171101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20180101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20180201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20180401:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20180601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20180701:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20180801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20181001:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20181101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20190201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20190401:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20190601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20190701:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20190801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20190901:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20191101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20191201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20200301:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20200401:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20200501:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20200601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20200701:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20200801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20201101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20210201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210201:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-native:network/v20210301:NetworkSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210301:NetworkSecurityGroup"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing NetworkSecurityGroup resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static NetworkSecurityGroup Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new NetworkSecurityGroup(name, id, options); } } public sealed class NetworkSecurityGroupArgs : Pulumi.ResourceArgs { [Input("defaultSecurityRules")] private InputList<Inputs.SecurityRuleArgs>? _defaultSecurityRules; /// <summary> /// The default security rules of network security group. /// </summary> public InputList<Inputs.SecurityRuleArgs> DefaultSecurityRules { get => _defaultSecurityRules ?? (_defaultSecurityRules = new InputList<Inputs.SecurityRuleArgs>()); set => _defaultSecurityRules = value; } /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the network security group. /// </summary> [Input("networkSecurityGroupName")] public Input<string>? NetworkSecurityGroupName { get; set; } /// <summary> /// The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [Input("provisioningState")] public Input<string>? ProvisioningState { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The resource GUID property of the network security group resource. /// </summary> [Input("resourceGuid")] public Input<string>? ResourceGuid { get; set; } [Input("securityRules")] private InputList<Inputs.SecurityRuleArgs>? _securityRules; /// <summary> /// A collection of security rules of the network security group. /// </summary> public InputList<Inputs.SecurityRuleArgs> SecurityRules { get => _securityRules ?? (_securityRules = new InputList<Inputs.SecurityRuleArgs>()); set => _securityRules = value; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public NetworkSecurityGroupArgs() { } } }
54.626712
153
0.616701
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20181201/NetworkSecurityGroup.cs
15,951
C#
//------------------------------------------------------------------------------ // <auto-generated> // O código foi gerado por uma ferramenta. // Versão de Tempo de Execução:4.0.30319.42000 // // As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se // o código for gerado novamente. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Ex003")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Ex003")] [assembly: System.Reflection.AssemblyTitleAttribute("Ex003")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Gerado pela classe WriteCodeFragment do MSBuild.
41.708333
90
0.651349
[ "MIT" ]
Vini-Dev-Py/C-sharp.NET
Exercicos/Ex003/Ex003/obj/Debug/netcoreapp3.1/Ex003.AssemblyInfo.cs
1,010
C#
using System.ServiceProcess; using Microsoft.AspNetCore.Hosting; namespace WindowsService { internal static class WebHostServiceExtensions { public static void RunAsCustomService(this IWebHost host) { var webHostService = new CustomWebHostService(host); ServiceBase.Run(webHostService); } } }
28.5
67
0.71345
[ "MIT" ]
wk-j/windows-service
src/WindowsService/Pack/WebHostServiceExtensions.cs
342
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace NarikDemo.Data.Model.Mapping { public partial class ProductTypeMap : IEntityTypeConfiguration<ProductType> { private readonly string _schema; public ProductTypeMap() : this("dbo") { } public ProductTypeMap(string schema) { this._schema = schema; } public void Configure(EntityTypeBuilder<ProductType> builder) { builder.ToTable("PRODUCT_TYPE", _schema); builder.HasKey(x => x.ProductTypeCd); builder.Property(x => x.ProductTypeCd).HasColumnName("PRODUCT_TYPE_CD").HasColumnType("varchar").HasMaxLength(255).IsRequired(); builder.Property(x => x.Name).HasColumnName("NAME").HasColumnType("varchar").HasMaxLength(50); ConfigurePartial(builder); } partial void ConfigurePartial(EntityTypeBuilder<ProductType> builder); } }
25.571429
140
0.616387
[ "MIT" ]
NarikMe/narik-asp-core-api-demo
Data/NarikDemo.Data/Model/Mapping/ProductTypeMap.cs
1,074
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Scorpio; namespace Scorpio.Auditing { /// <summary> /// /// </summary> public class AuditInfo { /// <summary> /// /// </summary> public string CurrentUser { get; set; } /// <summary> /// /// </summary> public string ImpersonatorUser { get; set; } /// <summary> /// /// </summary> public DateTime ExecutionTime { get; set; } /// <summary> /// /// </summary> public TimeSpan ExecutionDuration { get; set; } /// <summary> /// /// </summary> public IList<AuditActionInfo> Actions { get; } /// <summary> /// /// </summary> public IList<Exception> Exceptions { get; } /// <summary> /// /// </summary> public IDictionary<string, object> ExtraProperties { get; } /// <summary> /// /// </summary> public IList<string> Comments { get; } /// <summary> /// /// </summary> public AuditInfo() { ExtraProperties = new Dictionary<string, object>(); Actions = new List<AuditActionInfo>(); Exceptions = new List<Exception>(); Comments = new List<string>(); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> protected T GetExtraProperty<T>(string name) { return (T)(ExtraProperties.GetOrDefault(name) ?? default(T)); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="value"></param> protected void SetExtraProperty(string name, object value) { ExtraProperties[name] = value; } /// <summary> /// /// </summary> /// <typeparam name="TWapper"></typeparam> /// <returns></returns> public TWapper CreateWapper<TWapper>() where TWapper : AuditInfoWapper { return Activator.CreateInstance(typeof(TWapper), this) as TWapper; } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine($"AUDIT LOG:"); sb.AppendLine($"- {"User",-20}: {CurrentUser} "); sb.AppendLine($"- {"ExecutionDuration",-20}: {ExecutionDuration}"); if (ExtraProperties.Any()) { foreach (var property in ExtraProperties) { sb.AppendLine($"- {property.Key,-20}: {property.Value}"); } } if (Actions.Any()) { sb.AppendLine("- Actions:"); foreach (var action in Actions) { sb.AppendLine($" - {action.ServiceName}.{action.MethodName} ({action.ExecutionDuration} ms.)"); sb.AppendLine($" {action.Parameters}"); } } if (Exceptions.Any()) { sb.AppendLine("- Exceptions:"); foreach (var exception in Exceptions) { sb.AppendLine($" - {exception.Message}"); sb.AppendLine($" {exception}"); } } return sb.ToString(); } } /// <summary> /// /// </summary> public class AuditActionInfo { /// <summary> /// /// </summary> public string ServiceName { get; set; } /// <summary> /// /// </summary> public string MethodName { get; set; } /// <summary> /// /// </summary> public string Parameters { get; set; } /// <summary> /// /// </summary> public DateTime ExecutionTime { get; set; } /// <summary> /// /// </summary> public TimeSpan ExecutionDuration { get; set; } /// <summary> /// /// </summary> public Dictionary<string, object> ExtraProperties { get; } /// <summary> /// /// </summary> public AuditActionInfo() { ExtraProperties = new Dictionary<string, object>(); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> protected T GetExtraProperty<T>(string name) { return (T)(ExtraProperties.GetOrDefault(name) ?? default(T)); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="value"></param> protected void SetExtraProperty(string name, object value) { ExtraProperties[name] = value; } } }
25.463415
116
0.450766
[ "MIT" ]
wzd24/Scorpio
src/Scorpio.Auditing/Scorpio/Auditing/AuditInfo.cs
5,222
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.Data.Json; using Windows.Storage; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板 namespace Tucao.View { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class LocalVideo : Page { public LocalVideo() { this.InitializeComponent(); } //导航到该页时调用 protected override void OnNavigatedTo(NavigationEventArgs e) { Videos.ItemsSource = new ObservableCollection<Video>(); LoadItems(); } private async Task LoadItems() { ObservableCollection<Video> items = new ObservableCollection<Video>(); //下载目录 StorageFolder downloadfolder = await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("Download", CreationCollisionOption.OpenIfExists); //获取目录下 var folders = await downloadfolder.GetFoldersAsync(); int count = folders.Count; foreach (var folder in folders) { if (await folder.TryGetItemAsync("info.json") != null) { Video v = new Video(); StorageFile file = await folder.GetFileAsync("info.json"); Stream stream = await file.OpenStreamForReadAsync(); StreamReader reader = new StreamReader(stream); string str = await reader.ReadToEndAsync(); JsonObject json = JsonObject.Parse(str); v.hid = json["hid"].GetString(); v.title = json["title"].GetString(); v.parts = await LoadParts(folder); //没有下载完成的分p就不显示标题 if (v.parts.Count == 0) continue; items.Add(v); } } await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { Videos.ItemsSource = items; LoadProgress.Visibility = Visibility.Collapsed; Delete.IsEnabled = true; }); } private async Task<ObservableCollection<Part>> LoadParts(StorageFolder storage) { ObservableCollection<Part> parts = new ObservableCollection<Part>(); var folders = await storage.GetFoldersAsync(); foreach (StorageFolder folder in folders) { if (await folder.TryGetItemAsync("part.json") != null) { int i; Part p = new Part(); StorageFile jsonfile = await folder.GetFileAsync("part.json"); Stream stream = await jsonfile.OpenStreamForReadAsync(); StreamReader reader = new StreamReader(stream); string str = await reader.ReadToEndAsync(); reader.Dispose(); stream.Dispose(); JsonObject json = JsonObject.Parse(str); p.hid = storage.Name; p.partNum = int.Parse(folder.Name) - 1; p.partTitle = json["title"].GetString(); ulong size = 0; List<string> playlist = new List<string>(); for (i = 0; i < json["filecount"].GetNumber(); i++) { if (await folder.TryGetItemAsync(i.ToString()) != null) { StorageFile file = await folder.GetFileAsync(i.ToString()); var filesize = (await file.GetBasicPropertiesAsync()).Size; //文件大小为0时不继续判断 if (filesize == 0) break; size += filesize; playlist.Add(file.Path); } } //有分段视频没有下载完不添加这个分p if (i < json["filecount"].GetNumber()) continue; p.size = $"{(((double)size / 1024 / 1024)).ToString("0.0")}M"; p.play_list = playlist; parts.Add(p); } } return parts; } //点击一个视频 private void Videos_ItemClick(object sender, ItemClickEventArgs e) { App.OpenVideo((e.ClickedItem as Video).hid); } //点击一个分P private void Parts_ItemClick(object sender, ItemClickEventArgs e) { var part = e.ClickedItem as Part; var param = new MediaPlayer.MediaPlayerSource(); param.Title = (string)(sender as ListView).Tag; param.PartTitle = part.partTitle; param.PlayList = part.play_list; param.IsLocalFile = true; param.Hid = part.hid; param.Part = part.partNum; Frame root = Window.Current.Content as Frame; Frame frame = Window.Current.Content as Frame; frame.Navigate(typeof(MediaPlayer), param, new DrillInNavigationTransitionInfo()); } //打开缓存文件夹 private async void OpenDownloadFolder_Tapped(object sender, TappedRoutedEventArgs e) { await Windows.System.Launcher.LaunchFolderAsync(ApplicationData.Current.LocalCacheFolder); } public class Video { public string hid { get; set; } public string title { get; set; } public ObservableCollection<Part> parts { get; set; } } public class Part { public string hid { get; set; } public int partNum { get; set; } public string partTitle { get; set; } public string size { get; set; } public List<string> play_list { get; set; } } private void Delete_Tapped(object sender, TappedRoutedEventArgs e) { foreach (ListViewItem v in Videos.ItemsPanelRoot.Children) { ListView parts = ((v.ContentTemplateRoot as Grid).Children[0] as Grid).Children[1] as ListView; parts.SelectionMode = ListViewSelectionMode.Multiple; parts.IsItemClickEnabled = false; } Delete.Visibility = Visibility.Collapsed; OpenDownloadFolder.Visibility = Visibility.Collapsed; OK.Visibility = Visibility.Visible; Cancel.Visibility = Visibility.Visible; } private void Cancel_Tapped(object sender, TappedRoutedEventArgs e) { foreach (ListViewItem v in Videos.ItemsPanelRoot.Children) { ListView parts = ((v.ContentTemplateRoot as Grid).Children[0] as Grid).Children[1] as ListView; parts.SelectionMode = ListViewSelectionMode.None; parts.IsItemClickEnabled = true; } Delete.Visibility = Visibility.Visible; OpenDownloadFolder.Visibility = Visibility.Visible; OK.Visibility = Visibility.Collapsed; Cancel.Visibility = Visibility.Collapsed; } private async void OK_Tapped(object sender, TappedRoutedEventArgs e) { //倒着删,正着删会使\影响列表其他项目导致出错 for (int c = Videos.ItemsPanelRoot.Children.Count - 1; c >= 0; c--) { ListViewItem v = Videos.ItemsPanelRoot.Children[c] as ListViewItem; ListView parts = ((v.ContentTemplateRoot as Grid).Children[0] as Grid).Children[1] as ListView; for (int i = parts.SelectedItems.Count - 1; i >= 0; i--) { Part part = parts.SelectedItems[i] as Part; var folderpath = part.play_list[0].Remove(part.play_list[0].LastIndexOf("\\")); var folder = await StorageFolder.GetFolderFromPathAsync(folderpath); var parent = await folder.GetParentAsync(); //删除文件夹 await folder.DeleteAsync(); var items = (parts.ItemsSource as ObservableCollection<Part>); items.Remove(part); if (items.Count == 0) { (Videos.ItemsSource as ObservableCollection<Video>).Remove(parts.DataContext as Video); } //父文件夹没有文件夹时删除它 int count = (await parent.GetFoldersAsync()).Count; if (count == 0) { await parent.DeleteAsync(); } } } //完成操作后关闭删除模式 Cancel_Tapped(Cancel, new TappedRoutedEventArgs()); } } }
42.588785
158
0.53544
[ "MIT" ]
CN-Sanhei/TucaoUwp
Tucao/View/LocalVideo.xaml.cs
9,422
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace MMDash.Web.Models { public class ForgotPasswordViewModel { [Required] [EmailAddress] public string Email { get; set; } } }
19.5
44
0.708333
[ "Apache-2.0" ]
caseybarsness/MMDVMDashboard
src/MMDash.Web/Models/AccountViewModels/ForgotPasswordViewModel.cs
312
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyHealth.Client.Core.Extensions { static class DateTimeExtensions { public static DateTime DayBefore(this DateTime dt) { return dt.Subtract(new TimeSpan(1, 0, 0, 0)); } public static DateTime WithTime(this DateTime dt, string hours) { var dateAndTime = dt.Date; if (hours != null) { var tokens = hours.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); var thour = tokens[0]; var tminute = tokens.Length > 1 ? tokens[1].Substring(0, 2) : "00"; var pm = tokens[1].Length > 2 && tokens[1].ToLowerInvariant().EndsWith("pm"); var hour = 0; var minute = 0; if (int.TryParse(thour, out hour)) { if (pm) { hour += 12; } dateAndTime = dateAndTime.AddHours(hour); } if (int.TryParse(tminute, out minute)) { dateAndTime = dateAndTime.AddMinutes(minute); } } return dateAndTime; } } }
30.931818
95
0.483468
[ "MIT" ]
3miliomc/Consultorio
src/MyHealth.Client.Core/Extensions/DateTimeExtensions.cs
1,363
C#
using Abp.MultiTenancy; using AbpNiucaiCore.Authorization.Users; namespace AbpNiucaiCore.MultiTenancy { public class Tenant : AbpTenant<User> { public Tenant() { } public Tenant(string tenancyName, string name) : base(tenancyName, name) { } } }
18.444444
54
0.572289
[ "MIT" ]
linqtosql/ABPNiuCai
aspnet-core/src/AbpNiucaiCore.Core/MultiTenancy/Tenant.cs
334
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace Microsoft.TemplateEngine.Cli { internal class Dotnet { private ProcessStartInfo _info; private DataReceivedEventHandler _errorDataReceived; private StringBuilder _stderr; private StringBuilder _stdout; private DataReceivedEventHandler _outputDataReceived; private bool _anyNonEmptyStderrWritten; internal string Command => string.Concat(_info.FileName, " ", _info.Arguments); internal static Dotnet Restore(params string[] args) { return new Dotnet { _info = new ProcessStartInfo("dotnet", ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(new[] { "restore" }.Concat(args))) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true } }; } internal static Dotnet AddProjectToProjectReference(string projectFile, params string[] args) { return new Dotnet { _info = new ProcessStartInfo("dotnet", ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(new[] { "add", projectFile, "reference" }.Concat(args))) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true } }; } internal static Dotnet AddPackageReference(string projectFile, string packageName, string version = null) { string argString; if (version == null) { argString = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(new[] { "add", projectFile, "package", packageName }); } else { argString = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(new[] { "add", projectFile, "package", packageName, "--version", version }); } return new Dotnet { _info = new ProcessStartInfo("dotnet", argString) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true } }; } internal static Dotnet AddProjectsToSolution(string solutionFile, IReadOnlyList<string> projects, string solutionFolder = "") { List<string> allArgs = new List<string>() { "sln", solutionFile, "add" }; if (!string.IsNullOrWhiteSpace(solutionFolder)) { allArgs.Add("--solution-folder"); allArgs.Add(solutionFolder); } allArgs.AddRange(projects); string argString = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(allArgs); return new Dotnet { _info = new ProcessStartInfo("dotnet", argString) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true } }; } internal static Dotnet Version() { return new Dotnet { _info = new ProcessStartInfo("dotnet", "--version") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true } }; } internal Dotnet ForwardStdErr() { _errorDataReceived = ForwardStreamStdErr; return this; } internal Dotnet ForwardStdOut() { _outputDataReceived = ForwardStreamStdOut; return this; } internal Dotnet CaptureStdOut() { _stdout = new StringBuilder(); _outputDataReceived += CaptureStreamStdOut; return this; } internal Dotnet CaptureStdErr() { _stderr = new StringBuilder(); _errorDataReceived += CaptureStreamStdErr; return this; } internal Result Execute() { Process p = Process.Start(_info); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.ErrorDataReceived += OnErrorDataReceived; p.OutputDataReceived += OnOutputDataReceived; p.WaitForExit(); return new Result(_stdout?.ToString(), _stderr?.ToString(), p.ExitCode); } private void ForwardStreamStdOut(object sender, DataReceivedEventArgs e) { Console.Out.WriteLine(e.Data); } private void ForwardStreamStdErr(object sender, DataReceivedEventArgs e) { if (!_anyNonEmptyStderrWritten) { if (string.IsNullOrWhiteSpace(e.Data)) { return; } _anyNonEmptyStderrWritten = true; } Console.Error.WriteLine(e.Data); } private void CaptureStreamStdOut(object sender, DataReceivedEventArgs e) { _stdout.AppendLine(e.Data); } private void CaptureStreamStdErr(object sender, DataReceivedEventArgs e) { _stderr.AppendLine(e.Data); } private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { _outputDataReceived?.Invoke(sender, e); } private void OnErrorDataReceived(object sender, DataReceivedEventArgs e) { _errorDataReceived?.Invoke(sender, e); } internal class Result { internal Result(string stdout, string stderr, int exitCode) { StdErr = stderr; StdOut = stdout; ExitCode = exitCode; } internal string StdErr { get; } internal string StdOut { get; } internal int ExitCode { get; } } } }
31.317757
171
0.539093
[ "MIT" ]
2mol/templating
src/Microsoft.TemplateEngine.Cli/Dotnet.cs
6,702
C#
// ----------------------------------------------------------------------- // <copyright file="FunctionOutputDto.cs" company="OSharp开源团队"> // Copyright (c) 2014-2018 OSharp. All rights reserved. // </copyright> // <site>http://www.osharp.org</site> // <last-editor>郭明锋</last-editor> // <last-date>2018-06-27 4:44</last-date> // ----------------------------------------------------------------------- using System; using OSharp.Authorization.Functions; using OSharp.Entity; using OSharp.Mapping; namespace Liuliu.Demo.Security.Dtos { /// <summary> /// 功能输出DTO /// </summary> [MapFrom(typeof(Function))] public class FunctionOutputDto : IOutputDto, IDataAuthEnabled { /// <summary> /// 获取或设置 编号 /// </summary> public Guid Id { get; set; } /// <summary> /// 获取或设置 功能名称 /// </summary> public string Name { get; set; } /// <summary> /// 获取或设置 区域名称 /// </summary> public string Area { get; set; } /// <summary> /// 获取或设置 控制器名称 /// </summary> public string Controller { get; set; } /// <summary> /// 获取或设置 控制器的功能名称 /// </summary> public string Action { get; set; } /// <summary> /// 获取或设置 是否是控制器 /// </summary> public bool IsController { get; set; } /// <summary> /// 获取或设置 是否Ajax功能 /// </summary> public bool IsAjax { get; set; } /// <summary> /// 获取或设置 访问类型 /// </summary> public FunctionAccessType AccessType { get; set; } /// <summary> /// 获取或设置 访问类型是否更改,如为true,刷新功能时将忽略功能类型 /// </summary> public bool IsAccessTypeChanged { get; set; } /// <summary> /// 获取或设置 是否启用操作审计 /// </summary> public bool AuditOperationEnabled { get; set; } /// <summary> /// 获取或设置 是否启用数据审计 /// </summary> public bool AuditEntityEnabled { get; set; } /// <summary> /// 获取或设置 数据缓存时间(秒) /// </summary> public int CacheExpirationSeconds { get; set; } /// <summary> /// 获取或设置 是否相对过期时间,否则为绝对过期 /// </summary> public bool IsCacheSliding { get; set; } /// <summary> /// 获取或设置 是否锁定 /// </summary> public bool IsLocked { get; set; } #region Implementation of IDataAuthEnabled /// <summary> /// 获取或设置 是否可更新的数据权限状态 /// </summary> public bool Updatable { get; set; } /// <summary> /// 获取或设置 是否可删除的数据权限状态 /// </summary> public bool Deletable { get; set; } #endregion } }
24.917431
75
0.4838
[ "Apache-2.0" ]
leixf2005/OSharp
samples/web/Liuliu.Demo.Core/Security/Dtos/FunctionOutputDto.cs
3,160
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security; using MVCExample.Web.Models; namespace MVCExample.Web { public class EmailService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email. return Task.FromResult(0); } } public class SmsService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { // Plug in your SMS service here to send a text message. return Task.FromResult(0); } } // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); // Configure validation logic for usernames manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Configure user lockout defaults manager.UserLockoutEnabledByDefault = true; manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); manager.MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser> { MessageFormat = "Your security code is {0}" }); manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); manager.EmailService = new EmailService(); manager.SmsService = new SmsService(); var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); } return manager; } } // Configure the application sign-in manager which is used in this application. public class ApplicationSignInManager : SignInManager<ApplicationUser, string> { public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager) { } public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user) { return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager); } public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context) { return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication); } } }
39.4
152
0.659898
[ "MIT" ]
MilenaSh/Training
MVCExample/MVCExample.Web/App_Start/IdentityConfig.cs
4,336
C#
namespace Neo.SmartContract.Framework.Services.Neo { public class Notification : IApiInterface { /// <summary> /// Sender script hash /// </summary> public readonly byte[] ScriptHash; /// <summary> /// Notification's name /// </summary> public readonly string EventName; /// <summary> /// Notification's state /// </summary> public readonly object[] State; } }
22.428571
50
0.543524
[ "MIT" ]
OnBlockIO/neo-devpack-dotnet
src/Neo.SmartContract.Framework/Services/Neo/Notification.cs
471
C#
using System.ComponentModel; namespace JD_XI_Editor.Models.Enums.Analog { internal enum SubOscillatorStatus : byte { [Description("Off")] Off = 0x00, [Description("Octave -1")] Octave = 0x01, [Description("Octave -2")] TwoOctaves = 0x02 } }
25.272727
52
0.643885
[ "MIT" ]
Magiczne/JD-XI-Editor
JD-XI Editor/Models/Enums/Analog/SubOscillatorStatus.cs
280
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using MetroFramework.Forms; using Microsoft.Win32; namespace ALVR { public partial class Launcher : MetroFramework.Forms.MetroForm { string m_Host = "127.0.0.1"; int m_Port = 9944; TcpClient client; enum ServerStatus { CONNECTING, CONNECTED, DEAD }; ServerStatus status = ServerStatus.DEAD; enum ClientStatus { CONNECTED, DEAD }; ClientStatus clientStatus = ClientStatus.DEAD; string buf = ""; ServerConfig config = new ServerConfig(); public Launcher() { InitializeComponent(); } private void Launcher_Load(object sender, EventArgs e) { SetFileVersion(); if (!config.Load()) { Application.Exit(); return; } foreach (var width in ServerConfig.supportedWidth) { int i = resolutionComboBox.Items.Add(width + " x " + (width / 2)); if (config.renderWidth == width) { resolutionComboBox.SelectedItem = resolutionComboBox.Items[i]; } } bitrateTrackBar.Value = config.bitrate; SetBufferSizeBytes(config.bufferSize); metroTabControl1.SelectedTab = serverTab; UpdateServerStatus(); messageLabel.Text = "Checking server status. Please wait..."; messagePanel.Show(); findingPanel.Hide(); Connect(); timer1.Start(); } private void LaunchServer() { if (!DriverInstaller.InstallDriver()) { return; } if (!SaveConfig()) { return; } Process.Start("vrmonitor:"); } private bool SaveConfig() { // Save json int renderWidth = ServerConfig.supportedWidth[resolutionComboBox.SelectedIndex]; int bitrate = bitrateTrackBar.Value; int bufferSize = GetBufferSizeKB() * 1000; bool debugLog = debugLogCheckBox.Checked; if (!config.Save(bitrate, renderWidth, bufferSize, debugLog)) { Application.Exit(); return false; } return true; } async private Task<string> SendCommand(string command) { byte[] buffer = Encoding.UTF8.GetBytes(command + "\n"); try { client.GetStream().Write(buffer, 0, buffer.Length); } catch (Exception e) { } return await ReadNextMessage(); } async private Task<string> ReadNextMessage() { byte[] buffer = new byte[1000]; int ret = -1; try { ret = await client.GetStream().ReadAsync(buffer, 0, 1000); } catch (Exception e) { } if (ret == 0 || ret < 0) { // Disconnected client.Close(); status = ServerStatus.DEAD; UpdateServerStatus(); return ""; } else { string str = Encoding.UTF8.GetString(buffer, 0, ret); buf += str; int i = buf.IndexOf("\nEND\n"); if (i == -1) { return await ReadNextMessage(); } string ret2 = buf.Substring(0, i); buf = buf.Substring(i + 5); return ret2; } } private void SetFileVersion() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; var split = version.Split('.'); versionLabel.Text = "v" + split[0] + "." + split[1]; licenseTextBox.Text = Properties.Resources.LICENSE; } async private void Connect() { if (status != ServerStatus.DEAD && client.Connected) { return; } try { status = ServerStatus.CONNECTING; UpdateServerStatus(); client = new TcpClient(); await client.ConnectAsync(m_Host, m_Port); } catch (Exception e) { Debug.WriteLine("Connection error: " + e + "\r\n" + e.Message); } metroProgressSpinner1.Hide(); if (client.Connected) { status = ServerStatus.CONNECTED; UpdateServerStatus(); UpdateClients(); } else { status = ServerStatus.DEAD; UpdateServerStatus(); } } private void UpdateServerStatus() { if (status == ServerStatus.CONNECTED) { metroLabel3.Text = "Server is alive!"; metroLabel3.BackColor = Color.LimeGreen; metroLabel3.ForeColor = Color.White; startServerButton.Hide(); } else { metroLabel3.Text = "Server is down"; metroLabel3.BackColor = Color.Gray; metroLabel3.ForeColor = Color.White; messageLabel.Text = "Server is not runnning.\r\nPress \"Start Server\""; messagePanel.Show(); findingPanel.Hide(); startServerButton.Show(); } } async private void UpdateClients() { if (!client.Connected) { Connect(); return; } string str = await SendCommand("GetConfig"); logText.Text = str.Replace("\n", "\r\n"); if (str.Contains("Connected 1\n")) { // Connected messageLabel.Text = "Connected!\r\nPlease enjoy!"; messagePanel.Show(); findingPanel.Hide(); return; } messagePanel.Hide(); findingPanel.Show(); str = await SendCommand("GetRequests"); foreach (var row in dataGridView1.Rows.Cast<DataGridViewRow>()) { // Mark as old data row.Tag = 0; } foreach (var s in str.Split('\n')) { if (s == "") { continue; } var elem = s.Split(" ".ToCharArray(), 2); bool found = false; foreach (var row in dataGridView1.Rows.Cast<DataGridViewRow>()) { if ((string)row.Cells[1].Value == elem[0]) { found = true; row.Cells[0].Value = elem[1]; // Mark as new data row.Tag = 1; } } if (!found) { int index = dataGridView1.Rows.Add(new string[] { elem[1], elem[0], "Connect" }); dataGridView1.Rows[index].Tag = 1; } } for (int j = dataGridView1.Rows.Count - 1; j >= 0; j--) { // Remove old row if ((int)dataGridView1.Rows[j].Tag == 0) { dataGridView1.Rows.RemoveAt(j); } } noClientLabel.Visible = dataGridView1.Rows.Count == 0; } private void SetBufferSizeBytes(int bufferSizeBytes) { int kb = bufferSizeBytes / 1000; if (kb == 200) { bufferTrackBar.Value = 5; } // Map 0 - 100 to 100kB - 2000kB bufferTrackBar.Value = (kb - 100) * 100 / 1900; } private int GetBufferSizeKB() { if (bufferTrackBar.Value == 5) { return 200; } // Map 0 - 100 to 100kB - 2000kB return bufferTrackBar.Value * 1900 / 100 + 100; } // // Event handlers // private void timer1_Tick(object sender, EventArgs e) { UpdateClients(); } async private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name == "Button") { string IPAddr = (string)dataGridView1.Rows[e.RowIndex].Cells[1].Value; await SendCommand("Connect " + IPAddr); } } async private void metroButton3_Click(object sender, EventArgs e) { await SendCommand("Capture"); } async private void sendDebugPos_Click(object sender, EventArgs e) { await SendCommand("SetDebugPos " + (debugPosCheckBox.Checked ? "1" : "0") + " " + debugXTextBox.Text + " " + debugYTextBox.Text + " " + debugZTextBox); } private void bitrateTrackBar_ValueChanged(object sender, EventArgs e) { bitrateLabel.Text = bitrateTrackBar.Value + "Mbps"; } async private void button2_Click(object sender, EventArgs e) { await SendCommand("EnableTestMode " + metroTextBox1.Text); } async private void button3_Click(object sender, EventArgs e) { await SendCommand("EnableDriverTestMode " + metroTextBox2.Text); } async private void metroButton4_Click(object sender, EventArgs e) { string str = await SendCommand("GetConfig"); logText.Text = str.Replace("\n", "\r\n"); } async private void metroButton5_Click(object sender, EventArgs e) { await SendCommand("SetConfig DebugFrameIndex " + (metroCheckBox1.Checked ? "1" : "0")); } async private void metroCheckBox2_CheckedChanged(object sender, EventArgs e) { await SendCommand("Suspend " + (metroCheckBox2.Checked ? "1" : "0")); } async private void metroCheckBox3_CheckedChanged(object sender, EventArgs e) { await SendCommand("SetConfig UseKeyedMutex " + (metroCheckBox2.Checked ? "1" : "0")); } private void metroButton6_Click(object sender, EventArgs e) { LaunchServer(); } private void bufferTrackBar_ValueChanged(object sender, EventArgs e) { bufferLabel.Text = GetBufferSizeKB() + "kB"; } } }
29.242967
163
0.48347
[ "MIT", "BSD-3-Clause" ]
AGS-/ALVR
ALVR/Launcher.cs
11,436
C#
using System; using JetBrains.Annotations; namespace MicroFlow.Meta { public class ServiceInfo { public ServiceInfo( [NotNull] Type serviceType, [CanBeNull] Type implementationType = null, LifetimeKind lifetimeKind = LifetimeKind.Transient, [CanBeNull] string[] constructorArgumentExpressions = null, [CanBeNull] string instanceExpression = null) { ServiceType = serviceType.NotNull(); ImplementationType = implementationType; LifetimeKind = lifetimeKind; ConstructorArgumentExpressions = constructorArgumentExpressions; InstanceExpression = instanceExpression; } [NotNull] public static ServiceInfo Transient( [NotNull] Type serviceType, [NotNull] Type implementationType, [CanBeNull] string[] constructorArgumentExpressions = null) { return new ServiceInfo( serviceType.NotNull(), implementationType.NotNull(), constructorArgumentExpressions: constructorArgumentExpressions); } [NotNull] public static ServiceInfo Transient<TService, TImplementation>( [CanBeNull] string[] constructorArgumentExpressions = null) { return Transient( typeof(TService), typeof(TImplementation), constructorArgumentExpressions); } [NotNull] public static ServiceInfo Singleton( [NotNull] Type serviceType, [NotNull] Type implementationType, bool isDisposable = false, [CanBeNull] string[] constructorArgumentExpressions = null) { return new ServiceInfo( serviceType.NotNull(), implementationType.NotNull(), isDisposable ? LifetimeKind.DisposableSingleton : LifetimeKind.Singleton, constructorArgumentExpressions); } [NotNull] public static ServiceInfo Singleton<TService, TImplementation>( bool isDisposable = false, [CanBeNull] string[] constructorArgumentExpressions = null) { return Singleton( typeof(TService), typeof(TImplementation), isDisposable, constructorArgumentExpressions); } [NotNull] public static ServiceInfo Singleton( [NotNull] Type serviceType, [NotNull] string instanceExpression, bool isDisposable = false) { return new ServiceInfo( serviceType, lifetimeKind: isDisposable ? LifetimeKind.DisposableSingleton : LifetimeKind.Singleton, instanceExpression: instanceExpression); } [NotNull] public static ServiceInfo Singleton<TService>( [NotNull] string instanceExpression, bool isDisposable = false) { return Singleton(typeof(TService), instanceExpression, isDisposable); } public Type ServiceType { get; } [CanBeNull] public Type ImplementationType { get; } public LifetimeKind LifetimeKind { get; } [CanBeNull] public string[] ConstructorArgumentExpressions { get; } [CanBeNull] public string InstanceExpression { get; } } public enum LifetimeKind { Transient, Singleton, DisposableSingleton } }
30.29
95
0.703202
[ "MIT" ]
akarpov89/MicroFlow
src/Meta/Scheme/ServiceInfo.cs
3,029
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SecurityHub.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations { /// <summary> /// GetInsights Request Marshaller /// </summary> public class GetInsightsRequestMarshaller : IMarshaller<IRequest, GetInsightsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetInsightsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetInsightsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SecurityHub"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-10-26"; request.HttpMethod = "POST"; request.ResourcePath = "/insights/get"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetInsightArns()) { context.Writer.WritePropertyName("InsightArns"); context.Writer.WriteArrayStart(); foreach(var publicRequestInsightArnsListValue in publicRequest.InsightArns) { context.Writer.Write(publicRequestInsightArnsListValue); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetMaxResults()) { context.Writer.WritePropertyName("MaxResults"); context.Writer.Write(publicRequest.MaxResults); } if(publicRequest.IsSetNextToken()) { context.Writer.WritePropertyName("NextToken"); context.Writer.Write(publicRequest.NextToken); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetInsightsRequestMarshaller _instance = new GetInsightsRequestMarshaller(); internal static GetInsightsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetInsightsRequestMarshaller Instance { get { return _instance; } } } }
35.475
137
0.60653
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/GetInsightsRequestMarshaller.cs
4,257
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using NUnit.Framework; using Octopus.Client.Model; using Octopus.Client.Serialization; namespace Octopus.Client.Tests.Serialization { [TestFixture] public class FeedResourceConverterFixture { [Test] public void DockerFeedTypesDeserialize() { var input = new { Name = "Blah", FeedType = FeedType.Docker, ApiVersion = "Cat" }; var result = Execute<DockerFeedResource>(input); Assert.AreEqual(FeedType.Docker, result.FeedType); Assert.IsAssignableFrom(typeof(DockerFeedResource), result); Assert.AreEqual(input.ApiVersion, result.ApiVersion); } [Test] public void MavenFeedTypesDeserialize() { var input = new { Name = "Blah", FeedType = FeedType.Maven, DownloadAttempts = 91 }; var result = Execute<MavenFeedResource>(input); Assert.AreEqual(FeedType.Maven, result.FeedType); Assert.IsAssignableFrom(typeof(MavenFeedResource), result); Assert.AreEqual(input.DownloadAttempts, result.DownloadAttempts); } [Test] public void BuiltInFeedTypesDeserialize() { var input = new { Name = "Blah", FeedType = FeedType.BuiltIn, DeleteUnreleasedPackagesAfterDays = 4 }; var result = Execute<BuiltInFeedResource>(input); Assert.AreEqual(FeedType.BuiltIn, result.FeedType); Assert.IsAssignableFrom(typeof(BuiltInFeedResource), result); Assert.AreEqual(input.DeleteUnreleasedPackagesAfterDays, result.DeleteUnreleasedPackagesAfterDays); } [Test] public void GitHubFeedTypesDeserialize() { var input = new { Name = "GitIt", FeedType = FeedType.GitHub, DownloadAttempts = 91 }; var result = Execute<GitHubFeedResource>(input); Assert.AreEqual(FeedType.GitHub, result.FeedType); Assert.IsAssignableFrom(typeof(GitHubFeedResource), result); Assert.AreEqual(input.DownloadAttempts, result.DownloadAttempts); } [Test] public void NuGetFeedTypesDeserialize() { var input = new { Name = "Blah", FeedType = FeedType.NuGet }; var result = Execute<FeedResource>(input); Assert.AreEqual(FeedType.NuGet, result.FeedType); Assert.IsAssignableFrom(typeof(NuGetFeedResource), result); } [Test] public void MissingFeedTypeDeserializesAsFeedNuGet() { var input = new { Name = "Blah", }; var result = Execute<FeedResource>(input); Assert.AreEqual(FeedType.NuGet, result.FeedType); Assert.IsAssignableFrom(typeof(NuGetFeedResource), result); } private static T Execute<T>(object input) { var settings = JsonSerialization.GetDefaultSerializerSettings(); var json = JsonConvert.SerializeObject(input, settings); return (T)new FeedConverter() .ReadJson( new JsonTextReader(new StringReader(json)), typeof(T), null, JsonSerializer.Create(settings) ); } } }
29.708661
111
0.558177
[ "Apache-2.0" ]
BlythMeister/OctopusClients
source/Octopus.Client.Tests/Serialization/FeedResourceConverterFixture.cs
3,775
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Labs.Mvc.Models; using AnlabMvc.Helpers; using Dapper; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Authorization; namespace Labs.Mvc.Controllers { public class HomeController : SuperController { private readonly IConfiguration configuration; public HomeController(IConfiguration configuration) { this.configuration = configuration; } public async Task<IActionResult> Index() { var conn = this.configuration.GetConnectionString("DefaultConnection"); using (var db = new DbManager(conn)) { var terms = await db.Connection.QueryAsync<TermModel>(Queries.Terms); var model = new BulkModel(); model.Terms = terms.ToList(); return View(model); } } [HttpPost] public async Task<IActionResult> Index(BulkModel model) { var conn = this.configuration.GetConnectionString("DefaultConnection"); using (var db = new DbManager(conn)) { var terms = await db.Connection.QueryAsync<TermModel>(Queries.Terms); // TODO: figure out a way to not have to fetch this again model.Terms = terms.ToList(); if (String.IsNullOrWhiteSpace(model.SearchCourses) || String.IsNullOrWhiteSpace(model.SearchTerm)) { ErrorMessage = "You must select something to search"; return View(model); } const string regex = @"\d{5}"; var courses = System.Text.RegularExpressions.Regex.Matches(model.SearchCourses, regex).Select(x => x.Value).ToArray(); var students = await db.Connection.QueryAsync<StudentModel>(Queries.StudentsForCourse(courses, model.SearchTerm)); var studentIds = students.Select(x => x.Id).ToList().Distinct(); var cards = await db.Connection.QueryAsync<CardModel>(Queries.CardholdInfo, new { ids = studentIds }); var result = from student in students.Distinct() join card in cards on student.Id equals card.strEmployeeId into cardGroup from item in cardGroup.DefaultIfEmpty(new CardModel { CardsId = String.Empty }) select new StudentXCardModel { FirstName = student.FirstName, LastName = student.LastName, Id = student.Id, CardId = item.CardsId, nCardholderId = item.nCardholderId, Department = item.Department, strEncodedCardNumber = item.strEncodedCardNumber, dtExpirationDate = item.dtExpirationDate, nActive = item.nActive, Access1 = item.Access1, Access2 = item.Access2, nFacilityCode = item.nFacilityCode, strCardFormatName = item.strCardFormatName, Email = student.Email, Program = student.Program }; model.Terms = terms.ToList(); model.StudentsWithCards = result.Where(x => checkValid(x) && !String.IsNullOrEmpty(x.CardId)).ToList(); model.StudentsWithoutCards = result.Where(x => String.IsNullOrEmpty(x.CardId)).ToList(); model.StudentsWithProblems = result.Where(x => !checkValid(x) && !String.IsNullOrEmpty(x.CardId)).ToList(); return View(model); } } public IActionResult Privacy() { return View(); } [HttpGet] public IActionResult Query() { var conn = this.configuration.GetConnectionString("DefaultConnection"); using (var db = new DbManager(conn)) { var result = db.Connection.Query(Queries.CardholdInfo, new { ids = new[] { "999811562" } }); return Json(result); } } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } private bool checkValid(StudentXCardModel student) { if(student.nActive == "0" || student.dtExpirationDate < DateTime.Today) { return false; } else { return true; } } } }
41.456
144
0.529718
[ "MIT" ]
ucdavis/labs
src/Labs.Mvc/Controllers/HomeController.cs
5,184
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #region Usings Setup using System; using System.Collections.Generic; using System.Globalization; using System.Net; using Mozu.Api; using Mozu.Api.Security; using Mozu.Api.Test.Helpers; using System.Diagnostics; using Newtonsoft.Json.Linq; #endregion namespace Mozu.Api.Test.Factories { /// <summary> /// Use the Cart Items subresource to manage a collection of items in an active shopping cart. /// </summary> public partial class CartItemFactory : BaseDataFactory { /// <summary> /// Retrieves a particular cart item by providing the cart item ID. /// <example> /// <code> /// var result = CartItemFactory.GetCartItem(handler : handler, cartItemId : cartItemId, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CartItem/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.CommerceRuntime.Carts.CartItem GetCartItem(ServiceClientMessageHandler handler, string cartItemId, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Carts.CartItemClient.GetCartItemClient( cartItemId : cartItemId, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).Execute(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// Retrieves a list of cart items including the total number of items in the cart. /// <example> /// <code> /// var result = CartItemFactory.GetCartItems(handler : handler, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CartItemCollection/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.CommerceRuntime.Carts.CartItemCollection GetCartItems(ServiceClientMessageHandler handler, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Carts.CartItemClient.GetCartItemsClient( responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).Execute(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// Adds a product to the current shopper's cart. /// <example> /// <code> /// var result = CartItemFactory.AddItemToCart(handler : handler, cartItem : cartItem, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CartItem/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.CommerceRuntime.Carts.CartItem AddItemToCart(ServiceClientMessageHandler handler, Mozu.Api.Contracts.CommerceRuntime.Carts.CartItem cartItem, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.Created, HttpStatusCode successCode = HttpStatusCode.Created) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Carts.CartItemClient.AddItemToCartClient( cartItem : cartItem, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).Execute(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// Update the quantity of an individual cart item in the cart of the current shopper. /// <example> /// <code> /// var result = CartItemFactory.UpdateCartItemQuantity(handler : handler, cartItemId : cartItemId, quantity : quantity, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CartItem/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.CommerceRuntime.Carts.CartItem UpdateCartItemQuantity(ServiceClientMessageHandler handler, string cartItemId, int quantity, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Carts.CartItemClient.UpdateCartItemQuantityClient( cartItemId : cartItemId, quantity : quantity, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).Execute(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// Update the product or product quantity of an item in the current shopper's cart. /// <example> /// <code> /// var result = CartItemFactory.UpdateCartItem(handler : handler, cartItem : cartItem, cartItemId : cartItemId, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CartItem/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.CommerceRuntime.Carts.CartItem UpdateCartItem(ServiceClientMessageHandler handler, Mozu.Api.Contracts.CommerceRuntime.Carts.CartItem cartItem, string cartItemId, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Carts.CartItemClient.UpdateCartItemClient( cartItem : cartItem, cartItemId : cartItemId, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).Execute(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// Removes all items in the current shopper's active cart. /// <example> /// <code> /// var result = CartItemFactory.RemoveAllCartItems(handler : handler, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<Cart/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.CommerceRuntime.Carts.Cart RemoveAllCartItems(ServiceClientMessageHandler handler, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Carts.CartItemClient.RemoveAllCartItemsClient( ); try { apiClient.WithContext(handler.ApiContext).Execute(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// Deletes a specific cart item by providing the cart item ID. /// <example> /// <code> /// var result = CartItemFactory.DeleteCartItem(handler : handler, cartItemId : cartItemId, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<void/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static void DeleteCartItem(ServiceClientMessageHandler handler, string cartItemId, HttpStatusCode expectedCode = HttpStatusCode.NoContent, HttpStatusCode successCode = HttpStatusCode.NoContent) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Carts.CartItemClient.DeleteCartItemClient( cartItemId : cartItemId ); try { apiClient.WithContext(handler.ApiContext).Execute(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; } var noResponse = ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } } }
41.587459
218
0.724625
[ "MIT" ]
thomsumit/mozu-dotnet
Mozu.Api.Test/Factories/CartItemFactory.cs
12,601
C#
#pragma checksum "..\..\..\WindowFrame\LeftSideMenuControl.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "02E20611146158601F08DA89479C147355D75FCC" //------------------------------------------------------------------------------ // <auto-generated> // 這段程式碼是由工具產生的。 // 執行階段版本:4.0.30319.42000 // // 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, // 變更將會遺失。 // </auto-generated> //------------------------------------------------------------------------------ using Server_Restart_Final; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Forms.Integration; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Server_Restart_Final { /// <summary> /// LeftSideMenuControl /// </summary> public partial class LeftSideMenuControl : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { #line 113 "..\..\..\WindowFrame\LeftSideMenuControl.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Canvas Maincanvas; #line default #line hidden #line 115 "..\..\..\WindowFrame\LeftSideMenuControl.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Frame PageContent; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Endless Development Project Studio;component/windowframe/leftsidemenucontrol.xam" + "l", System.UriKind.Relative); #line 1 "..\..\..\WindowFrame\LeftSideMenuControl.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal System.Delegate _CreateDelegate(System.Type delegateType, string handler) { return System.Delegate.CreateDelegate(delegateType, this, handler); } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.Maincanvas = ((System.Windows.Controls.Canvas)(target)); return; case 2: this.PageContent = ((System.Windows.Controls.Frame)(target)); return; case 3: #line 124 "..\..\..\WindowFrame\LeftSideMenuControl.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Click); #line default #line hidden return; } this._contentLoaded = true; } } }
40.610169
149
0.653589
[ "BSD-3-Clause" ]
asd7766zxc/Endless_Development_Project
obj/Release/WindowFrame/LeftSideMenuControl.g.i.cs
4,912
C#
namespace Dev.DevKit.Shared.Entities { public partial class ActionCardUserState { #region --- PROPERTIES --- //public DateTime? DateTime { get { return GetAliasedValue<DateTime?>("c.birthdate"); } } #endregion #region --- STATIC METHODS --- #endregion } }
18.470588
97
0.592357
[ "MIT" ]
Kayserheimer/Dynamics-Crm-DevKit
test/v.2.12.31/TestAllEntities/All-DEMO/Dev.DevKit.Shared/Entities/ActionCardUserState.cs
316
C#
/* * Copyright (c) 2010-2012, Achim 'ahzf' Friedland <code@ahzf.de> * This file is part of Pipes.NET <http://www.github.com/ahzf/Pipes.NET> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Usings using System; using System.Collections.Generic; using System.Collections; #endregion namespace de.ahzf.Styx { /// <summary> /// The SideEffectCapPipe will yield an E that is the side effect of /// the provided SideEffectPipe. This is useful for when the side /// effect of a Pipe is desired in a computational stream. /// </summary> /// <typeparam name="S">The type of the consuming objects.</typeparam> /// <typeparam name="T">The type of the sideeffect.</typeparam> public class SideEffectCapPipe<S, T> : AbstractPipe<S, T>, IStartPipe { // Note: Usage of IStartPipe in order to allow explicit // interface implementation! #region Data private readonly ISideEffectPipe<S, Object, T> _PipeToCap; private Boolean _Alive; #endregion #region Constructor(s) #region SideEffectCapPipe() /// <summary> /// Creates a new SideEffectCapPipe. /// </summary> public SideEffectCapPipe() { } #endregion #region SideEffectCapPipe(myPipeToCap) /// <summary> /// Creates a new SideEffectCapPipe. /// </summary> /// <param name="myPipeToCap">A ISideEffectCapPipe.</param> public SideEffectCapPipe(ISideEffectPipe<S, Object, T> myPipeToCap) { _PipeToCap = myPipeToCap; _Alive = true; } #endregion #endregion #region SetSource(IEnumerator) /// <summary> /// Set the elements emitted by the given IEnumerator&lt;S&gt; as input. /// </summary> /// <param name="IEnumerator">An IEnumerator&lt;S&gt; as element source.</param> public override void SetSource(IEnumerator<S> IEnumerator) { _PipeToCap.SetSource(IEnumerator); } #endregion #region SetSourceCollection(IEnumerable) /// <summary> /// Set the elements emitted by the given IEnumerator&lt;S&gt; as input. /// </summary> /// <param name="IEnumerable">An IEnumerable&lt;S&gt; as element source.</param> public override void SetSourceCollection(IEnumerable<S> IEnumerable) { _PipeToCap.SetSource(IEnumerable.GetEnumerator()); } #endregion #region MoveNext() /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// True if the enumerator was successfully advanced to the next /// element; false if the enumerator has passed the end of the /// collection. /// </returns> public override Boolean MoveNext() { if (_Alive) { // Consume the entire pipe! while (_PipeToCap.MoveNext()) { } _Alive = false; _CurrentElement = _PipeToCap.SideEffect; return true; } else return false; } #endregion #region Path /// <summary> /// Returns the transformation path to arrive at the current object /// of the pipe. This is a list of all of the objects traversed for /// the current iterator position of the pipe. /// </summary> public new List<Object> Path { get { var _List = _PipeToCap.Path; _List.Add(this._CurrentElement); return _List; } } #endregion #region ToString() /// <summary> /// A string representation of this pipe. /// </summary> public override String ToString() { return base.ToString() + "[" + _PipeToCap + "]"; } #endregion } }
26.337079
88
0.571672
[ "MIT" ]
isa-group/mcc-engine
Styx/Pipes/SideeffectPipes/SideEffectCapPipe.cs
4,690
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchAllQueryArguments { [OutputConstructor] private WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchAllQueryArguments() { } } }
31.363636
131
0.771014
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchAllQueryArguments.cs
690
C#