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
using System.Threading.Tasks; using WeatherDiary.Domain; namespace WeatherDiary.Api { public class EmptyWeatherApiRequester : IWeatherApiRequester { internal static readonly WeatherStamp EmptyStamp = new WeatherStamp(Cloudy.Cloudless, Phenomena.None, Precipitation.None, 0, 0, WindDirection.None, 0); public WeatherStamp GetRecord(string city) { // Empty return EmptyStamp; } public Task<WeatherStamp> GetRecordTask(string city) { // Empty return new Task<WeatherStamp>(() => EmptyStamp); } } }
37.333333
93
0.390873
[ "MIT" ]
ashenBlade/WeatherDiaryApp
WeatherDiary.Api/EmptyWeatherApiRequester.cs
1,008
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Threading.Tasks; using Squidex.Domain.Apps.Entities.Assets.Commands; using Squidex.Domain.Apps.Entities.Assets.Guards; using Squidex.Domain.Apps.Entities.Assets.State; using Squidex.Domain.Apps.Events; using Squidex.Domain.Apps.Events.Assets; using Squidex.Infrastructure; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.EventSourcing; using Squidex.Infrastructure.Log; using Squidex.Infrastructure.Orleans; using Squidex.Infrastructure.Reflection; using Squidex.Infrastructure.States; namespace Squidex.Domain.Apps.Entities.Assets { public sealed class AssetFolderGrain : DomainObjectGrain<AssetFolderState>, IAssetFolderGrain { private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5); private readonly IAssetQueryService assetQuery; public AssetFolderGrain(IStore<Guid> store, IAssetQueryService assetQuery, IActivationLimit limit, ISemanticLog log) : base(store, log) { Guard.NotNull(assetQuery); this.assetQuery = assetQuery; limit?.SetLimit(5000, Lifetime); } protected override Task OnActivateAsync(Guid key) { TryDelayDeactivation(Lifetime); return base.OnActivateAsync(key); } protected override Task<object?> ExecuteAsync(IAggregateCommand command) { VerifyNotDeleted(); switch (command) { case CreateAssetFolder createAssetFolder: return CreateReturnAsync(createAssetFolder, async c => { await GuardAssetFolder.CanCreate(c, assetQuery); Create(c); return Snapshot; }); case MoveAssetFolder moveAssetFolder: return UpdateReturnAsync(moveAssetFolder, async c => { await GuardAssetFolder.CanMove(c, assetQuery, Snapshot.Id, Snapshot.ParentId); Move(c); return Snapshot; }); case RenameAssetFolder renameAssetFolder: return UpdateReturn(renameAssetFolder, c => { GuardAssetFolder.CanRename(c, Snapshot.FolderName); Rename(c); return Snapshot; }); case DeleteAssetFolder deleteAssetFolder: return Update(deleteAssetFolder, c => { GuardAssetFolder.CanDelete(c); Delete(c); }); default: throw new NotSupportedException(); } } public void Create(CreateAssetFolder command) { RaiseEvent(SimpleMapper.Map(command, new AssetFolderCreated())); } public void Move(MoveAssetFolder command) { RaiseEvent(SimpleMapper.Map(command, new AssetFolderMoved())); } public void Rename(RenameAssetFolder command) { RaiseEvent(SimpleMapper.Map(command, new AssetFolderRenamed())); } public void Delete(DeleteAssetFolder command) { RaiseEvent(SimpleMapper.Map(command, new AssetFolderDeleted())); } private void RaiseEvent(AppEvent @event) { if (@event.AppId == null) { @event.AppId = Snapshot.AppId; } RaiseEvent(Envelope.Create(@event)); } private void VerifyNotDeleted() { if (Snapshot.IsDeleted) { throw new DomainException("Asset folder has already been deleted"); } } } }
32.389313
124
0.542776
[ "MIT" ]
BigHam/squidex
backend/src/Squidex.Domain.Apps.Entities/Assets/AssetFolderGrain.cs
4,246
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("TelerikWpfMain")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TelerikWpfMain")] [assembly: AssemblyCopyright("Copyright © 2017")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.571429
98
0.707634
[ "Apache-2.0" ]
emacslisp/TelerikWPF
TelerikWpfMain/TelerikWpfMain/Properties/AssemblyInfo.cs
2,387
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System.Text; namespace Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Runtime.Json { internal static class StringBuilderExtensions { /// <summary> /// Extracts the buffered value and resets the buffer /// </summary> internal static string Extract(this StringBuilder builder) { var text = builder.ToString(); builder.Clear(); return text; } } }
35.695652
97
0.476248
[ "MIT" ]
3quanfeng/azure-powershell
src/HealthBot/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs
801
C#
// // Copyright (c) Seal Report, Eric Pfirsch (sealreport@gmail.com), http://www.sealreport.org. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. http://www.apache.org/licenses/LICENSE-2.0.. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing.Design; using System.ComponentModel; using System.Windows.Forms.Design; using System.Windows.Forms; using Seal.Model; using System.ComponentModel.Design; using System.Reflection; using System.Drawing; namespace Seal.Forms { public class EntityCollectionEditor : CollectionEditor { // Define a static event to expose the inner PropertyGrid's // PropertyValueChanged event args... public delegate void ViewParameterPropertyValueChangedEventHandler(object sender, PropertyValueChangedEventArgs e); public static event ViewParameterPropertyValueChangedEventHandler MyPropertyValueChanged; RootComponent _component = null; public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { if (context.Instance is RootComponent) _component = (RootComponent)context.Instance; if (context.PropertyDescriptor.IsReadOnly) return UITypeEditorEditStyle.None; return UITypeEditorEditStyle.Modal; } void SetModified() { if (HelperEditor.HandlerInterface != null && _useHandlerInterface) HelperEditor.HandlerInterface.SetModified(); } // Inherit the default constructor from the standard // Collection Editor... public EntityCollectionEditor(Type type) : base(type) { } bool _useHandlerInterface = true; // Override this method in order to access the containing user controls // from the default Collection Editor form or to add new ones... protected override CollectionForm CreateCollectionForm() { // Getting the default layout of the Collection Editor... CollectionForm collectionForm = base.CreateCollectionForm(); bool allowAdd = false; bool allowRemove = false; Form frmCollectionEditorForm = collectionForm as Form; frmCollectionEditorForm.HelpButton = false; frmCollectionEditorForm.Text = "Collection Editor"; if (CollectionItemType == typeof(ReportRestriction)) { frmCollectionEditorForm.Text = "Restrictions Collection Editor"; } else if (CollectionItemType == typeof(OutputParameter)) { frmCollectionEditorForm.Text = "Custom Output Parameters Collection Editor"; } else if (CollectionItemType == typeof(SecurityParameter)) { frmCollectionEditorForm.Text = "Security Parameters Collection Editor"; _useHandlerInterface = false; } else if (CollectionItemType == typeof(Parameter)) { frmCollectionEditorForm.Text = "Template Parameters Collection Editor"; } else if (CollectionItemType == typeof(SecurityGroup)) { frmCollectionEditorForm.Text = "Security Groups Collection Editor"; allowAdd = true; allowRemove = true; _useHandlerInterface = false; } else if (CollectionItemType == typeof(SecurityFolder)) { frmCollectionEditorForm.Text = "Security Folders Collection Editor"; allowAdd = true; allowRemove = true; _useHandlerInterface = false; } else if (CollectionItemType == typeof(SecurityColumn)) { frmCollectionEditorForm.Text = "Security Columns Collection Editor"; allowAdd = true; allowRemove = true; _useHandlerInterface = false; } else if (CollectionItemType == typeof(SecuritySource)) { frmCollectionEditorForm.Text = "Security Data Sources Collection Editor"; allowAdd = true; allowRemove = true; _useHandlerInterface = false; } else if (CollectionItemType == typeof(SecurityDevice)) { frmCollectionEditorForm.Text = "Security Devices Collection Editor"; allowAdd = true; allowRemove = true; _useHandlerInterface = false; } else if (CollectionItemType == typeof(SecurityConnection)) { frmCollectionEditorForm.Text = "Security Connections Collection Editor"; allowAdd = true; allowRemove = true; _useHandlerInterface = false; } else if (CollectionItemType == typeof(SubReport)) { frmCollectionEditorForm.Text = "Sub-Reports Collection Editor"; allowRemove = true; _useHandlerInterface = true; } else if (CollectionItemType == typeof(ReportViewPartialTemplate)) { frmCollectionEditorForm.Text = "Partial Templates Collection Editor"; _useHandlerInterface = false; } TableLayoutPanel tlpLayout = frmCollectionEditorForm.Controls[0] as TableLayoutPanel; if (tlpLayout != null) { // Get a reference to the inner PropertyGrid and hook // an event handler to it. if (tlpLayout.Controls[5] is PropertyGrid) { PropertyGrid propertyGrid = tlpLayout.Controls[5] as PropertyGrid; propertyGrid.HelpVisible = true; propertyGrid.ToolbarVisible = false; propertyGrid.PropertyValueChanged += new PropertyValueChangedEventHandler(propertyGrid_PropertyValueChanged); propertyGrid.LineColor = SystemColors.ControlLight; } } //Hide Add/Remove -> Get the forms type if (!allowRemove) { Type formType = frmCollectionEditorForm.GetType(); FieldInfo fieldInfo = formType.GetField("removeButton", BindingFlags.NonPublic | BindingFlags.Instance); if (fieldInfo != null) { System.Windows.Forms.Control removeButton = (System.Windows.Forms.Control)fieldInfo.GetValue(frmCollectionEditorForm); removeButton.Hide(); } } if (!allowAdd) { Type formType = frmCollectionEditorForm.GetType(); FieldInfo fieldInfo = formType.GetField("addButton", BindingFlags.NonPublic | BindingFlags.Instance); if (fieldInfo != null) { System.Windows.Forms.Control addButton = (System.Windows.Forms.Control)fieldInfo.GetValue(frmCollectionEditorForm); addButton.Hide(); } } return collectionForm; } void propertyGrid_PropertyValueChanged(object sender, PropertyValueChangedEventArgs e) { // Fire our customized collection event... if (EntityCollectionEditor.MyPropertyValueChanged != null) { EntityCollectionEditor.MyPropertyValueChanged(this, e); } SetModified(); } protected override object CreateInstance(Type itemType) { object instance = Activator.CreateInstance(itemType, true); SetModified(); if (_component != null) _component.UpdateEditor(); return instance; } protected override void DestroyInstance(object instance) { base.DestroyInstance(instance); SetModified(); if (_component != null) _component.UpdateEditor(); } protected override string GetDisplayText(object value) { string result = ""; if (value is RootEditor) ((RootEditor)value).InitEditor(); if (value is ReportRestriction) result = string.Format("{0} ({1})", ((ReportRestriction)value).DisplayNameEl, ((ReportRestriction)value).Model.Name); else if (value is Parameter) result = ((Parameter)value).DisplayName; else if (value is SecurityGroup) result = ((SecurityGroup)value).Name; else if (value is SecurityFolder) result = ((SecurityFolder)value).Path; else if (value is SecurityColumn) result = ((SecurityColumn)value).DisplayName; else if (value is SecuritySource) result = ((SecuritySource)value).DisplayName; else if (value is SecurityDevice) result = ((SecurityDevice)value).DisplayName; else if (value is SecurityConnection) result = ((SecurityConnection)value).DisplayName; else if (value is SubReport) result = ((SubReport)value).Name; else if (value is ReportComponent) result = ((ReportComponent)value).Name; return base.GetDisplayText(string.IsNullOrEmpty(result) ? "<Empty Name>" : result); } } }
43.018265
176
0.60588
[ "Apache-2.0" ]
chinayou25/Seal-Report
Projects/SealLibrary/Forms/EntityCollectionEditor.cs
9,423
C#
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1 { public class DerObjectIdentifier : Asn1Object { private readonly string identifier; private byte[] body = null; /** * return an Oid from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerObjectIdentifier GetInstance(object obj) { if (obj == null || obj is DerObjectIdentifier) return (DerObjectIdentifier) obj; if (obj is byte[]) return FromOctetString((byte[])obj); throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * return an object Identifier from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerObjectIdentifier GetInstance( Asn1TaggedObject obj, bool explicitly) { Asn1Object o = obj.GetObject(); if (explicitly || o is DerObjectIdentifier) { return GetInstance(o); } return FromOctetString(Asn1OctetString.GetInstance(o).GetOctets()); } public DerObjectIdentifier( string identifier) { if (identifier == null) throw new ArgumentNullException("identifier"); if (!IsValidIdentifier(identifier)) throw new FormatException("string " + identifier + " not an OID"); this.identifier = identifier; } internal DerObjectIdentifier(DerObjectIdentifier oid, string branchID) { if (!IsValidBranchID(branchID, 0)) throw new ArgumentException("string " + branchID + " not a valid OID branch", "branchID"); this.identifier = oid.Id + "." + branchID; } // TODO Change to ID? public string Id { get { return identifier; } } public virtual DerObjectIdentifier Branch(string branchID) { return new DerObjectIdentifier(this, branchID); } /** * Return true if this oid is an extension of the passed in branch, stem. * @param stem the arc or branch that is a possible parent. * @return true if the branch is on the passed in stem, false otherwise. */ public virtual bool On(DerObjectIdentifier stem) { string id = Id, stemId = stem.Id; return id.Length > stemId.Length && id[stemId.Length] == '.' && Platform.StartsWith(id, stemId); } internal DerObjectIdentifier(byte[] bytes) { this.identifier = MakeOidStringFromBytes(bytes); this.body = Arrays.Clone(bytes); } private void WriteField( Stream outputStream, long fieldValue) { byte[] result = new byte[9]; int pos = 8; result[pos] = (byte)(fieldValue & 0x7f); while (fieldValue >= (1L << 7)) { fieldValue >>= 7; result[--pos] = (byte)((fieldValue & 0x7f) | 0x80); } outputStream.Write(result, pos, 9 - pos); } private void WriteField( Stream outputStream, BigInteger fieldValue) { int byteCount = (fieldValue.BitLength + 6) / 7; if (byteCount == 0) { outputStream.WriteByte(0); } else { BigInteger tmpValue = fieldValue; byte[] tmp = new byte[byteCount]; for (int i = byteCount-1; i >= 0; i--) { tmp[i] = (byte) ((tmpValue.IntValue & 0x7f) | 0x80); tmpValue = tmpValue.ShiftRight(7); } tmp[byteCount-1] &= 0x7f; outputStream.Write(tmp, 0, tmp.Length); } } private void DoOutput(MemoryStream bOut) { OidTokenizer tok = new OidTokenizer(identifier); string token = tok.NextToken(); int first = int.Parse(token) * 40; token = tok.NextToken(); if (token.Length <= 18) { WriteField(bOut, first + Int64.Parse(token)); } else { WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first))); } while (tok.HasMoreTokens) { token = tok.NextToken(); if (token.Length <= 18) { WriteField(bOut, Int64.Parse(token)); } else { WriteField(bOut, new BigInteger(token)); } } } internal byte[] GetBody() { lock (this) { if (body == null) { MemoryStream bOut = new MemoryStream(); DoOutput(bOut); body = bOut.ToArray(); } } return body; } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, GetBody()); } protected override int Asn1GetHashCode() { return identifier.GetHashCode(); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerObjectIdentifier other = asn1Object as DerObjectIdentifier; if (other == null) return false; return this.identifier.Equals(other.identifier); } public override string ToString() { return identifier; } private static bool IsValidBranchID( String branchID, int start) { bool periodAllowed = false; int pos = branchID.Length; while (--pos >= start) { char ch = branchID[pos]; // TODO Leading zeroes? if ('0' <= ch && ch <= '9') { periodAllowed = true; continue; } if (ch == '.') { if (!periodAllowed) return false; periodAllowed = false; continue; } return false; } return periodAllowed; } private static bool IsValidIdentifier(string identifier) { if (identifier.Length < 3 || identifier[1] != '.') return false; char first = identifier[0]; if (first < '0' || first > '2') return false; return IsValidBranchID(identifier, 2); } private const long LONG_LIMIT = (long.MaxValue >> 7) - 0x7f; private static string MakeOidStringFromBytes( byte[] bytes) { StringBuilder objId = new StringBuilder(); long value = 0; BigInteger bigValue = null; bool first = true; for (int i = 0; i != bytes.Length; i++) { int b = bytes[i]; if (value <= LONG_LIMIT) { value += (b & 0x7f); if ((b & 0x80) == 0) // end of number reached { if (first) { if (value < 40) { objId.Append('0'); } else if (value < 80) { objId.Append('1'); value -= 40; } else { objId.Append('2'); value -= 80; } first = false; } objId.Append('.'); objId.Append(value); value = 0; } else { value <<= 7; } } else { if (bigValue == null) { bigValue = BigInteger.ValueOf(value); } bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f)); if ((b & 0x80) == 0) { if (first) { objId.Append('2'); bigValue = bigValue.Subtract(BigInteger.ValueOf(80)); first = false; } objId.Append('.'); objId.Append(bigValue); bigValue = null; value = 0; } else { bigValue = bigValue.ShiftLeft(7); } } } return objId.ToString(); } private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024]; internal static DerObjectIdentifier FromOctetString(byte[] enc) { int hashCode = Arrays.GetHashCode(enc); int first = hashCode & 1023; lock (cache) { DerObjectIdentifier entry = cache[first]; if (entry != null && Arrays.AreEqual(enc, entry.GetBody())) { return entry; } return cache[first] = new DerObjectIdentifier(enc); } } } }
30.022535
110
0.433759
[ "Apache-2.0" ]
Arthurvdmerwe/-ISO-TC-68-SC-2-ISO20038
Crypto/src/asn1/DerObjectIdentifier.cs
10,658
C#
// https://leetcode.com/problems/create-maximum-number/ // // Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits. You should try to optimize your time and space complexity. // // Example 1: // // nums1 = [3, 4, 6, 5] 3 4 6 5 // nums2 = [9, 1, 2, 5, 8, 3] 9 9 9 9 9 // k = 5 1 3 4 6 5 // return [9, 8, 6, 5, 3] 2 3 4 6 5 // 5 5 5 6 5 // Example 2: 8 8 8 8 8 // 3 3 4 6 5 // nums1 = [6, 7] // nums2 = [6, 0, 4] // k = 5 // return [6, 7, 6, 0, 4] // // Example 3: // // nums1 = [3, 9] // nums2 = [8, 9] // k = 3 // return [9, 8, 9] using System; using System.Linq; public class Solution { public int[] MaxNumber(int[] nums1, int[] nums2, int k) { var dp = new int [nums1.Length + 1, nums2.Length + 1, k + 1]; var result = new int[k]; var prevMax = 0; for (var i = 0; i <= k; i++) { var max = 0; for (var a = 0; a <= nums1.Length; a++) { for (var b = 0; b <= nums2.Length; b++) { if (i == 0 || a == 0 && b == 0) { dp[a, b, i] = 0; } else if (a == 0) { dp[a, b, i] = Math.Max(nums2[b - 1] + dp[0, b - 1, i - 1], dp[0, b - 1, i]); } else if (b == 0) { dp[a, b, i] = Math.Max(nums1[a - 1] + dp[a - 1, 0, i - 1], dp[a - 1, 0, i]); } else { dp[a, b, i] = Math.Max( dp[a - 1, b - 1, i], Math.Max( nums1[a - 1] + dp[a - 1, b, i - 1], nums2[b - 1] + dp[a, b - 1, i - 1])); } max = Math.Max(max, dp[a, b, i]); } } if (i > 0) { result[i - 1] = max - prevMax; prevMax = max; } } for (var i = 0; i <= k; i++) { Console.WriteLine(i); for (var a = 0; a <= nums1.Length; a++) { for (var b = 0; b <= nums2.Length; b++) { Console.Write(dp[a, b, i] + " "); } Console.WriteLine(); } Console.WriteLine(); } return result; } static void Main() { var s = new Solution(); Console.WriteLine(String.Join(", ", s.MaxNumber(new [] { 3, 4, 6, 5 }, new [] { 9, 1, 2, 5, 8, 3 }, 5))); Console.WriteLine(String.Join(", ", s.MaxNumber(new [] { 6, 7 }, new [] { 6, 0, 4 }, 5))); Console.WriteLine(String.Join(", ", s.MaxNumber(new [] { 3, 9 }, new [] { 8, 9 }, 3))); } }
33.782178
316
0.336166
[ "MIT" ]
Gerula/interviews
LeetCode/remote/create_maximum_number.cs
3,412
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 batch-2016-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Batch.Model { /// <summary> /// Container for the parameters to the CancelJob operation. /// Cancels a job in an AWS Batch job queue. Jobs that are in the <code>SUBMITTED</code>, /// <code>PENDING</code>, or <code>RUNNABLE</code> state are canceled. Jobs that have /// progressed to <code>STARTING</code> or <code>RUNNING</code> aren't canceled, but the /// API operation still succeeds, even if no job is canceled. These jobs must be terminated /// with the <a>TerminateJob</a> operation. /// </summary> public partial class CancelJobRequest : AmazonBatchRequest { private string _jobId; private string _reason; /// <summary> /// Gets and sets the property JobId. /// <para> /// The AWS Batch job ID of the job to cancel. /// </para> /// </summary> [AWSProperty(Required=true)] public string JobId { get { return this._jobId; } set { this._jobId = value; } } // Check to see if JobId property is set internal bool IsSetJobId() { return this._jobId != null; } /// <summary> /// Gets and sets the property Reason. /// <para> /// A message to attach to the job that explains the reason for canceling it. This message /// is returned by future <a>DescribeJobs</a> operations on the job. This message is also /// recorded in the AWS Batch activity logs. /// </para> /// </summary> [AWSProperty(Required=true)] public string Reason { get { return this._reason; } set { this._reason = value; } } // Check to see if Reason property is set internal bool IsSetReason() { return this._reason != null; } } }
32.6
103
0.623241
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/Batch/Generated/Model/CancelJobRequest.cs
2,771
C#
/* * Copyright 2010-2014 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 codebuild-2016-10-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CodeBuild.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeBuild.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for BuildArtifacts Object /// </summary> public class BuildArtifactsUnmarshaller : IUnmarshaller<BuildArtifacts, XmlUnmarshallerContext>, IUnmarshaller<BuildArtifacts, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> BuildArtifacts IUnmarshaller<BuildArtifacts, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public BuildArtifacts Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; BuildArtifacts unmarshalledObject = new BuildArtifacts(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("artifactIdentifier", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ArtifactIdentifier = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("encryptionDisabled", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.EncryptionDisabled = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("location", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Location = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("md5sum", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Md5sum = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("overrideArtifactName", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.OverrideArtifactName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("sha256sum", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Sha256sum = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static BuildArtifactsUnmarshaller _instance = new BuildArtifactsUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static BuildArtifactsUnmarshaller Instance { get { return _instance; } } } }
37.52459
155
0.603757
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/Model/Internal/MarshallTransformations/BuildArtifactsUnmarshaller.cs
4,578
C#
namespace TCPingInfoView.Forms { partial class DisplayedColumns { /// <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.checkedListBox1 = new System.Windows.Forms.CheckedListBox(); this.OK_button = new System.Windows.Forms.Button(); this.Cancel_button = new System.Windows.Forms.Button(); this.SuspendLayout(); // // checkedListBox1 // this.checkedListBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.checkedListBox1.CheckOnClick = true; this.checkedListBox1.FormattingEnabled = true; this.checkedListBox1.Location = new System.Drawing.Point(13, 13); this.checkedListBox1.Name = "checkedListBox1"; this.checkedListBox1.Size = new System.Drawing.Size(191, 180); this.checkedListBox1.TabIndex = 0; this.checkedListBox1.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.checkedListBox1_ItemCheck); // // OK_button // this.OK_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.OK_button.Location = new System.Drawing.Point(48, 210); this.OK_button.Name = "OK_button"; this.OK_button.Size = new System.Drawing.Size(75, 23); this.OK_button.TabIndex = 1; this.OK_button.Text = "确定"; this.OK_button.UseVisualStyleBackColor = true; this.OK_button.Click += new System.EventHandler(this.OK_button_Click); // // Cancel_button // this.Cancel_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.Cancel_button.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.Cancel_button.Location = new System.Drawing.Point(129, 210); this.Cancel_button.Name = "Cancel_button"; this.Cancel_button.Size = new System.Drawing.Size(75, 23); this.Cancel_button.TabIndex = 2; this.Cancel_button.Text = "取消"; this.Cancel_button.UseVisualStyleBackColor = true; this.Cancel_button.Click += new System.EventHandler(this.Cancel_button_Click); // // DisplayedColumns // this.AcceptButton = this.OK_button; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.Cancel_button; this.ClientSize = new System.Drawing.Size(216, 245); this.Controls.Add(this.Cancel_button); this.Controls.Add(this.OK_button); this.Controls.Add(this.checkedListBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DisplayedColumns"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "列设置"; this.Load += new System.EventHandler(this.DisplayedColumns_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.CheckedListBox checkedListBox1; private System.Windows.Forms.Button OK_button; private System.Windows.Forms.Button Cancel_button; } }
39.112245
155
0.732846
[ "MIT" ]
HMBSbige/TCPingInfoView
TCPingInfoView/Forms/DisplayedColumns.Designer.cs
3,849
C#
using System.Windows.Controls; namespace Milvaneth.Overlay { /// <summary> /// Interaction logic for ListTabPage.xaml /// </summary> public partial class ListTabPage : Page { private ListingPresenterViewModel lpvm; public ListTabPage(ListingPresenterViewModel dataContext) { InitializeComponent(); this.ElementView.DataContext = dataContext; lpvm = dataContext; } } }
24.315789
65
0.632035
[ "MIT" ]
ShadyWhite/Milvaneth
Client/Milvaneth.Overlay/ListTabPage.xaml.cs
464
C#
using Microsoft.Extensions.Logging; using Newtonsoft.Json; using RpgMath; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adventure.Services { interface IPersistenceWriter { void AddSaveBlock(object blocker); Persistence Load(Func<Persistence.GameState> createNewWorld); void RemoveSaveBlock(object blocker); void Save(); } class PersistenceWriter : IPersistenceWriter, IDisposable { private Persistence persistence; private readonly ILogger<PersistenceWriter> logger; private JsonSerializer serializer; private HashSet<object> saveBlockers = new HashSet<object>(); public PersistenceWriter(ILogger<PersistenceWriter> logger) { this.logger = logger; serializer = new JsonSerializer() { Formatting = Formatting.Indented, }; } public void Dispose() { Save(); } public void Save() { if (persistence == null) { return; } if (saveBlockers.Count > 0) { logger.LogInformation($"Save is currently disabled. Skipping save. Reasons: {String.Concat(saveBlockers.Select(i => i?.ToString()))}"); return; } var outFile = GetSaveFile(); using var stream = new StreamWriter(File.Open(outFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)); serializer.Serialize(stream, persistence); logger.LogInformation($"Wrote save to '{outFile}'."); } public void AddSaveBlock(Object blocker) { saveBlockers.Add(blocker); } public void RemoveSaveBlock(Object blocker) { saveBlockers.Remove(blocker); } public Persistence Load(Func<Persistence.GameState> createNewWorld) { var outFile = GetSaveFile(); if (!File.Exists(outFile)) { logger.LogInformation($"Creating new save."); persistence = new Persistence() { Current = createNewWorld() }; } else { logger.LogInformation($"Loading save from '{outFile}'."); using var stream = new JsonTextReader(new StreamReader(File.Open(outFile, FileMode.Open, FileAccess.Read, FileShare.Read))); persistence = serializer.Deserialize<Persistence>(stream); } return persistence; } private String GetSaveFile() { var outDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Anomalous Adventure"); var outFile = Path.Combine(outDir, "save.json"); Directory.CreateDirectory(outDir); return outFile; } } }
29.990099
151
0.58237
[ "MIT" ]
AnomalousMedical/Adventure
Adventure/Services/PersistenceWriter.cs
3,031
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms.VisualStyles; using DG; namespace QoL_Mods.Data_Classes { public class FaceLockMoves { public Style StyleItem { get; set; } public Skill[] BasicSkills { get; set; } public SkillType[] Type { get; set; } public Skill[] CustomSkills { get; set; } public FaceLockMoves(Style item) { StyleItem = item; BasicSkills = new Skill[4]; Type = new SkillType[4]; CustomSkills = new Skill[4]; //Set initial moves for (int i = 0; i < Type.Length; i++) { BasicSkills[i] = new Skill("Elbow Butt", (int)BasicSkillEnum.PowerCompetitionWin_ElbowBat); Type[i] = SkillType.BasicMove; CustomSkills[i] = new Skill("Elbow Butt", (int)BasicSkillEnum.PowerCompetitionWin_ElbowBat); } } public override string ToString() { return this.StyleItem.Name; } public String SaveFaceLockData() { String data = ""; data += StyleItem.Name +";" + StyleItem.StyleType + "|"; foreach (Skill skill in BasicSkills) { data += skill.SkillName + ";" + skill.SkillID + "|"; } foreach (SkillType type in Type) { data += type + "|"; } foreach (Skill skill in CustomSkills) { data += skill.SkillName + ";" + skill.SkillID + "|"; } return data; } public void LoadFaceLockData(String data) { String[] information = data.Split('|'); StyleItem.Name = information[0].Split(';')[0]; StyleItem.StyleType = (FightStyleEnum)Enum.Parse(typeof(FightStyleEnum), information[0].Split(';')[1]); for (int i = 0; i < 4; i++) { BasicSkills[i].SkillName = information[i + 1].Split(';')[0]; BasicSkills[i].SkillID = int.Parse(information[i + 1].Split(';')[1]); Type[i] = (SkillType)Enum.Parse(typeof(SkillType), information[i + 5]); CustomSkills[i].SkillName = information[i + 9].Split(';')[0]; CustomSkills[i].SkillID = int.Parse(information[i + 9].Split(';')[1]); } } } }
33.053333
115
0.514724
[ "MIT" ]
timcanpy/ExtraGameOptions
QoL Mods/Private/Facelock/FaceLockMoves.cs
2,481
C#
using System.Collections; using System.Collections.Generic; using TMPro; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class WeaponGroupElement : MonoBehaviour { public TextMeshProUGUI Label; public Button Button; public ObservableBeginDragTrigger BeginDragTrigger; public ObservableDragTrigger DragTrigger; public ObservableEndDragTrigger EndDragTrigger; }
25.1875
55
0.816377
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ArnautS/Aetheria-Economy
Assets/Scripts/UI/Menu/WeaponGroupElement.cs
403
C#
using System.Linq; using NUnit.Framework; using QuestPDF.Examples.Engine; using QuestPDF.Fluent; using QuestPDF.Helpers; using QuestPDF.Infrastructure; using SkiaSharp; namespace QuestPDF.Examples { [TestFixture] public class ElementExamples { [Test] public void Placeholder() { RenderingTest .Create() .PageSize(200, 150) .Render(container => { container .Background("#FFF") .Padding(25) .Placeholder(); }); } [Test] public void Decoration() { RenderingTest .Create() .PageSize(300, 300) .Render(container => { container .Background("#FFF") .Padding(25) .Decoration(decoration => { decoration .Before() .Background(Colors.Grey.Medium) .Padding(10) .Text("Notes") .FontSize(16) .FontColor("#FFF"); decoration .Content() .Background(Colors.Grey.Lighten3) .Padding(10) .ExtendVertical() .Text(Helpers.Placeholders.LoremIpsum()); }); }); } [Test] public void Row() { RenderingTest .Create() .PageSize(740, 200) .Render(container => { container .Background("#FFF") .Padding(20) .Column(column => { column.Item() .PaddingBottom(10) .AlignCenter() .Text("This Row element is 700pt wide"); column.Item().Row(row => { row.ConstantItem(100) .Background(Colors.Grey.Lighten1) .Padding(10) .ExtendVertical() .Text("This column is 100 pt wide"); row.RelativeItem() .Background(Colors.Grey.Lighten2) .Padding(10) .Text("This column takes 1/3 of the available space (200pt)"); row.RelativeItem(2) .Background(Colors.Grey.Lighten3) .Padding(10) .Text("This column takes 2/3 of the available space (400pt)"); }); }); }); } [Test] public void RowSpacing() { RenderingTest .Create() .PageSize(740, 200) .Render(container => { container .Background("#FFF") .Padding(20) .Row(row => { row.Spacing(20); row.RelativeItem(2).Border(1).Background(Colors.Grey.Lighten1); row.RelativeItem(3).Border(1).Background(Colors.Grey.Lighten2); row.RelativeItem(4).Border(1).Background(Colors.Grey.Lighten3); }); }); } [Test] public void column() { RenderingTest .Create() .PageSize(500, 360) .Render(container => { container .Background("#FFF") .Padding(15) .Column(column => { column.Spacing(15); column.Item().Background(Colors.Grey.Medium).Height(50); column.Item().Background(Colors.Grey.Lighten1).Height(100); column.Item().Background(Colors.Grey.Lighten2).Height(150); }); }); } [Test] public void Debug() { RenderingTest .Create() .PageSize(210, 210) .Render(container => { container .Padding(25) .DebugArea("Grid example", Colors.Blue.Medium) .Grid(grid => { grid.Columns(3); grid.Spacing(5); foreach (var _ in Enumerable.Range(0, 8)) grid.Item().Height(50).Placeholder(); }); }); } [Test] public void ElementEnd() { RenderingTest .Create() .PageSize(300, 200) .Render(container => { var text = ""; container .Padding(10) .Element(x => { if (string.IsNullOrWhiteSpace(text)) x.Height(10).Width(50).Background("#DDD"); else x.Text(text); }); }); } [Test] public void GridExample() { RenderingTest .Create() .PageSize(400, 230) .Render(container => { var textStyle = TextStyle.Default.Size(14); container .Padding(15) .AlignRight() .Grid(grid => { grid.VerticalSpacing(10); grid.HorizontalSpacing(10); grid.AlignCenter(); grid.Columns(10); // 12 by default grid.Item(6).Background(Colors.Blue.Lighten1).Height(50); grid.Item(4).Background(Colors.Blue.Lighten3).Height(50); grid.Item(2).Background(Colors.Teal.Lighten1).Height(70); grid.Item(3).Background(Colors.Teal.Lighten2).Height(70); grid.Item(5).Background(Colors.Teal.Lighten3).Height(70); grid.Item(2).Background(Colors.Green.Lighten1).Height(50); grid.Item(2).Background(Colors.Green.Lighten2).Height(50); grid.Item(2).Background(Colors.Green.Lighten3).Height(50); }); }); } [Test] public void Canvas() { RenderingTest .Create() .PageSize(300, 200) .Render(container => { container .Background("#FFF") .Padding(25) .Canvas((canvas, size) => { using var paint = new SKPaint { Color = SKColors.Red, StrokeWidth = 10, IsStroke = true }; // move origin to the center of the available space canvas.Translate(size.Width / 2, size.Height / 2); // draw a circle canvas.DrawCircle(0, 0, 50, paint); }); }); } [Test] public void LayersExample() { RenderingTest .Create() .PageSize(400, 250) .Render(container => { container .Padding(25) .Layers(layers => { // layer below main content layers .Layer() .Height(100) .Width(100) .Background(Colors.Grey.Lighten3); layers .PrimaryLayer() .Padding(25) .Column(column => { column.Spacing(5); foreach (var _ in Enumerable.Range(0, 7)) column.Item().Text(Placeholders.Sentence()); }); // layer above the main content layers .Layer() .AlignCenter() .AlignMiddle() .Text("Watermark") .FontSize(48) .Bold() .FontColor(Colors.Green.Lighten3); layers .Layer() .AlignBottom() .Text(text => text.CurrentPageNumber().FontSize(16).FontColor(Colors.Green.Medium)); }); }); } // [Test] // public void EnsureSpace() // { // RenderingTest // .Create() // .PageSize(300, 400) // .Render(container => // { // container // .Padding(50) // .Page(page => // { // page.Header().PageNumber("Page {pdf:currentPage}"); // // page.Content().Height(300).column(content => // { // content.Item().Height(200).Background(Colors.Grey.Lighten2); // // content.Item().EnsureSpace(100).column(column => // { // column.Spacing(10); // // foreach (var _ in Enumerable.Range(0, 4)) // column.Item().Height(50).Background(Colors.Green.Lighten1); // }); // }); // }); // }); // } [Test] public void RandomColorMatrix() { RenderingTest .Create() .PageSize(300, 300) .Render(container => { container .Padding(25) .Grid(grid => { grid.Columns(5); Enumerable .Range(0, 25) .Select(x => Placeholders.BackgroundColor()) .ToList() .ForEach(x => grid.Item().Height(50).Background(x)); }); }); } [Test] public void DefinedColors() { var colors = new[] { Colors.Green.Darken4, Colors.Green.Darken3, Colors.Green.Darken2, Colors.Green.Darken1, Colors.Green.Medium, Colors.Green.Lighten1, Colors.Green.Lighten2, Colors.Green.Lighten3, Colors.Green.Lighten4, Colors.Green.Lighten5, Colors.Green.Accent1, Colors.Green.Accent2, Colors.Green.Accent3, Colors.Green.Accent4, }; RenderingTest .Create() .PageSize(450, 150) .Render(container => { container .Padding(25) .Height(100) .Row(row => { foreach (var color in colors) row.RelativeItem().Background(color); }); }); } [Test] public void DefinedFonts() { var fonts = new[] { Fonts.Calibri, Fonts.Candara, Fonts.Arial, Fonts.TimesNewRoman, Fonts.Consolas, Fonts.Tahoma, Fonts.Impact, Fonts.Trebuchet, Fonts.ComicSans }; RenderingTest .Create() .PageSize(500, 175) .Render(container => { container .Padding(25) .Grid(grid => { grid.Columns(3); foreach (var font in fonts) { grid.Item() .Border(1) .BorderColor(Colors.Grey.Medium) .Padding(10) .Text(font) .FontFamily(font) .FontSize(16); } }); }); } [Test] public void Layers() { RenderingTest .Create() .PageSize(300, 300) .Render(container => { container .Background("#FFF") .Padding(25) .Layers(layers => { layers.Layer().Text("Something else"); layers.PrimaryLayer().Column(column => { column.Item().PaddingTop(20).Text("Text 1"); column.Item().PaddingTop(40).Text("Text 2"); }); layers.Layer().Canvas((canvas, size) => { using var paint = new SKPaint { Color = SKColors.Red, StrokeWidth = 5 }; canvas.Translate(size.Width / 2, size.Height / 2); canvas.DrawCircle(0, 0, 50, paint); }); layers.Layer().Background("#8F00").Extend(); layers.Layer().PaddingTop(40).Text("It works!").FontSize(24); }); }); } [Test] public void Box() { RenderingTest .Create() .PageSize(300, 150) .Render(container => { container .Background("#FFF") .Padding(15) .Border(4) .BorderColor(Colors.Blue.Medium) //.MinimalBox() .Background(Colors.Grey.Lighten2) .Padding(15) .Text("Test of the \n box element").FontSize(20); }); } [Test] public void Scale() { RenderingTest .Create() .PageSize(300, 175) .Render(container => { container .Background(Colors.White) .Padding(10) .Decoration(decoration => { var headerFontStyle = TextStyle .Default .Size(20) .Color(Colors.Blue.Darken2) .SemiBold(); decoration .Before() .PaddingBottom(10) .Text("Example: scale component") .Style(headerFontStyle); decoration .Content() .Column(column => { var scales = new[] { 0.8f, 0.9f, 1.1f, 1.2f }; foreach (var scale in scales) { var fontColor = scale <= 1f ? Colors.Red.Lighten4 : Colors.Green.Lighten4; var fontStyle = TextStyle.Default.Size(16); column .Item() .Border(1) .Background(fontColor) .Scale(scale) .Padding(5) .Text($"Content with {scale} scale.") .Style(fontStyle); } }); }); }); } [Test] public void Translate() { RenderingTest .Create() .PageSize(300, 200) .Render(container => { container .Background("#FFF") .MinimalBox() .Padding(25) .Background(Colors.Green.Lighten3) .TranslateX(15) .TranslateY(15) .Border(2) .BorderColor(Colors.Green.Darken1) .Padding(50) .Text("Moved text") .FontSize(25); }); } [Test] public void ConstrainedRotate() { RenderingTest .Create() .PageSize(650, 450) .Render(container => { container .Padding(20) .Grid(grid => { grid.Columns(2); grid.Spacing(10); foreach (var turns in Enumerable.Range(0, 4)) { grid.Item() .Width(300) .Height(200) .Background(Colors.Grey.Lighten2) .Padding(10) .Element(element => { foreach (var x in Enumerable.Range(0, turns)) element = element.RotateRight(); return element; }) .MinimalBox() .Background(Colors.White) .Padding(10) .Text($"Rotated {turns * 90}°") .FontSize(16); } }); }); } [Test] public void FreeRotate() { RenderingTest .Create() .PageSize(300, 300) .Render(container => { container .Padding(25) .Background(Colors.Grey.Lighten2) .AlignCenter() .AlignMiddle() .Background(Colors.White) .Rotate(30) .Width(100) .Height(100) .Background(Colors.Blue.Medium); }); } [Test] public void FreeRotateCenter() { RenderingTest .Create() .PageSize(300, 300) .Render(container => { container .Padding(25) .Background(Colors.Grey.Lighten2) .AlignCenter() .AlignMiddle() .Background(Colors.White) .TranslateX(50) .TranslateY(50) .Rotate(30) .TranslateX(-50) .TranslateY(-50) .Width(100) .Height(100) .Background(Colors.Blue.Medium); }); } [Test] public void Flip() { RenderingTest .Create() .PageSize(350, 350) .Render(container => { container .Padding(20) .Grid(grid => { grid.Columns(2); grid.Spacing(10); foreach (var turns in Enumerable.Range(0, 4)) { grid.Item() .Width(150) .Height(150) .Background(Colors.Grey.Lighten3) .Padding(10) .Element(element => { if (turns == 1 || turns == 2) element = element.FlipHorizontal(); if (turns == 2 || turns == 3) element = element.FlipVertical(); return element; }) .MinimalBox() .Background(Colors.White) .Padding(10) .Text($"Flipped {turns}") .FontSize(16); } }); }); } [Test] public void RotateInTable() { RenderingTest .Create() .PageSize(200, 200) .Render(container => { container .Padding(10) .Border(2) .Row(row => { row.ConstantItem(25) .Border(1) .RotateLeft() .AlignCenter() .AlignMiddle() .Text("Sample text"); row.RelativeItem().Border(1).Padding(5).Text(Placeholders.Paragraph()); }); }); } [Test] public void Unconstrained() { RenderingTest .Create() .PageSize(400, 350) .Render(container => { container .Padding(25) .PaddingLeft(50) .Column(column => { column.Item().Width(300).Height(150).Background(Colors.Blue.Lighten4); column .Item() // creates an infinite space for its child .Unconstrained() // moves the child up and left .TranslateX(-50) .TranslateY(-50) // limits the space for the child .Width(100) .Height(100) .Background(Colors.Blue.Darken1); column.Item().Width(300).Height(150).Background(Colors.Blue.Lighten3); }); }); } [Test] public void ComplexLayout() { RenderingTest .Create() .PageSize(500, 225) .Render(container => { container .Padding(25) .Column(column => { column.Item().Row(row => { row.RelativeItem().LabelCell("Label 1"); row.RelativeItem(3).Grid(grid => { grid.Columns(3); grid.Item(2).LabelCell("Label 2"); grid.Item().LabelCell("Label 3"); grid.Item(2).ValueCell().Text("Value 2"); grid.Item().ValueCell().Text("Value 3"); }); }); column.Item().Row(row => { row.RelativeItem().ValueCell().Text("Value 1"); row.RelativeItem(3).Grid(grid => { grid.Columns(3); grid.Item().LabelCell("Label 4"); grid.Item(2).LabelCell("Label 5"); grid.Item().ValueCell().Text("Value 4"); grid.Item(2).ValueCell().Text("Value 5"); }); }); column.Item().Row(row => { row.RelativeItem().LabelCell("Label 6"); row.RelativeItem().ValueCell().Text("Value 6"); }); }); }); } [Test] public void DomainSpecificLanguage() { RenderingTest .Create() .PageSize(600, 310) .Render(container => { container .Padding(25) .Grid(grid => { grid.Columns(10); for(var i=1; i<=4; i++) { grid.Item(2).LabelCell(Placeholders.Label()); grid.Item(3).ValueCell().Image(Placeholders.Image(200, 150)); } }); }); } } }
36.179245
116
0.286832
[ "MIT" ]
Bebo-Maker/QuestPDF
QuestPDF.Examples/ElementExamples.cs
30,681
C#
using System; namespace KdSoft { /// <summary> /// Exposes a property to be used for identity purposes. /// </summary> /// <typeparam name="TKey">Type of Id property.</typeparam> public interface IIdentifiable<TKey> where TKey : IEquatable<TKey> { /// <summary>Identifier.</summary> TKey Id { get; } } }
21.866667
68
0.64939
[ "MIT" ]
kwaclaw/KdSoft.General
KdSoft.Shared/IIdentifiable.cs
330
C#
using UnityEngine; using System.Collections; public class PauseTime : MonoBehaviour { public bool paused; int rewindcounter; // Use this for initialization void Start () { paused = false; } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.R)) { //Pause (); } if (Input.GetKey(KeyCode.E)) { if (rewindcounter == 10) { SpeedUp(); } rewindcounter++; Normal(); //Time.timeScale = 1; } if (Input.GetKeyUp(KeyCode.E)) { rewindcounter = 0; Pause(); } if (Time.timeScale == 0.2f && gameObject.GetComponentInChildren<Animator>().GetCurrentAnimatorStateInfo(0).IsName("player_dead")) { Pause(); } } public void Pause (){ paused = !paused; if (paused) { Time.timeScale = 0; } else if(!paused) { Time.timeScale = 1; } } public void SlowDown(){ Time.timeScale = 0.2f; } public void Normal(){ Time.timeScale = 1; } public void SpeedUp(){ //Time.timeScale = 2; } }
18.970588
137
0.473643
[ "MIT" ]
marcosdanix/chrono-squad
Chrono Squad/Assets/Scripts/PauseTime.cs
1,292
C#
#region using System; using System.IO; #endregion namespace LCLog { /// <summary> /// Worlds most basic logger for LegendaryClient /// </summary> public class WriteToLog { /// <summary> /// Where to put the log file /// </summary> public static string ExecutingDirectory; /// <summary> /// What is the Log file name /// </summary> public static string LogfileName; /// <summary> /// Has the disconnected from internet message been sent? /// Resend the message if it hasn't /// </summary> private static bool Disconnected = false; /// <summary> /// Do the log /// </summary> /// <param name="lines"></param> /// <param name="type"></param> public static void Log(String lines, String type = "LOG") { if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { Disconnected = false; using ( FileStream stream = File.Open(Path.Combine(ExecutingDirectory, "Logs", LogfileName), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) using (var file = new StreamWriter(stream)) file.WriteLine("({0} {1}) [{2}]: {3}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), type.ToUpper(), lines); } else if (!Disconnected) { Disconnected = true; using ( FileStream stream = File.Open(Path.Combine(ExecutingDirectory, "Logs", LogfileName), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) using (var file = new StreamWriter(stream)) file.WriteLine("({0} {1}) [{2}]: {3}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), "NETWORK", "You have disconnected from the internet. Logs have stopped. Please reconnect!"); } } public static void CreateLogFile() { //Generate A Unique file to use as a log file if (!Directory.Exists(Path.Combine(ExecutingDirectory, "Logs"))) Directory.CreateDirectory(Path.Combine(ExecutingDirectory, "Logs")); LogfileName = string.Format("{0}T{1} {2}", DateTime.Now.ToShortDateString().Replace("/", "_"), DateTime.Now.ToShortTimeString().Replace(" ", "").Replace(":", "-"), "_" + LogfileName); FileStream file = File.Create(Path.Combine(ExecutingDirectory, "Logs", LogfileName)); file.Close(); } } }
38.887324
150
0.543281
[ "BSD-2-Clause" ]
nongnoobjung/Legendary-Garena
LCLog/WriteToLog.cs
2,763
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Frs.V2.Model { /// <summary> /// Request Object /// </summary> public class BatchDeleteFacesRequest { /// <summary> /// 人脸库名称。 /// </summary> [SDKProperty("face_set_name", IsPath = true)] [JsonProperty("face_set_name", NullValueHandling = NullValueHandling.Ignore)] public string FaceSetName { get; set; } /// <summary> /// /// </summary> [SDKProperty("body", IsBody = true)] [JsonProperty("body", NullValueHandling = NullValueHandling.Ignore)] public DeleteFacesBatchReq Body { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class BatchDeleteFacesRequest {\n"); sb.Append(" faceSetName: ").Append(FaceSetName).Append("\n"); sb.Append(" body: ").Append(Body).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as BatchDeleteFacesRequest); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(BatchDeleteFacesRequest input) { if (input == null) return false; return ( this.FaceSetName == input.FaceSetName || (this.FaceSetName != null && this.FaceSetName.Equals(input.FaceSetName)) ) && ( this.Body == input.Body || (this.Body != null && this.Body.Equals(input.Body)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.FaceSetName != null) hashCode = hashCode * 59 + this.FaceSetName.GetHashCode(); if (this.Body != null) hashCode = hashCode * 59 + this.Body.GetHashCode(); return hashCode; } } } }
29.130435
85
0.505597
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Frs/V2/Model/BatchDeleteFacesRequest.cs
2,692
C#
using System; namespace Bender.Extensions { public static class NumericExtensions { public static bool IsNonNumeric(this float value) { return float.IsNaN(value) || float.IsInfinity(value) || float.IsNegativeInfinity(value) || float.IsPositiveInfinity(value); } public static bool IsNonNumeric(this double value) { return double.IsNaN(value) || double.IsInfinity(value) || double.IsNegativeInfinity(value) || double.IsPositiveInfinity(value); } } }
31
89
0.599321
[ "MIT" ]
mikeobrien/Bender
src/Bender/Extensions/NumericExtensions.cs
591
C#
namespace SlackNet.Events { /// <summary> /// Sent to all connections for a team when an integration "bot" is updated. /// </summary> public class BotChanged : Event { public BotInfo Bot { get; set; } } }
23.6
80
0.601695
[ "MIT" ]
Cereal-Killa/SlackNet
SlackNet/Events/BotChanged.cs
236
C#
using System.Collections.Generic; namespace SimplyBlog.Website.Models.Response { public class ListResponse<T> : Response { public List<T> Data { get; set; } = new List<T>(); public int MaxPages { get; set; } public int CurrentPage { get; set; } } }
23.916667
58
0.623693
[ "MIT" ]
LadyHail/Simply-Blog
Server/SimplyBlog.Website/Models/Response/ListResponse.cs
289
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Informacje ogólne o zestawie zależą od poniższego // zestawu atrybutów. Zmień wartości tych atrybutów, aby zmodyfikować informacje // związane z zestawem. [assembly: AssemblyTitle("internet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("internet")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Ustawienie dla atrybutu ComVisible wartości false powoduje, że typy w tym zestawie stają się niewidoczne // dla składników COM. Jeśli musisz uzyskiwać dostęp do typu w tym zestawie // z modelu COM, ustaw dla atrybutu ComVisible tego typu wartość true. [assembly: ComVisible(false)] // Poniższy identyfikator GUID odpowiada atrybutowi ID biblioteki typów, jeśli ten projekt jest uwidaczniany w modelu COM [assembly: Guid("5c1efc08-9caa-4e54-ad57-6412acced117")] // Informacje o wersji zestawu obejmują następujące cztery wartości: // // Wersja główna // Wersja pomocnicza // Numer kompilacji // Poprawka // // Możesz określić wszystkie te wartości lub użyć wartości domyślnych numerów poprawki i kompilacji, // stosując znak „*”, jak pokazano poniżej: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.638889
121
0.765943
[ "Apache-2.0" ]
BrOlaf45/csharp-projects
repos/Repos/internet/internet/Properties/AssemblyInfo.cs
1,475
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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.IO; using System.Linq; using System.Threading; using NUnit.Framework; using QuantConnect.Api; using QuantConnect.API; using QuantConnect.Brokerages; using QuantConnect.Configuration; using RestSharp.Extensions.MonoHttp; namespace QuantConnect.Tests.API { [TestFixture, Ignore("These tests require configured and active accounts to Tradier, FXCM and Oanda")] class RestApiTests { private int _testAccount = 1; private string _testToken = "ec87b337ac970da4cbea648f24f1c851"; private string _dataFolder = Config.Get("data-folder"); private Api.Api _api; private const bool stopLiveAlgos = true; /// <summary> /// Run before every test /// </summary> [SetUp] public void Setup() { _api = new Api.Api(); _api.Initialize(_testAccount, _testToken, _dataFolder); } /// <summary> /// Test creating and deleting projects with the Api /// </summary> [Test] public void Projects_CanBeCreatedAndDeleted_Successfully() { var name = "Test Project " + DateTime.Now; //Test create a new project successfully var project = _api.CreateProject(name, Language.CSharp); Assert.IsTrue(project.Success); Assert.IsTrue(project.Projects.First().ProjectId > 0); Assert.IsTrue(project.Projects.First().Name == name); // Delete the project var deleteProject = _api.DeleteProject(project.Projects.First().ProjectId); Assert.IsTrue(deleteProject.Success); // Make sure the project is really deleted var projectList = _api.ListProjects(); Assert.IsFalse(projectList.Projects.Any(p => p.ProjectId == project.Projects.First().ProjectId)); } /// <summary> /// Test successfully authenticating with the API using valid credentials. /// </summary> [Test] public void ApiWillAuthenticate_ValidCredentials_Successfully() { var connection = new ApiConnection(_testAccount, _testToken); Assert.IsTrue(connection.Connected); } /// <summary> /// Test that the Api will reject invalid credentials /// </summary> [Test] public void ApiWillAuthenticate_InvalidCredentials_Unsuccessfully() { var connection = new ApiConnection(_testAccount, ""); Assert.IsFalse(connection.Connected); } /// <summary> /// Test updating the files associated with a project /// </summary> [Test] public void CRUD_ProjectFiles_Successfully() { var fakeFile = new ProjectFile { Name = "Hello.cs", Code = HttpUtility.HtmlEncode("Hello, world!") }; var realFile = new ProjectFile { Name = "main.cs", Code = HttpUtility.HtmlEncode(File.ReadAllText("../../../Algorithm.CSharp/BasicTemplateAlgorithm.cs")) }; var secondRealFile = new ProjectFile() { Name = "lol.cs", Code = HttpUtility.HtmlEncode(File.ReadAllText("../../../Algorithm.CSharp/BubbleAlgorithm.cs")) }; // Create a new project and make sure there are no files var project = _api.CreateProject("Test project - " + DateTime.Now, Language.CSharp); Assert.IsTrue(project.Success); Assert.IsTrue(project.Projects.First().ProjectId > 0); // Add random file var randomAdd = _api.AddProjectFile(project.Projects.First().ProjectId, fakeFile.Name, fakeFile.Code); Assert.IsTrue(randomAdd.Success); Assert.IsTrue(randomAdd.Files.First().Code == fakeFile.Code); Assert.IsTrue(randomAdd.Files.First().Name == fakeFile.Name); // Update names of file var updatedName = _api.UpdateProjectFileName(project.Projects.First().ProjectId, randomAdd.Files.First().Name, realFile.Name); Assert.IsTrue(updatedName.Success); // Replace content of file var updateContents = _api.UpdateProjectFileContent(project.Projects.First().ProjectId, realFile.Name, realFile.Code); Assert.IsTrue(updateContents.Success); // Read single file var readFile = _api.ReadProjectFile(project.Projects.First().ProjectId, realFile.Name); Assert.IsTrue(readFile.Success); Assert.IsTrue(readFile.Files.First().Code == realFile.Code); Assert.IsTrue(readFile.Files.First().Name == realFile.Name); // Add a second file var secondFile = _api.AddProjectFile(project.Projects.First().ProjectId, secondRealFile.Name, secondRealFile.Code); Assert.IsTrue(secondFile.Success); Assert.IsTrue(secondFile.Files.First().Code == secondRealFile.Code); Assert.IsTrue(secondFile.Files.First().Name == secondRealFile.Name); // Read multiple files var readFiles = _api.ReadProjectFiles(project.Projects.First().ProjectId); Assert.IsTrue(readFiles.Success); Assert.IsTrue(readFiles.Files.Count == 2); // Delete the second file var deleteFile = _api.DeleteProjectFile(project.Projects.First().ProjectId, secondRealFile.Name); Assert.IsTrue(deleteFile.Success); // Read files var readFilesAgain = _api.ReadProjectFiles(project.Projects.First().ProjectId); Assert.IsTrue(readFilesAgain.Success); Assert.IsTrue(readFilesAgain.Files.Count == 1); Assert.IsTrue(readFilesAgain.Files.First().Name == realFile.Name); // Delete the project var deleteProject = _api.DeleteProject(project.Projects.First().ProjectId); Assert.IsTrue(deleteProject.Success); } /// <summary> /// Test creating the settings object that provide the necessary parameters for each broker /// </summary> [Test] public void LiveAlgorithmSettings_CanBeCreated_Successfully() { string user = ""; string password = ""; BrokerageEnvironment environment = BrokerageEnvironment.Paper; string account = ""; // Oanda Custom Variables string accessToken = ""; var dateIssuedString = "20160920"; // Tradier Custom Variables string dateIssued = ""; string refreshToken = ""; string lifetime = ""; // Create and test settings for each brokerage foreach (BrokerageName brokerageName in Enum.GetValues(typeof(BrokerageName))) { BaseLiveAlgorithmSettings settings = null; switch (brokerageName) { case BrokerageName.Default: user = Config.Get("default-username"); password = Config.Get("default-password"); settings = new DefaultLiveAlgorithmSettings(user, password, environment, account); Assert.IsTrue(settings.Id == BrokerageName.Default.ToString()); break; case BrokerageName.FxcmBrokerage: user = Config.Get("fxcm-user-name"); password = Config.Get("fxcm-password"); settings = new FXCMLiveAlgorithmSettings(user, password, environment, account); Assert.IsTrue(settings.Id == BrokerageName.FxcmBrokerage.ToString()); break; case BrokerageName.InteractiveBrokersBrokerage: user = Config.Get("ib-user-name"); password = Config.Get("ib-password"); account = Config.Get("ib-account"); settings = new InteractiveBrokersLiveAlgorithmSettings(user, password, account); Assert.IsTrue(settings.Id == BrokerageName.InteractiveBrokersBrokerage.ToString()); break; case BrokerageName.OandaBrokerage: accessToken = Config.Get("oanda-access-token"); account = Config.Get("oanda-account-id"); settings = new OandaLiveAlgorithmSettings(accessToken, environment, account); Assert.IsTrue(settings.Id == BrokerageName.OandaBrokerage.ToString()); break; case BrokerageName.TradierBrokerage: dateIssued = Config.Get("tradier-issued-at"); refreshToken = Config.Get("tradier-refresh-token"); account = Config.Get("tradier-account-id"); settings = new TradierLiveAlgorithmSettings(refreshToken, dateIssued, refreshToken, account); break; default: throw new Exception("Settings have not been implemented for this brokerage: " + brokerageName.ToString()); } // Tests common to all brokerage configuration classes Assert.IsTrue(settings != null); Assert.IsTrue(settings.Password == password); Assert.IsTrue(settings.User == user); // tradier brokerage is always live, the rest are variable if (brokerageName != BrokerageName.TradierBrokerage) Assert.IsTrue(settings.Environment == environment); // Oanda specific settings if (brokerageName == BrokerageName.OandaBrokerage) { var oandaSetting = settings as OandaLiveAlgorithmSettings; Assert.IsTrue(oandaSetting.AccessToken == accessToken); } // Tradier specific settings if (brokerageName == BrokerageName.TradierBrokerage) { var tradierLiveAlogrithmSettings = settings as TradierLiveAlgorithmSettings; Assert.IsTrue(tradierLiveAlogrithmSettings.DateIssued == dateIssued); Assert.IsTrue(tradierLiveAlogrithmSettings.RefreshToken == refreshToken); Assert.IsTrue(settings.Environment == BrokerageEnvironment.Live); } // reset variables user = ""; password = ""; environment = BrokerageEnvironment.Paper; account = ""; } } /// <summary> /// Reading live algorithm tests /// - Get a list of live algorithms /// - Get logs for the first algorithm returned /// Will there always be a live algorithm for the test user? /// </summary> [Test] public void LiveAlgorithmsAndLiveLogs_CanBeRead_Successfully() { // Read all currently running algorithms var liveAlgorithms = _api.ListLiveAlgorithms(AlgorithmStatus.Running); Assert.IsTrue(liveAlgorithms.Success); // There has to be at least one running algorithm Assert.IsTrue(liveAlgorithms.Algorithms.Any()); // Read the logs of the first live algorithm var firstLiveAlgo = liveAlgorithms.Algorithms[0]; var liveLogs = _api.ReadLiveLogs(firstLiveAlgo.ProjectId, firstLiveAlgo.DeployId); Assert.IsTrue(liveLogs.Success); Assert.IsTrue(liveLogs.Logs.Any()); } /// <summary> /// Paper trading FXCM /// </summary> [Test] public void LiveForexAlgorithms_CanBeUsedWithFXCM_Successfully() { var user = Config.Get("fxcm-user-name"); var password = Config.Get("fxcm-password"); var account = Config.Get("fxcm-account-id"); var file = new ProjectFile { Name = "main.cs", Code = File.ReadAllText("../../../Algorithm.CSharp/BasicTemplateForexAlgorithm.cs") }; // Create a new project var project = _api.CreateProject("Test project - " + DateTime.Now, Language.CSharp); Assert.IsTrue(project.Success); // Add Project Files var addProjectFile = _api.AddProjectFile(project.Projects.First().ProjectId, file.Name, file.Code); Assert.IsTrue(addProjectFile.Success); // Create compile var compile = _api.CreateCompile(project.Projects.First().ProjectId); Assert.IsTrue(compile.Success); // Create default algorithm settings var settings = new FXCMLiveAlgorithmSettings(user, password, BrokerageEnvironment.Paper, account); // Wait for project to compile Thread.Sleep(10000); // Create live default algorithm var createLiveAlgorithm = _api.CreateLiveAlgorithm(project.Projects.First().ProjectId, compile.CompileId, "server512", settings); Assert.IsTrue(createLiveAlgorithm.Success); if (stopLiveAlgos) { // Liquidate live algorithm var liquidateLive = _api.LiquidateLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(liquidateLive.Success); // Stop live algorithm var stopLive = _api.StopLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(stopLive.Success); // Delete the project var deleteProject = _api.DeleteProject(project.Projects.First().ProjectId); Assert.IsTrue(deleteProject.Success); } } /// <summary> /// Live paper trading via IB. /// </summary> [Test] public void LiveEquityAlgorithms_CanBeUsedWithInteractiveBrokers_Successfully() { var user = Config.Get("ib-user-name"); var password = Config.Get("ib-password"); var account = Config.Get("ib-account"); var file = new ProjectFile { Name = "main.cs", Code = File.ReadAllText("../../../Algorithm.CSharp/BasicTemplateAlgorithm.cs") }; // Create a new project var project = _api.CreateProject("Test project - " + DateTime.Now, Language.CSharp); // Add Project Files var addProjectFile = _api.AddProjectFile(project.Projects.First().ProjectId, file.Name, file.Code); Assert.IsTrue(addProjectFile.Success); // Create compile var compile = _api.CreateCompile(project.Projects.First().ProjectId); Assert.IsTrue(compile.Success); // Create default algorithm settings var settings = new InteractiveBrokersLiveAlgorithmSettings(user, password, account); // Wait for project to compile Thread.Sleep(10000); // Create live default algorithm var createLiveAlgorithm = _api.CreateLiveAlgorithm(project.Projects.First().ProjectId, compile.CompileId, "server512", settings); Assert.IsTrue(createLiveAlgorithm.Success); if (stopLiveAlgos) { // Liquidate live algorithm var liquidateLive = _api.LiquidateLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(liquidateLive.Success); // Stop live algorithm var stopLive = _api.StopLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(stopLive.Success); // Delete the project var deleteProject = _api.DeleteProject(project.Projects.First().ProjectId); Assert.IsTrue(deleteProject.Success); } } /// <summary> /// Live paper trading via Oanda /// </summary> [Test] public void LiveForexAlgorithms_CanBeUsedWithOanda_Successfully() { var token = Config.Get("oanda-access-token"); var account = Config.Get("oanda-account-id"); var file = new ProjectFile { Name = "main.cs", Code = File.ReadAllText("../../../Algorithm.CSharp/BasicTemplateForexAlgorithm.cs") }; // Create a new project var project = _api.CreateProject("Test project - " + DateTime.Now, Language.CSharp); // Add Project Files var addProjectFile = _api.AddProjectFile(project.Projects.First().ProjectId, file.Name, file.Code); Assert.IsTrue(addProjectFile.Success); // Create compile var compile = _api.CreateCompile(project.Projects.First().ProjectId); Assert.IsTrue(compile.Success); // Create default algorithm settings var settings = new OandaLiveAlgorithmSettings(token, BrokerageEnvironment.Paper, account); // Wait for project to compile Thread.Sleep(10000); // Create live default algorithm var createLiveAlgorithm = _api.CreateLiveAlgorithm(project.Projects.First().ProjectId, compile.CompileId, "server512", settings); Assert.IsTrue(createLiveAlgorithm.Success); if (stopLiveAlgos) { // Liquidate live algorithm var liquidateLive = _api.LiquidateLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(liquidateLive.Success); // Stop live algorithm var stopLive = _api.StopLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(stopLive.Success); // Delete the project var deleteProject = _api.DeleteProject(project.Projects.First().ProjectId); Assert.IsTrue(deleteProject.Success); } } /// <summary> /// Live paper trading via Tradier /// </summary> [Test] public void LiveEquityAlgorithms_CanBeUsedWithTradier_Successfully() { var refreshToken = Config.Get("tradier-refresh-token"); var account = Config.Get("tradier-account-id"); var accessToken = Config.Get("tradier-access-token"); var dateIssued = Config.Get("tradier-issued-at"); var file = new ProjectFile { Name = "main.cs", Code = File.ReadAllText("../../../Algorithm.CSharp/BasicTemplateAlgorithm.cs") }; // Create a new project var project = _api.CreateProject("Test project - " + DateTime.Now, Language.CSharp); // Add Project Files var addProjectFile = _api.AddProjectFile(project.Projects.First().ProjectId, file.Name, file.Code); Assert.IsTrue(addProjectFile.Success); var readProject = _api.ReadProject(project.Projects.First().ProjectId); Assert.IsTrue(readProject.Success); // Create compile var compile = _api.CreateCompile(project.Projects.First().ProjectId); Assert.IsTrue(compile.Success); // Create default algorithm settings var settings = new TradierLiveAlgorithmSettings(accessToken, dateIssued, refreshToken, account); // Wait for project to compile Thread.Sleep(10000); // Create live default algorithm var createLiveAlgorithm = _api.CreateLiveAlgorithm(project.Projects.First().ProjectId, compile.CompileId, "server512", settings); Assert.IsTrue(createLiveAlgorithm.Success); if (stopLiveAlgos) { // Liquidate live algorithm var liquidateLive = _api.LiquidateLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(liquidateLive.Success); // Stop live algorithm var stopLive = _api.StopLiveAlgorithm(project.Projects.First().ProjectId); Assert.IsTrue(stopLive.Success); // Delete the project var deleteProject = _api.DeleteProject(project.Projects.First().ProjectId); Assert.IsTrue(deleteProject.Success); } } /// <summary> /// Test getting links to forex data for FXCM /// </summary> [Test] public void FXCMDataLinks_CanBeRetrieved_Successfully() { var minuteDataLink = _api.ReadDataLink(new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD"), Resolution.Minute, new DateTime(2013, 10, 07)); var dailyDataLink = _api.ReadDataLink(new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD"), Resolution.Daily, new DateTime(2013, 10, 07)); Assert.IsTrue(minuteDataLink.Success); Assert.IsTrue(dailyDataLink.Success); } /// <summary> /// Test getting links to forex data for Oanda /// </summary> [Test] public void OandaDataLinks_CanBeRetrieved_Successfully() { var minuteDataLink = _api.ReadDataLink(new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.Oanda), "EURUSD"), Resolution.Minute, new DateTime(2013, 10, 07)); var dailyDataLink = _api.ReadDataLink(new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.Oanda), "EURUSD"), Resolution.Daily, new DateTime(2013, 10, 07)); Assert.IsTrue(minuteDataLink.Success); Assert.IsTrue(dailyDataLink.Success); } /// <summary> /// Test downloading data that does not come with the repo (Oanda) /// </summary> [Test] public void BacktestingData_CanBeDownloadedAndSaved_Successfully() { var minutePath = Path.Combine(_dataFolder, "forex/oanda/minute/eurusd/20131011_quote.zip"); var dailyPath = Path.Combine(_dataFolder, "forex/oanda/daily/eurusd.zip"); if (File.Exists(dailyPath)) File.Delete(dailyPath); if (File.Exists(minutePath)) File.Delete(minutePath); var downloadedMinuteData = _api.DownloadData(new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.Oanda), "EURUSD"), Resolution.Minute, new DateTime(2013, 10, 11)); var downloadedDailyData = _api.DownloadData(new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.Oanda), "EURUSD"), Resolution.Daily, new DateTime(2013, 10, 07)); Assert.IsTrue(downloadedMinuteData); Assert.IsTrue(downloadedDailyData); Assert.IsTrue(File.Exists(dailyPath)); Assert.IsTrue(File.Exists(minutePath)); } /// <summary> /// Test downloading non existent data /// </summary> [Test] public void NonExistantData_WillBeDownloaded_Unsuccessfully() { var nonExistentData = _api.DownloadData(new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.Oanda), "EURUSD"), Resolution.Minute, new DateTime(1989, 10, 11)); Assert.IsFalse(nonExistentData); } /// <summary> /// Test creating, compiling and backtesting a C# project via the Api /// </summary> [Test] public void CSharpProject_CreatedCompiledAndBacktested_Successully() { var language = Language.CSharp; var code = File.ReadAllText("../../../Algorithm.CSharp/BasicTemplateAlgorithm.cs"); var algorithmName = "main.cs"; var projectName = DateTime.UtcNow.ToString("u") + " Test " + _testAccount + " Lang " + language; Perform_CreateCompileBactest_Tests(projectName, language, algorithmName, code); } /// <summary> /// Test creating, compiling and backtesting a F# project via the Api /// </summary> [Test] public void FSharpProject_CreatedCompiledAndBacktested_Successully() { var language = Language.FSharp; var code = File.ReadAllText("../../../Algorithm.FSharp/BasicTemplateAlgorithm.fs"); var algorithmName = "main.fs"; var projectName = DateTime.UtcNow.ToString("u") + " Test " + _testAccount + " Lang " + language; Perform_CreateCompileBactest_Tests(projectName, language, algorithmName, code); } /// <summary> /// Test creating, compiling and bactesting a Python project via the Api /// </summary> [Test] public void PythonProject_CreatedCompiledAndBacktested_Successully() { var language = Language.Python; var code = File.ReadAllText("../../../Algorithm.Python/BasicTemplateAlgorithm.py"); var algorithmName = "main.py"; var projectName = DateTime.UtcNow.ToString("u") + " Test " + _testAccount + " Lang " + language; Perform_CreateCompileBactest_Tests(projectName, language, algorithmName, code); } private void Perform_CreateCompileBactest_Tests(string projectName, Language language, string algorithmName, string code) { //Test create a new project successfully var project = _api.CreateProject(projectName, language); Assert.IsTrue(project.Success); Assert.IsTrue(project.Projects.First().ProjectId > 0); Assert.IsTrue(project.Projects.First().Name == projectName); // Make sure the project just created is now present var projects = _api.ListProjects(); Assert.IsTrue(projects.Success); Assert.IsTrue(projects.Projects.Any(p => p.ProjectId == project.Projects.First().ProjectId)); // Test read back the project we just created var readProject = _api.ReadProject(project.Projects.First().ProjectId); Assert.IsTrue(readProject.Success); Assert.IsTrue(readProject.Projects.First().Name == projectName); // Test set a project file for the project var file = new ProjectFile { Name = algorithmName, Code = code }; var addProjectFile = _api.AddProjectFile(project.Projects.First().ProjectId, file.Name, file.Code); Assert.IsTrue(addProjectFile.Success); // Download the project again to validate its got the new file var verifyRead = _api.ReadProject(project.Projects.First().ProjectId); Assert.IsTrue(verifyRead.Success); // Compile the project we've created var compileCreate = _api.CreateCompile(project.Projects.First().ProjectId); Assert.IsTrue(compileCreate.Success); Assert.IsTrue(compileCreate.State == CompileState.InQueue); // Read out the compile var compileSuccess = WaitForCompilerResponse(project.Projects.First().ProjectId, compileCreate.CompileId); Assert.IsTrue(compileSuccess.Success); Assert.IsTrue(compileSuccess.State == CompileState.BuildSuccess); // Update the file, create a build error, test we get build error file.Code += "[Jibberish at end of the file to cause a build error]"; _api.UpdateProjectFileContent(project.Projects.First().ProjectId, file.Name, file.Code); var compileError = _api.CreateCompile(project.Projects.First().ProjectId); compileError = WaitForCompilerResponse(project.Projects.First().ProjectId, compileError.CompileId); Assert.IsTrue(compileError.Success); // Successfully processed rest request. Assert.IsTrue(compileError.State == CompileState.BuildError); //Resulting in build fail. // Using our successful compile; launch a backtest! var backtestName = DateTime.Now.ToString("u") + " API Backtest"; var backtest = _api.CreateBacktest(project.Projects.First().ProjectId, compileSuccess.CompileId, backtestName); Assert.IsTrue(backtest.Success); // Now read the backtest and wait for it to complete var backtestRead = WaitForBacktestCompletion(project.Projects.First().ProjectId, backtest.BacktestId); Assert.IsTrue(backtestRead.Success); Assert.IsTrue(backtestRead.Progress == 1); Assert.IsTrue(backtestRead.Name == backtestName); Assert.IsTrue(backtestRead.Result.Statistics["Total Trades"] == "1"); // Verify we have the backtest in our project var listBacktests = _api.ListBacktests(project.Projects.First().ProjectId); Assert.IsTrue(listBacktests.Success); Assert.IsTrue(listBacktests.Backtests.Count >= 1); Assert.IsTrue(listBacktests.Backtests[0].Name == backtestName); // Update the backtest name and test its been updated backtestName += "-Amendment"; var renameBacktest = _api.UpdateBacktest(project.Projects.First().ProjectId, backtest.BacktestId, backtestName); Assert.IsTrue(renameBacktest.Success); backtestRead = _api.ReadBacktest(project.Projects.First().ProjectId, backtest.BacktestId); Assert.IsTrue(backtestRead.Name == backtestName); //Update the note and make sure its been updated: var newNote = DateTime.Now.ToString("u"); var noteBacktest = _api.UpdateBacktest(project.Projects.First().ProjectId, backtest.BacktestId, note: newNote); Assert.IsTrue(noteBacktest.Success); backtestRead = _api.ReadBacktest(project.Projects.First().ProjectId, backtest.BacktestId); Assert.IsTrue(backtestRead.Note == newNote); // Delete the backtest we just created var deleteBacktest = _api.DeleteBacktest(project.Projects.First().ProjectId, backtest.BacktestId); Assert.IsTrue(deleteBacktest.Success); // Test delete the project we just created var deleteProject = _api.DeleteProject(project.Projects.First().ProjectId); Assert.IsTrue(deleteProject.Success); } /// <summary> /// Wait for the compiler to respond to a specified compile request /// </summary> /// <param name="projectId">Id of the project</param> /// <param name="compileId">Id of the compilation of the project</param> /// <returns></returns> private Compile WaitForCompilerResponse(int projectId, string compileId) { var compile = new Compile(); var finish = DateTime.Now.AddSeconds(60); while (DateTime.Now < finish) { compile = _api.ReadCompile(projectId, compileId); if (compile.State == CompileState.BuildSuccess) break; Thread.Sleep(1000); } return compile; } /// <summary> /// Wait for the backtest to complete /// </summary> /// <param name="projectId">Project id to scan</param> /// <param name="backtestId">Backtest id previously started</param> /// <returns>Completed backtest object</returns> private Backtest WaitForBacktestCompletion(int projectId, string backtestId) { var result = new Backtest(); var finish = DateTime.Now.AddSeconds(60); while (DateTime.Now < finish) { result = _api.ReadBacktest(projectId, backtestId); if (result.Progress == 1) break; if (!result.Success) break; Thread.Sleep(1000); } return result; } } }
44.258575
141
0.591839
[ "Apache-2.0" ]
WhiteSourceE/LeanUnsafe
Tests/API/ApiTests.cs
33,550
C#
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("15.Hexadecimal to Decimal Number")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("15.Hexadecimal to Decimal Number")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("2f1448c1-bc51-4393-a7c8-bfe9f7ed59b0")] // 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("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.837838
84
0.746695
[ "MIT" ]
milkokochev/Telerik
C#1/HomeWorks/06. Loops/Hexadecimal to Decimal Number/Properties/AssemblyInfo.cs
1,440
C#
// Copyright 2021 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Ads.GoogleAds.V8.Services.Snippets { using Google.Ads.GoogleAds.V8.Enums; using Google.Ads.GoogleAds.V8.Services; using System.Threading.Tasks; public sealed partial class GeneratedConversionValueRuleServiceClientStandaloneSnippets { /// <summary>Snippet for MutateConversionValueRulesAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task MutateConversionValueRulesRequestObjectAsync() { // Create client ConversionValueRuleServiceClient conversionValueRuleServiceClient = await ConversionValueRuleServiceClient.CreateAsync(); // Initialize request argument(s) MutateConversionValueRulesRequest request = new MutateConversionValueRulesRequest { CustomerId = "", Operations = { new ConversionValueRuleOperation(), }, ValidateOnly = false, ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.Unspecified, PartialFailure = false, }; // Make the request MutateConversionValueRulesResponse response = await conversionValueRuleServiceClient.MutateConversionValueRulesAsync(request); } } }
41.411765
138
0.682292
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/ads/googleads/v8/googleads-csharp/Google.Ads.GoogleAds.V8.Services.StandaloneSnippets/ConversionValueRuleServiceClient.MutateConversionValueRulesRequestObjectAsyncSnippet.g.cs
2,112
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.System; using Windows.UI.Core; namespace Template10.Services.KeyboardService { // DOCS: https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-KeyboardService public class KeyboardEventArgs : EventArgs { public bool Handled { get; set; } = false; public bool AltKey { get; set; } public bool ControlKey { get; set; } public bool ShiftKey { get; set; } public VirtualKey VirtualKey { get; set; } public AcceleratorKeyEventArgs EventArgs { get; set; } public char? Character { get; set; } public bool WindowsKey { get; internal set; } public bool OnlyWindows => WindowsKey & !AltKey & !ControlKey & !ShiftKey; public bool OnlyAlt => !WindowsKey & AltKey & !ControlKey & !ShiftKey; public bool OnlyControl => !WindowsKey & !AltKey & ControlKey & !ShiftKey; public bool OnlyShift => !WindowsKey & !AltKey & !ControlKey & ShiftKey; public bool Combo => new[] { AltKey, ControlKey, ShiftKey }.Any(x => x) & Character.HasValue; public override string ToString() { return $"KeyboardEventArgs = Handled {Handled}, AltKey {AltKey}, ControlKey {ControlKey}, ShiftKey {ShiftKey}, VirtualKey {VirtualKey}, Character {Character}, WindowsKey {WindowsKey}, OnlyWindows {OnlyWindows}, OnlyAlt {OnlyAlt}, OnlyControl {OnlyControl}, OnlyShift {OnlyShift}"; } } }
43.942857
292
0.672302
[ "Apache-2.0" ]
ArtjomP/Template10
Template10 (Library)/Services/KeyboardService/KeyboardEventArgs.cs
1,540
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace BEDA.CMB.Contracts.Responses { /// <summary> /// 23.11.临时额度取消响应主体 /// </summary> [XmlRoot("CMBSDKPGK")] public class RS23_11 : CMBBase<RSINFO>, IResponse { /// <summary> /// NTCPRAUC /// </summary> /// <returns></returns> public override string GetFUNNAM() => "NTCPRAUC"; /// <summary> /// 23.11.临时额度取消响应内容 /// </summary> public NTOPRRTNZ NTOPRRTNZ { get; set; } } }
23.392857
57
0.603053
[ "MIT" ]
fdstar/BankEnterpriseDirectAttach
src/BEDA.CMB/Contracts/Responses/23/RS23_11.cs
697
C#
/* * Copyright 2018 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. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Amazon.KinesisTap.Core; using System; namespace Amazon.KinesisTap.Filesystem { /// <summary> /// Interface for log parsers /// </summary> /// <remarks> /// As a general guideline, implementations of this class should be state-less i.e. it should not contains /// changing information about the log files. Any such meta data should be set in the <typeparamref name="TContext"/> parameter. /// </remarks> public interface ILogParser<TData, TContext> : IRecordParser where TContext : LogContext { /// <summary> /// Parse the log file for records. /// </summary> /// <param name="context">Log file's context</param> /// <param name="output">Where parsed records are appended</param> /// <param name="recordCount">Maximum number of records to be parsed</param> /// <param name="stopToken">Token to stop the operation</param> /// <remarks> /// Regarding the cancellation behavior of this method: when <paramref name="stopToken"/> throws <see cref="OperationCanceledException"/>, /// records might still have been added to <paramref name="output"/> and metadata in <paramref name="context"/> might have been changed. /// It is up to the user to decide how to deal with this updated information, for example, a source can simple ignore it and not use it to save bookmarks. /// </remarks> Task ParseRecordsAsync(TContext context, IList<IEnvelope<TData>> output, int recordCount, CancellationToken stopToken = default); } }
47.574468
162
0.694544
[ "Apache-2.0" ]
awslabs/kinesis-agent-windows
Amazon.KinesisTap.FileSystem/ILogParser.cs
2,236
C#
// -------------------------------------------------------------------------- // <copyright file="DiagnosticsClient.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // -------------------------------------------------------------------------- using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common.API.Clients.Abstractions; using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common.API.Clients.Diagnostics.Responses; using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common.Constants; using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common.TemplateModels; using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Extractor.Models; namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common.API.Clients.Diagnostics { public class DiagnosticClient : ApiClientBase, IDiagnosticClient { const string GetAllDiagnosticsRequest = "{0}/subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.ApiManagement/service/{3}/diagnostics?api-version={4}"; public async Task<List<DiagnosticTemplateResource>> GetApiDiagnosticsAsync(string apiName, ExtractorParameters extractorParameters) { var (azToken, azSubId) = await this.Auth.GetAccessToken(); string requestUrl = string.Format("{0}/subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.ApiManagement/service/{3}/apis/{4}/diagnostics?api-version={5}", this.BaseUrl, azSubId, extractorParameters.ResourceGroup, extractorParameters.SourceApimName, apiName, GlobalConstants.ApiVersion); var response = await this.CallApiManagementAsync<GetDiagnosticsResponse>(azToken, requestUrl); return response.Diagnostics; } public async Task<List<DiagnosticTemplateResource>> GetAllAsync(ExtractorParameters extractorParameters) { var (azToken, azSubId) = await this.Auth.GetAccessToken(); var requestUrl = string.Format(GetAllDiagnosticsRequest, this.BaseUrl, azSubId, extractorParameters.ResourceGroup, extractorParameters.SourceApimName, GlobalConstants.ApiVersion); var response = await this.CallApiManagementAsync<GetDiagnosticsResponse>(azToken, requestUrl); return response.Diagnostics; } } }
54.909091
172
0.711093
[ "MIT" ]
NET-C1211/azure-api-kit
src/ArmTemplates/Common/API/Clients/Diagnostics/DiagnosticClient.cs
2,418
C#
//********************************************************************* //xCAD //Copyright(C) 2021 Xarial Pty Limited //Product URL: https://www.xcad.net //License: https://xcad.xarial.com/license/ //********************************************************************* using SolidWorks.Interop.sldworks; using System; using System.Collections.Generic; using System.Text; using Xarial.XCad.SolidWorks.UI.PropertyPage; namespace Xarial.XCad.SolidWorks.Services { public interface IPropertyPageHandlerProvider { SwPropertyManagerPageHandler CreateHandler(ISldWorks app, Type handlerType); } internal class PropertyPageHandlerProvider : IPropertyPageHandlerProvider { public SwPropertyManagerPageHandler CreateHandler(ISldWorks app, Type handlerType) => (SwPropertyManagerPageHandler)Activator.CreateInstance(handlerType); } }
32.62963
90
0.643587
[ "MIT" ]
EddyAlleman/xcad
src/SolidWorks/Services/PropertyPageHandlerProvider.cs
883
C#
using System; using Microsoft.AspNetCore.Http; namespace DatingApp.API.Helpers { public static class Extensions { public static void AddApplicationError(this HttpResponse response, string message) { response.Headers.Add("Application-Error", message); response.Headers.Add("Access-Control-Expose-Headers","Application-Error"); response.Headers.Add("Access-Control-Allow-Origin","*"); } public static int CalculateAge(this DateTime thDateTime) { var age = DateTime.Today.Year - thDateTime.Year; if (thDateTime.AddYears(age) > DateTime.Today) { age--; } return age; } } }
29.68
90
0.597035
[ "Unlicense" ]
brauniks/SomeAngularAPP
API/Helpers/Extensions.cs
742
C#
using System; using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.ReactiveUI; namespace IPOCS.JMRI.CONTROL { class Program { // Initialization code. Don't use any Avalonia, third-party APIs or any // SynchronizationContext-reliant code before AppMain is called: things aren't initialized // yet and stuff might break. public static void Main(string[] args) => BuildAvaloniaApp() .StartWithClassicDesktopLifetime(args); // Avalonia configuration, don't remove; also used by visual designer. public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() .UsePlatformDetect() .LogToDebug() .UseReactiveUI(); } }
30.5
94
0.70082
[ "MIT" ]
GMJS/gmjs_ocs_jmri
IPOCS.JMRI.CONTROL/Program.cs
734
C#
using System; using System.Collections.Generic; using Esfa.Vacancy.Application.Commands.CreateApprenticeship; using Esfa.Vacancy.Application.Interfaces; using Esfa.Vacancy.Domain.Entities; using Esfa.Vacancy.Infrastructure.Services; using FluentAssertions; using Moq; using NUnit.Framework; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using SFA.DAS.VacancyServices.Wage; namespace Esfa.Vacancy.UnitTests.CreateApprenticeship.Application.GivenAMinimumWageSelector { [TestFixture] public class WhenSelectingHourlyRate { private static List<TestCaseData> TestCases => new List<TestCaseData> { new TestCaseData(DateTime.Parse("2016-09-30"), 3.30m ) .SetName("And date is pre 1/10/2016"), new TestCaseData(DateTime.Parse("2016-10-01"), 3.40m ) .SetName("And date is 1/10/2016"), new TestCaseData(DateTime.Parse("2017-03-20"), 3.40m ) .SetName("And date is 20/03/2017"), new TestCaseData(DateTime.Parse("2017-04-01"), 3.50m ) .SetName("And date is 1/04/2017"), new TestCaseData(DateTime.Parse("2018-03-03"), 3.50m ) .SetName("And date is 30/03/2017"), new TestCaseData(DateTime.Parse("2018-04-01"), 3.70m ) .SetName("And date is 01/04/2018"), new TestCaseData(DateTime.Parse("2019-03-30"), 3.70m ) .SetName("And date is 30/03/2019"), new TestCaseData(DateTime.Parse("2019-04-01"), 3.90m ) .SetName("And date is 01/04/2019"), }; [TestCaseSource(nameof(TestCases))] public void WhenCallingSelectHourlyRate(DateTime expectedStartDate, decimal expectedHourlyRate) { var getMinimumWagesService = new GetMinimumWagesService(); var hourlyRate = getMinimumWagesService.GetApprenticeMinimumWageRate(expectedStartDate); hourlyRate.Should().Be(expectedHourlyRate); } } }
41.729167
103
0.65302
[ "MIT" ]
SkillsFundingAgency/das-vacancyservices-api
src/Esfa.Vacancy.UnitTests/CreateApprenticeship/Application/GivenAMinimumWageSelector/WhenSelectingHourlyRate.cs
2,005
C#
#if !__WATCHOS__ using System; using System.Threading; using Foundation; using Network; using ObjCRuntime; using CoreFoundation; using NUnit.Framework; using MonoTests.System.Net.Http; namespace MonoTouchFixtures.Network { [TestFixture] [Preserve (AllMembers = true)] public class NWProtocolIPOptionsTest { AutoResetEvent connectedEvent; // used to let us know when the connection was established so that we can access the NWPath string host; NWConnection connection; NWProtocolStack stack; NWProtocolIPOptions options; void ConnectionStateHandler (NWConnectionState state, NWError error) { switch (state){ case NWConnectionState.Ready: connectedEvent.Set (); break; case NWConnectionState.Invalid: case NWConnectionState.Failed: Assert.Inconclusive ("Network connection could not be performed."); break; } } [OneTimeSetUp] public void Init () { TestRuntime.AssertXcodeVersion (11, 0); // we want to use a single connection, since it is expensive connectedEvent = new AutoResetEvent(false); host = NetworkResources.MicrosoftUri.Host; using (var parameters = NWParameters.CreateTcp ()) using (var endpoint = NWEndpoint.Create (host, "80")) { connection = new NWConnection (endpoint, parameters); connection.SetQueue (DispatchQueue.DefaultGlobalQueue); // important, else we will get blocked connection.SetStateChangeHandler (ConnectionStateHandler); connection.Start (); Assert.True (connectedEvent.WaitOne (20000), "Connection timed out."); stack = parameters.ProtocolStack; using (var ipOptions = stack.InternetProtocol) { if (ipOptions != null) { ipOptions.IPSetVersion (NWIPVersion.Version4); stack.PrependApplicationProtocol (ipOptions); } } } } [OneTimeTearDown] public void Dispose() { connection?.Dispose (); stack?.Dispose (); } [SetUp] public void SetUp () { options = stack.InternetProtocol as NWProtocolIPOptions; Assert.NotNull (options, "options"); } // we cannot assert that the C code those the right thing, BUT we do know // that if we call the property with the wrong pointer we will get an exception // from the runtime because the C lib does check the pointer that is used for the call [Test] public void SetIPVersionTest () => Assert.DoesNotThrow (() => options.SetVersion (NWIPVersion.Version6)); [Test] public void SetHopLimitTest () => Assert.DoesNotThrow (() => options.SetHopLimit (1)); [Test] public void SetUseMinimumMtu () => Assert.DoesNotThrow (() => options.SetUseMinimumMtu (true)); [Test] public void SetDisableFragmentation () => Assert.DoesNotThrow (() => options.SetDisableFragmentation (true)); [Test] public void SetCaculateReceiveTimeTest () => Assert.DoesNotThrow (() => options.SetCalculateReceiveTime (true)); [Test] public void SetIPLocalAddressPreference () => Assert.DoesNotThrow (() => options.SetIPLocalAddressPreference (NWIPLocalAddressPreference.Temporary)); } } #endif
29.466019
151
0.724876
[ "BSD-3-Clause" ]
Therzok/xamarin-macios
tests/monotouch-test/Network/NWProtocolIPOptionsTest.cs
3,035
C#
namespace MassTransit.Configurators { using System; using System.Linq; using Util.Scanning; public class SendMessageFilterSpecification : IMessageFilterConfigurator { readonly CompositeFilter<SendContext> _filter; public SendMessageFilterSpecification() { _filter = new CompositeFilter<SendContext>(); } public CompositeFilter<SendContext> Filter => _filter; void IMessageFilterConfigurator.Include(params Type[] messageTypes) => _filter.Includes += message => Match(message, messageTypes); void IMessageFilterConfigurator.Include<T>() => _filter.Includes += message => Match(message, typeof(T)); void IMessageFilterConfigurator.Include<T>(Func<T, bool> filter) => _filter.Includes += message => Match(message, filter); void IMessageFilterConfigurator.Exclude(params Type[] messageTypes) => _filter.Excludes += message => Match(message, messageTypes); void IMessageFilterConfigurator.Exclude<T>() => _filter.Excludes += message => Match(message, typeof(T)); void IMessageFilterConfigurator.Exclude<T>(Func<T, bool> filter) => _filter.Excludes += message => Match(message, filter); static bool Match(SendContext context, params Type[] messageTypes) { return messageTypes.Any(x => typeof(SendContext<>).MakeGenericType(x).IsInstanceOfType(context)); } static bool Match<T>(SendContext context, Func<T, bool> filter) where T : class { var sendContext = context as SendContext<T>; return sendContext != null && filter(sendContext.Message); } } }
34.730769
110
0.624585
[ "ECL-2.0", "Apache-2.0" ]
CodeNotFoundException/MassTransit
src/MassTransit/Configuration/Configurators/SendMessageFilterSpecification.cs
1,806
C#
using System.Threading.Tasks; namespace Resgrid.Model.Services { /// <summary> /// Interface ILimitsService /// </summary> public interface ILimitsService { /// <summary> /// Validates the department is within limits asynchronous. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> ValidateDepartmentIsWithinLimitsAsync(int departmentId); /// <summary> /// Determines whether this instance [can department add new user asynchronous] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> CanDepartmentAddNewUserAsync(int departmentId); /// <summary> /// Determines whether this instance [can department add new group] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> CanDepartmentAddNewGroup(int departmentId); /// <summary> /// Determines whether this instance [can department add new role] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns><c>true</c> if this instance [can department add new role] the specified department identifier; otherwise, <c>false</c>.</returns> bool CanDepartmentAddNewRole(int departmentId); /// <summary> /// Determines whether this instance [can department add new unit] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> CanDepartmentAddNewUnit(int departmentId); /// <summary> /// Gets the personnel limit for department asynchronous. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <param name="plan">The plan.</param> /// <returns>Task&lt;System.Int32&gt;.</returns> Task<int> GetPersonnelLimitForDepartmentAsync(int departmentId, Plan plan = null); /// <summary> /// Gets the groups limit for department asynchronous. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <param name="plan">The plan.</param> /// <returns>Task&lt;System.Int32&gt;.</returns> Task<int> GetGroupsLimitForDepartmentAsync(int departmentId, Plan plan = null); /// <summary> /// Gets the roles limit for department. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>System.Int32.</returns> int GetRolesLimitForDepartment(int departmentId); /// <summary> /// Gets the units limit for department asynchronous. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <param name="plan">The plan.</param> /// <returns>Task&lt;System.Int32&gt;.</returns> Task<int> GetUnitsLimitForDepartmentAsync(int departmentId, Plan plan = null); /// <summary> /// Determines whether this instance [can department provision number asynchronous] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> CanDepartmentProvisionNumberAsync(int departmentId); /// <summary> /// Determines whether this instance [can department use voice asynchronous] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> CanDepartmentUseVoiceAsync(int departmentId); /// <summary> /// Determines whether this instance [can department use links asynchronous] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> CanDepartmentUseLinksAsync(int departmentId); /// <summary> /// Determines whether this instance [can department create orders asynchronous] the specified department identifier. /// </summary> /// <param name="departmentId">The department identifier.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> CanDepartmentCreateOrdersAsync(int departmentId); } }
42.066667
145
0.71655
[ "Apache-2.0" ]
Joshb888/dfdfd
Core/Resgrid.Model/Services/ILimitsService.cs
4,419
C#
using System.Collections.Generic; using System.IO; namespace XnbUnpacker.ProgressHandling { /// <summary>The context info for the current unpack run.</summary> public interface IUnpackContext { /// <summary>The absolute path to the game folder.</summary> string GamePath { get; } /// <summary>The absolute path to the content folder.</summary> string ContentPath { get; } /// <summary>The absolute path to the folder containing exported assets.</summary> string ExportPath { get; } /// <summary>The files found to unpack.</summary> IEnumerable<FileInfo> Files { get; } } }
29.863636
90
0.65449
[ "MIT" ]
Steviegt6/XnbUnpacker
XnbUnpacker/ProgressHandling/IUnpackContext.cs
657
C#
using System.Threading; using System.Threading.Tasks; namespace Lucaniss.Dispatcher.Requests { public interface IRequestHandler<in TRequest, TResponse> where TRequest : IRequest<TResponse> { Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken); } }
27.545455
86
0.749175
[ "MIT" ]
lucaniss/dispatcher
Lucaniss.Dispatcher/Requests/IRequestHandler.cs
305
C#
using System; namespace IMDB.Api.Repositories.Interfaces { public interface IUserRepository : IGenericRepository<Entities.User> { } }
14.9
72
0.731544
[ "MIT" ]
eseerigha/IMDB.API
IMDB.Api/Repositories/Interfaces/IUserRepository.cs
151
C#
using System.ServiceModel; namespace UberStrok.WebServices.Contracts { [ServiceContract] public interface IAuthenticationWebServiceContract { [OperationContract] byte[] CreateUser(byte[] data); [OperationContract] byte[] CompleteAccount(byte[] data); [OperationContract] byte[] LoginMemberEmail(byte[] data); [OperationContract] byte[] LoginMemberFacebookUnitySdk(byte[] data); [OperationContract] byte[] LoginSteam(byte[] data); [OperationContract] byte[] LoginMemberPortal(byte[] data); [OperationContract] byte[] LinkSteamMember(byte[] data); } }
24.586207
57
0.612903
[ "MIT" ]
FICTURE7/uberstrok
src/UberStrok.WebServices.Contracts/IAuthenticationWebServiceContract.cs
715
C#
using System; using System.Collections.Generic; using UnityEditor.AddressableAssets.Settings; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.AddressableAssets; using System.Linq; namespace UnityEditor.AddressableAssets.GUI { internal class ProfileWindow : EditorWindow { //Min and Max proportion of the window that ProfilePane can take up const float k_MinProfilePaneWidth = 0.10f; const float k_MaxProfilePaneWidth = 0.6f; private const float k_MinLabelWidth = 155f; private const float k_ApproxCharWidth = 8.5f; const float k_DefaultHorizontalSplitterRatio = 0.33f; const int k_SplitterThickness = 2; const int k_ToolbarHeight = 20; const int k_ItemRectPadding = 15; //amount of padding between variable items const float k_VariableItemPadding = 5f; //Default length of the Label within the Variables Pane private float m_LabelWidth = 155f; private float m_FieldBufferWidth = 0f; //Separator private const char k_PrefixSeparator = '.'; GUIStyle m_ItemRectPadding; float m_HorizontalSplitterRatio = k_DefaultHorizontalSplitterRatio; internal AddressableAssetSettings settings { get { return AddressableAssetSettingsDefaultObject.Settings; } } private ProfileTreeView m_ProfileTreeView; private bool m_IsResizingHorizontalSplitter; internal static bool m_Reload = false; private Vector2 m_ProfilesPaneScrollPosition; private Vector2 m_VariablesPaneScrollPosition; private int m_ProfileIndex = -1; public int ProfileIndex { get { return m_ProfileIndex; } set { m_ProfileIndex = value; } } private GUIStyle m_ButtonStyle; private Dictionary<string, bool?> m_foldouts = new Dictionary<string, bool?>(); [MenuItem("Window/Asset Management/Addressables/Profiles", priority = 2051)] internal static void ShowWindow() { var settings = AddressableAssetSettingsDefaultObject.Settings; if (settings == null) { EditorUtility.DisplayDialog("Error", "Attempting to open Addressables Profiles window, but no Addressables Settings file exists. \n\nOpen 'Window/Asset Management/Addressables/Groups' for more info.", "Ok"); return; } GetWindow<ProfileWindow>().Show(); } internal static void DrawOutline(Rect rect, float size) { Color color = new Color(0.6f, 0.6f, 0.6f, 1.333f); if (EditorGUIUtility.isProSkin) { color.r = 0.12f; color.g = 0.12f; color.b = 0.12f; } if (Event.current.type != EventType.Repaint) return; Color orgColor = UnityEngine.GUI.color; UnityEngine.GUI.color = UnityEngine.GUI.color * color; UnityEngine.GUI.DrawTexture(new Rect(rect.x, rect.y, rect.width, size), EditorGUIUtility.whiteTexture); UnityEngine.GUI.DrawTexture(new Rect(rect.x, rect.yMax - size, rect.width, size), EditorGUIUtility.whiteTexture); UnityEngine.GUI.DrawTexture(new Rect(rect.x, rect.y + 1, size, rect.height - 2 * size), EditorGUIUtility.whiteTexture); UnityEngine.GUI.DrawTexture(new Rect(rect.xMax - size, rect.y + 1, size, rect.height - 2 * size), EditorGUIUtility.whiteTexture); UnityEngine.GUI.color = orgColor; } private void OnEnable() { Undo.undoRedoPerformed += MarkForReload; titleContent = new GUIContent("Addressables Profiles"); m_ItemRectPadding = new GUIStyle(); m_ItemRectPadding.padding = new RectOffset(k_ItemRectPadding, k_ItemRectPadding, k_ItemRectPadding, k_ItemRectPadding); } private void OnDisable() { Undo.undoRedoPerformed -= MarkForReload; } internal static void MarkForReload() { m_Reload = true; } GUIStyle GetStyle(string styleName) { GUIStyle s = UnityEngine.GUI.skin.FindStyle(styleName); if (s == null) s = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle(styleName); if (s == null) { Addressables.LogError("Missing built-in guistyle " + styleName); s = new GUIStyle(); } return s; } void DeleteVariable(AddressableAssetProfileSettings.ProfileIdData toBeDeleted) { Undo.RecordObject(settings, "Profile Variable Deleted"); settings.profileSettings.RemoveValue(toBeDeleted.Id); AddressableAssetUtility.OpenAssetIfUsingVCIntegration(settings); } void TopToolbar(Rect toolbarPos) { if (m_ButtonStyle == null) m_ButtonStyle = GetStyle("ToolbarButton"); m_ButtonStyle.alignment = TextAnchor.MiddleLeft; GUILayout.BeginArea(new Rect(0, 0, toolbarPos.width, k_ToolbarHeight)); GUILayout.BeginHorizontal(EditorStyles.toolbar); { var guiMode = new GUIContent("Create"); Rect rMode = GUILayoutUtility.GetRect(guiMode, EditorStyles.toolbarDropDown); if (EditorGUI.DropdownButton(rMode, guiMode, FocusType.Passive, EditorStyles.toolbarDropDown)) { var menu = new GenericMenu(); menu.AddItem(new GUIContent("Profile"), false, NewProfile); menu.AddItem(new GUIContent("Variable (All Profiles)"), false, () => EditorApplication.delayCall += NewVariable); menu.AddItem(new GUIContent("Build & Load Path Variables (All Profiles)"), false, () => EditorApplication.delayCall += NewPathPair); menu.DropDown(rMode); } GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.EndArea(); } void NewVariable() { try { PopupWindow.Show(new Rect(position.x, position.y + k_ToolbarHeight, position.width, k_ToolbarHeight), new ProfileNewVariablePopup(position.width, position.height, 0, m_ProfileTreeView, settings)); } catch (ExitGUIException) { // Exception not being caught through OnGUI call } } void NewPathPair() { try { PopupWindow.Show(new Rect(position.x, position.y + k_ToolbarHeight, position.width, k_ToolbarHeight), new ProfileNewPathPairPopup(position.width, position.height, 0, m_ProfileTreeView, settings)); } catch (ExitGUIException) { // Exception not being caught through OnGUI call } } //Contains all of the profile names, primarily implemented in ProfileTreeView void ProfilesPane(Rect profilesPaneRect) { DrawOutline(profilesPaneRect, 1); GUILayout.BeginArea(profilesPaneRect); { m_ProfilesPaneScrollPosition = GUILayout.BeginScrollView(m_ProfilesPaneScrollPosition); Rect r = new Rect(profilesPaneRect); r.y = 0; var profiles = settings.profileSettings.profiles; if (m_ProfileTreeView == null || m_ProfileTreeView.Names.Count != profiles.Count || m_Reload) { m_Reload = false; m_ProfileTreeView = new ProfileTreeView(new TreeViewState(), profiles, this, ProfileTreeView.CreateHeader()); } m_ProfileTreeView.OnGUI(r); GUILayout.EndScrollView(); } GUILayout.EndArea(); } //Displays all variables for the currently selected profile and initializes each variable's context menu void VariablesPane(Rect variablesPaneRect) { DrawOutline(variablesPaneRect, 1); Event evt = Event.current; AddressableAssetProfileSettings.BuildProfile selectedProfile = GetSelectedProfile(); if (selectedProfile == null) return; if (evt.isMouse || evt.isKey) { m_ProfileTreeView.lastClickedProfile = ProfileIndex; } //ensures amount of visible text is not affected by label width float fieldWidth = variablesPaneRect.width - (2 * k_ItemRectPadding) + m_FieldBufferWidth; if (!EditorGUIUtility.labelWidth.Equals(m_LabelWidth)) EditorGUIUtility.labelWidth = m_LabelWidth; int maxLabelLen = 0; int maxFieldLen = 0; GUILayout.BeginArea(variablesPaneRect); EditorGUI.indentLevel++; List<ProfileGroupType> groupTypes = ProfileGroupType.CreateGroupTypes(selectedProfile); HashSet<string> drawnGroupTypes = new HashSet<string>(); //Displaying Path Groups foreach (ProfileGroupType groupType in groupTypes) { bool? foldout; m_foldouts.TryGetValue(groupType.GroupTypePrefix, out foldout); GUILayout.Space(5); m_foldouts[groupType.GroupTypePrefix] = EditorGUILayout.Foldout(foldout != null ? foldout.Value : true, groupType.GroupTypePrefix, true); //Specific Grouped variables List<ProfileGroupType.GroupTypeVariable> pathVariables = new List<ProfileGroupType.GroupTypeVariable>(); pathVariables.Add(groupType.GetVariableBySuffix("BuildPath")); drawnGroupTypes.Add(groupType.GetName(groupType.GetVariableBySuffix("BuildPath"))); pathVariables.Add(groupType.GetVariableBySuffix("LoadPath")); drawnGroupTypes.Add(groupType.GetName(groupType.GetVariableBySuffix("LoadPath"))); if (m_foldouts[groupType.GroupTypePrefix].Value) { EditorGUI.indentLevel++; //Displaying Path Groups foreach(var variable in pathVariables) { Rect newPathRect = EditorGUILayout.BeginVertical(); string newPath = EditorGUILayout.TextField(groupType.GetName(variable), variable.Value, new GUILayoutOption[]{ GUILayout.Width(fieldWidth)}); EditorGUILayout.EndVertical(); if (evt.type == EventType.ContextClick) { CreateVariableContextMenu(variablesPaneRect, newPathRect, settings.profileSettings.GetProfileDataByName(groupType.GetName(variable)), evt); } if (newPath != variable.Value && ProfileIndex == m_ProfileTreeView.lastClickedProfile) { Undo.RecordObject(settings, "Variable value changed"); settings.profileSettings.SetValue(selectedProfile.id, groupType.GetName(variable), newPath); AddressableAssetUtility.OpenAssetIfUsingVCIntegration(settings); } } EditorGUI.indentLevel--; } } //Display all other variables for (var i = 0; i < settings.profileSettings.profileEntryNames.Count; i++) { AddressableAssetProfileSettings.ProfileIdData curVariable = settings.profileSettings.profileEntryNames[i]; if (!drawnGroupTypes.Contains(curVariable.ProfileName)) { GUILayout.Space(5); Rect newValueRect = EditorGUILayout.BeginVertical(); string newValue = EditorGUILayout.TextField(curVariable.ProfileName, selectedProfile.values[i].value, new GUILayoutOption[] { GUILayout.Width(fieldWidth) }); EditorGUILayout.EndVertical(); if (newValue != selectedProfile.values[i].value && ProfileIndex == m_ProfileTreeView.lastClickedProfile) { Undo.RecordObject(settings, "Variable value changed"); settings.profileSettings.SetValue(selectedProfile.id, settings.profileSettings.profileEntryNames[i].ProfileName, newValue); AddressableAssetUtility.OpenAssetIfUsingVCIntegration(settings); } if (evt.type == EventType.ContextClick) { CreateVariableContextMenu(variablesPaneRect, newValueRect, curVariable, evt); } } maxLabelLen = Math.Max(maxLabelLen, curVariable.ProfileName.Length); } EditorGUI.indentLevel--; GUILayout.EndArea(); //Update the label width to the maximum of the minimum acceptable label width and the amount of //space required to contain the longest variable name m_LabelWidth = Mathf.Max(maxLabelLen * k_ApproxCharWidth, k_MinLabelWidth); m_FieldBufferWidth = Mathf.Clamp((maxFieldLen * k_ApproxCharWidth) - fieldWidth, 0f, float.MaxValue); } //Creates the context menu for the selected variable void CreateVariableContextMenu(Rect parentWindow, Rect menuRect, AddressableAssetProfileSettings.ProfileIdData variable, Event evt) { if (menuRect.Contains(evt.mousePosition)) { GenericMenu menu = new GenericMenu(); //Displays name of selected variable so user can be confident they're deleting/renaming the right one menu.AddDisabledItem(new GUIContent(variable.ProfileName)); menu.AddSeparator(""); menu.AddItem(new GUIContent("Rename Variable (All Profiles)"), false, () => { RenameVariable(variable, parentWindow, menuRect); }); menu.AddItem(new GUIContent("Delete Variable (All Profiles)"), false, () => { DeleteVariable(variable); }); menu.ShowAsContext(); evt.Use(); } } //Opens ProfileRenameVariablePopup void RenameVariable(AddressableAssetProfileSettings.ProfileIdData profileVariable, Rect parentWindow, Rect displayRect) { try { //Determines the current variable rect location Rect variableRect = new Rect(position.x + parentWindow.x + displayRect.x, position.y + parentWindow.y + displayRect.y, position.width, k_ToolbarHeight); PopupWindow.Show(variableRect, new ProfileRenameVariablePopup(displayRect, profileVariable, settings)); } catch (ExitGUIException) { // Exception not being caught through OnGUI call } } //Returns the BuildProfile currently selected in the ProfilesPane AddressableAssetProfileSettings.BuildProfile GetSelectedProfile() { return m_ProfileTreeView.GetSelectedProfile(); } //Creates a new BuildProfile and reloads the ProfilesPane void NewProfile() { var uniqueProfileName = settings.profileSettings.GetUniqueProfileName("New Profile"); if (!string.IsNullOrEmpty(uniqueProfileName)) { Undo.RecordObject(settings, "New Profile Created"); //Either copy values from the selected profile, or if there is no selected profile, copy from the default string idToCopyFrom = GetSelectedProfile() != null ? GetSelectedProfile().id : settings.profileSettings.profiles[0].id; settings.profileSettings.AddProfile(uniqueProfileName, idToCopyFrom); AddressableAssetUtility.OpenAssetIfUsingVCIntegration(settings); m_ProfileTreeView.Reload(); } } private void OnGUI() { if (settings == null) return; if (m_IsResizingHorizontalSplitter) m_HorizontalSplitterRatio = Mathf.Clamp(Event.current.mousePosition.x / position.width, k_MinProfilePaneWidth, k_MaxProfilePaneWidth); var toolbarRect = new Rect(0, 0, position.width, position.height); var profilesPaneRect = new Rect(0, k_ToolbarHeight, (position.width * m_HorizontalSplitterRatio), position.height); var variablesPaneRect = new Rect(profilesPaneRect.width + k_SplitterThickness, k_ToolbarHeight, position.width - profilesPaneRect.width - k_SplitterThickness, position.height - k_ToolbarHeight); var horizontalSplitterRect = new Rect(profilesPaneRect.width, k_ToolbarHeight, k_SplitterThickness, position.height - k_ToolbarHeight); EditorGUIUtility.AddCursorRect(horizontalSplitterRect, MouseCursor.ResizeHorizontal); if (Event.current.type == EventType.MouseDown && horizontalSplitterRect.Contains(Event.current.mousePosition)) m_IsResizingHorizontalSplitter = true; else if (Event.current.type == EventType.MouseUp) m_IsResizingHorizontalSplitter = false; TopToolbar(toolbarRect); ProfilesPane(profilesPaneRect); VariablesPane(variablesPaneRect); if (m_IsResizingHorizontalSplitter) Repaint(); } class ProfileRenameVariablePopup : PopupWindowContent { internal Rect m_WindowRect; internal AddressableAssetProfileSettings.ProfileIdData m_ProfileVariable; internal AddressableAssetSettings m_Settings; internal string m_NewName; public ProfileRenameVariablePopup(Rect fieldRect, AddressableAssetProfileSettings.ProfileIdData profileVariable, AddressableAssetSettings settings) { m_WindowRect = fieldRect; m_ProfileVariable = profileVariable; m_Settings = settings; m_NewName = m_ProfileVariable.ProfileName; UnityEngine.GUI.enabled = true; } public override Vector2 GetWindowSize() { return new Vector2(m_WindowRect.width, m_WindowRect.height); } public override void OnGUI(Rect windowRect) { GUILayout.BeginArea(windowRect); Event evt = Event.current; bool hitEnter = evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter); m_NewName = GUILayout.TextField(m_NewName); if (hitEnter) { if (string.IsNullOrEmpty(m_NewName)) Debug.LogError("Variable name cannot be empty."); else if (m_NewName != m_Settings.profileSettings.GetUniqueProfileEntryName(m_NewName)) Debug.LogError("Profile variable '" + m_NewName + "' already exists."); else if (m_NewName.Trim().Length == 0) // new name cannot only contain spaces Debug.LogError("Name cannot be only spaces"); else { Undo.RecordObject(m_Settings, "Profile Variable Renamed"); m_ProfileVariable.SetName(m_NewName, m_Settings.profileSettings); AddressableAssetUtility.OpenAssetIfUsingVCIntegration(m_Settings, true); editorWindow.Close(); } } GUILayout.EndArea(); } } class ProfileNewVariablePopup : PopupWindowContent { internal float m_WindowWidth; internal float m_WindowHeight; internal float m_xOffset; internal string m_Name; internal string m_Value; internal bool m_NeedsFocus = true; internal AddressableAssetSettings m_Settings; ProfileTreeView m_ProfileTreeView; public ProfileNewVariablePopup(float width, float height, float xOffset, ProfileTreeView profileTreeView, AddressableAssetSettings settings) { m_WindowWidth = width; m_WindowHeight = height; m_xOffset = xOffset; m_Settings = settings; m_Name = m_Settings.profileSettings.GetUniqueProfileEntryName("New Entry"); m_Value = Application.dataPath; m_ProfileTreeView = profileTreeView; } public override Vector2 GetWindowSize() { float width = Mathf.Clamp(m_WindowWidth * 0.375f, Mathf.Min(600, m_WindowWidth - m_xOffset), m_WindowWidth); float height = Mathf.Clamp(65, Mathf.Min(65, m_WindowHeight), m_WindowHeight); return new Vector2(width, height); } public override void OnGUI(Rect windowRect) { GUILayout.Space(5); Event evt = Event.current; bool hitEnter = evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter); EditorGUIUtility.labelWidth = 90; m_Name = EditorGUILayout.TextField("Variable Name", m_Name); m_Value = EditorGUILayout.TextField("Default Value", m_Value); UnityEngine.GUI.enabled = m_Name.Length != 0; if (GUILayout.Button("Save") || hitEnter) { if (string.IsNullOrEmpty(m_Name)) Debug.LogError("Variable name cannot be empty."); else if (m_Name != m_Settings.profileSettings.GetUniqueProfileEntryName(m_Name)) Debug.LogError("Profile variable '" + m_Name + "' already exists."); else { Undo.RecordObject(m_Settings, "Profile Variable " + m_Name + " Created"); m_Settings.profileSettings.CreateValue(m_Name, m_Value); AddressableAssetUtility.OpenAssetIfUsingVCIntegration(m_Settings); m_ProfileTreeView.Reload(); editorWindow.Close(); } } } } class ProfileNewPathPairPopup : PopupWindowContent { internal float m_WindowWidth; internal float m_WindowHeight; internal float m_xOffset; internal string m_Name; internal string m_BuildPath; internal string m_LoadPath; internal bool m_NeedsFocus = true; internal AddressableAssetSettings m_Settings; ProfileTreeView m_ProfileTreeView; public ProfileNewPathPairPopup(float width, float height, float xOffset, ProfileTreeView profileTreeView, AddressableAssetSettings settings) { m_WindowWidth = width; m_WindowHeight = height; m_xOffset = xOffset; m_Settings = settings; m_Name = m_Settings.profileSettings.GetUniqueProfileEntryName("New Entry"); m_BuildPath = Application.dataPath; m_LoadPath = Application.dataPath; m_ProfileTreeView = profileTreeView; } public override Vector2 GetWindowSize() { float width = Mathf.Clamp(m_WindowWidth * 0.375f, Mathf.Min(600, m_WindowWidth - m_xOffset), m_WindowWidth); float height = Mathf.Clamp(65, Mathf.Min(65, m_WindowHeight), m_WindowHeight); return new Vector2(width, height); } public override void OnGUI(Rect windowRect) { GUILayout.Space(5); Event evt = Event.current; bool hitEnter = evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter); EditorGUIUtility.labelWidth = 120; m_Name = EditorGUILayout.TextField("Prefix Name", m_Name); m_BuildPath = EditorGUILayout.TextField("Build Path Value", m_BuildPath); m_LoadPath = EditorGUILayout.TextField("Load Path Value", m_LoadPath); UnityEngine.GUI.enabled = m_Name.Length != 0; if (GUILayout.Button("Save") || hitEnter) { string buildPathName = m_Name + ProfileGroupType.k_PrefixSeparator + "BuildPath"; string loadPathName = m_Name + ProfileGroupType.k_PrefixSeparator + "LoadPath"; if (string.IsNullOrEmpty(m_Name)) Debug.LogError("Variable name cannot be empty."); else if (buildPathName != m_Settings.profileSettings.GetUniqueProfileEntryName(buildPathName)) Debug.LogError("Profile variable '" + buildPathName + "' already exists."); else if (loadPathName != m_Settings.profileSettings.GetUniqueProfileEntryName(loadPathName)) Debug.LogError("Profile variable '" + loadPathName + "' already exists."); else { Undo.RecordObject(m_Settings, "Profile Path Pair Created"); m_Settings.profileSettings.CreateValue(m_Name + ProfileGroupType.k_PrefixSeparator + "BuildPath", m_BuildPath); m_Settings.profileSettings.CreateValue(m_Name + ProfileGroupType.k_PrefixSeparator + "LoadPath", m_LoadPath); AddressableAssetUtility.OpenAssetIfUsingVCIntegration(m_Settings); m_ProfileTreeView.Reload(); editorWindow.Close(); } } } } } }
45.689775
224
0.597239
[ "Apache-2.0" ]
BrinisSpark/Space-Invaders-Clone
Library/PackageCache/com.unity.addressables@1.18.16/Editor/GUI/ProfileWindow.cs
26,363
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.Linq; using System.Reflection; using Microsoft.ML.Data; using Microsoft.ML.Trainers; using Microsoft.ML.Trainers.LightGbm; namespace Microsoft.ML.AutoML { internal enum TrainerName { AveragedPerceptronBinary, AveragedPerceptronOva, FastForestBinary, FastForestOva, FastForestRegression, FastTreeBinary, FastTreeOva, FastTreeRegression, FastTreeTweedieRegression, LightGbmBinary, LightGbmMulti, LightGbmRegression, LinearSvmBinary, LinearSvmOva, LbfgsLogisticRegressionBinary, LbfgsLogisticRegressionOva, LbfgsMaximumEntropyMulti, OnlineGradientDescentRegression, OlsRegression, Ova, LbfgsPoissonRegression, SdcaLogisticRegressionBinary, SdcaMaximumEntropyMulti, SdcaRegression, SgdCalibratedBinary, SgdCalibratedOva, SymbolicSgdLogisticRegressionBinary, SymbolicSgdLogisticRegressionOva, MatrixFactorization, ImageClassification } internal static class TrainerExtensionUtil { private const string WeightColumn = "ExampleWeightColumnName"; private const string LabelColumn = "LabelColumnName"; public static T CreateOptions<T>(IEnumerable<SweepableParam> sweepParams, string labelColumn) where T : TrainerInputBaseWithLabel { var options = Activator.CreateInstance<T>(); options.LabelColumnName = labelColumn; if (sweepParams != null) { UpdateFields(options, sweepParams); } return options; } public static T CreateOptions<T>(IEnumerable<SweepableParam> sweepParams) where T : class { var options = Activator.CreateInstance<T>(); if (sweepParams != null) { UpdateFields(options, sweepParams); } return options; } private static string[] _lightGbmBoosterParamNames = new[] { "L2Regularization", "L1Regularization" }; private const string LightGbmBoosterPropName = "Booster"; public static TOptions CreateLightGbmOptions<TOptions, TOutput, TTransformer, TModel>(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo) where TOptions : LightGbmTrainerBase<TOptions, TOutput, TTransformer, TModel>.OptionsBase, new() where TTransformer : ISingleFeaturePredictionTransformer<TModel> where TModel : class { var options = new TOptions(); options.LabelColumnName = columnInfo.LabelColumnName; options.ExampleWeightColumnName = columnInfo.ExampleWeightColumnName; options.Booster = new GradientBooster.Options(); if (sweepParams != null) { var boosterParams = sweepParams.Where(p => _lightGbmBoosterParamNames.Contains(p.Name)); var parentArgParams = sweepParams.Except(boosterParams); UpdateFields(options, parentArgParams); UpdateFields(options.Booster, boosterParams); } return options; } public static PipelineNode BuildOvaPipelineNode(ITrainerExtension multiExtension, ITrainerExtension binaryExtension, IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo) { var ovaNode = new PipelineNode() { Name = TrainerName.Ova.ToString(), NodeType = PipelineNodeType.Trainer, Properties = new Dictionary<string, object>() { { LabelColumn, columnInfo.LabelColumnName } } }; var binaryNode = binaryExtension.CreatePipelineNode(sweepParams, columnInfo); ovaNode.Properties["BinaryTrainer"] = binaryNode; return ovaNode; } public static PipelineNode BuildPipelineNode(TrainerName trainerName, IEnumerable<SweepableParam> sweepParams, string labelColumn, string weightColumn = null, IDictionary<string, object> additionalProperties = null) { var properties = BuildBasePipelineNodeProps(sweepParams, labelColumn, weightColumn); if (additionalProperties != null) { foreach (var property in additionalProperties) { properties[property.Key] = property.Value; } } return new PipelineNode(trainerName.ToString(), PipelineNodeType.Trainer, DefaultColumnNames.Features, DefaultColumnNames.Score, properties); } public static PipelineNode BuildLightGbmPipelineNode(TrainerName trainerName, IEnumerable<SweepableParam> sweepParams, string labelColumn, string weightColumn) { return new PipelineNode(trainerName.ToString(), PipelineNodeType.Trainer, DefaultColumnNames.Features, DefaultColumnNames.Score, BuildLightGbmPipelineNodeProps(sweepParams, labelColumn, weightColumn)); } private static IDictionary<string, object> BuildBasePipelineNodeProps(IEnumerable<SweepableParam> sweepParams, string labelColumn, string weightColumn) { var props = new Dictionary<string, object>(); if (sweepParams != null) { foreach (var sweepParam in sweepParams) { props[sweepParam.Name] = sweepParam.ProcessedValue(); } } props[LabelColumn] = labelColumn; if (weightColumn != null) { props[WeightColumn] = weightColumn; } return props; } private static IDictionary<string, object> BuildLightGbmPipelineNodeProps(IEnumerable<SweepableParam> sweepParams, string labelColumn, string weightColumn) { Dictionary<string, object> props = null; if (sweepParams == null || !sweepParams.Any()) { props = new Dictionary<string, object>(); } else { var boosterParams = sweepParams.Where(p => _lightGbmBoosterParamNames.Contains(p.Name)); var parentArgParams = sweepParams.Except(boosterParams); var boosterProps = boosterParams.ToDictionary(p => p.Name, p => (object)p.ProcessedValue()); var boosterCustomProp = new CustomProperty("GradientBooster.Options", boosterProps); props = parentArgParams.ToDictionary(p => p.Name, p => (object)p.ProcessedValue()); props[LightGbmBoosterPropName] = boosterCustomProp; } props[LabelColumn] = labelColumn; if (weightColumn != null) { props[WeightColumn] = weightColumn; } return props; } public static ParameterSet BuildParameterSet(TrainerName trainerName, IDictionary<string, object> props) { props = props.Where(p => p.Key != LabelColumn && p.Key != WeightColumn) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (trainerName == TrainerName.LightGbmBinary || trainerName == TrainerName.LightGbmMulti || trainerName == TrainerName.LightGbmRegression) { return BuildLightGbmParameterSet(props); } var paramVals = props.Select(p => new StringParameterValue(p.Key, p.Value.ToString())); return new ParameterSet(paramVals); } public static ColumnInformation BuildColumnInfo(IDictionary<string, object> props) { var columnInfo = new ColumnInformation(); columnInfo.LabelColumnName = props[LabelColumn] as string; props.TryGetValue(WeightColumn, out var weightColumn); columnInfo.ExampleWeightColumnName = weightColumn as string; return columnInfo; } private static ParameterSet BuildLightGbmParameterSet(IDictionary<string, object> props) { IEnumerable<IParameterValue> parameters; if (props == null || !props.Any()) { parameters = new List<IParameterValue>(); } else { var parentProps = props.Where(p => p.Key != LightGbmBoosterPropName); var treeProps = ((CustomProperty)props[LightGbmBoosterPropName]).Properties; var allProps = parentProps.Union(treeProps); parameters = allProps.Select(p => new StringParameterValue(p.Key, p.Value.ToString())); } return new ParameterSet(parameters); } private static void SetValue(FieldInfo fi, IComparable value, object obj, Type propertyType) { if (propertyType == value?.GetType()) fi.SetValue(obj, value); else if (propertyType == typeof(double) && value is float) fi.SetValue(obj, Convert.ToDouble(value)); else if (propertyType == typeof(int) && value is long) fi.SetValue(obj, Convert.ToInt32(value)); else if (propertyType == typeof(long) && value is int) fi.SetValue(obj, Convert.ToInt64(value)); } /// <summary> /// Updates properties of object instance based on the values in sweepParams /// </summary> public static void UpdateFields(object obj, IEnumerable<SweepableParam> sweepParams) { foreach (var param in sweepParams) { try { // Only updates property if param.value isn't null and // param has a name of property. if (param.RawValue == null) { continue; } var fi = obj.GetType().GetField(param.Name); var propType = Nullable.GetUnderlyingType(fi.FieldType) ?? fi.FieldType; if (param is SweepableDiscreteParam dp) { var optIndex = (int)dp.RawValue; //Contracts.Assert(0 <= optIndex && optIndex < dp.Options.Length, $"Options index out of range: {optIndex}"); var option = dp.Options[optIndex].ToString().ToLower(); // Handle <Auto> string values in sweep params if (option == "auto" || option == "<auto>" || option == "< auto >") { //Check if nullable type, in which case 'null' is the auto value. if (Nullable.GetUnderlyingType(fi.FieldType) != null) fi.SetValue(obj, null); else if (fi.FieldType.IsEnum) { // Check if there is an enum option named Auto var enumDict = fi.FieldType.GetEnumValues().Cast<int>() .ToDictionary(v => Enum.GetName(fi.FieldType, v), v => v); if (enumDict.ContainsKey("Auto")) fi.SetValue(obj, enumDict["Auto"]); } } else SetValue(fi, (IComparable)dp.Options[optIndex], obj, propType); } else SetValue(fi, param.RawValue, obj, propType); } catch (Exception) { throw new InvalidOperationException($"Cannot set parameter {param.Name} for {obj.GetType()}"); } } } public static TrainerName GetTrainerName(BinaryClassificationTrainer binaryTrainer) { switch (binaryTrainer) { case BinaryClassificationTrainer.AveragedPerceptron: return TrainerName.AveragedPerceptronBinary; case BinaryClassificationTrainer.FastForest: return TrainerName.FastForestBinary; case BinaryClassificationTrainer.FastTree: return TrainerName.FastTreeBinary; case BinaryClassificationTrainer.LightGbm: return TrainerName.LightGbmBinary; case BinaryClassificationTrainer.LinearSvm: return TrainerName.LinearSvmBinary; case BinaryClassificationTrainer.LbfgsLogisticRegression: return TrainerName.LbfgsLogisticRegressionBinary; case BinaryClassificationTrainer.SdcaLogisticRegression: return TrainerName.SdcaLogisticRegressionBinary; case BinaryClassificationTrainer.SgdCalibrated: return TrainerName.SgdCalibratedBinary; case BinaryClassificationTrainer.SymbolicSgdLogisticRegression: return TrainerName.SymbolicSgdLogisticRegressionBinary; } // never expected to reach here throw new NotSupportedException($"{binaryTrainer} not supported"); } public static TrainerName GetTrainerName(MulticlassClassificationTrainer multiTrainer) { switch (multiTrainer) { case MulticlassClassificationTrainer.AveragedPerceptronOva: return TrainerName.AveragedPerceptronOva; case MulticlassClassificationTrainer.FastForestOva: return TrainerName.FastForestOva; case MulticlassClassificationTrainer.FastTreeOva: return TrainerName.FastTreeOva; case MulticlassClassificationTrainer.LightGbm: return TrainerName.LightGbmMulti; case MulticlassClassificationTrainer.LinearSupportVectorMachinesOva: return TrainerName.LinearSvmOva; case MulticlassClassificationTrainer.LbfgsMaximumEntropy: return TrainerName.LbfgsMaximumEntropyMulti; case MulticlassClassificationTrainer.LbfgsLogisticRegressionOva: return TrainerName.LbfgsLogisticRegressionOva; case MulticlassClassificationTrainer.SdcaMaximumEntropy: return TrainerName.SdcaMaximumEntropyMulti; case MulticlassClassificationTrainer.SgdCalibratedOva: return TrainerName.SgdCalibratedOva; case MulticlassClassificationTrainer.SymbolicSgdLogisticRegressionOva: return TrainerName.SymbolicSgdLogisticRegressionOva; } // never expected to reach here throw new NotSupportedException($"{multiTrainer} not supported"); } public static TrainerName GetTrainerName(RegressionTrainer regressionTrainer) { switch (regressionTrainer) { case RegressionTrainer.FastForest: return TrainerName.FastForestRegression; case RegressionTrainer.FastTree: return TrainerName.FastTreeRegression; case RegressionTrainer.FastTreeTweedie: return TrainerName.FastTreeTweedieRegression; case RegressionTrainer.LightGbm: return TrainerName.LightGbmRegression; case RegressionTrainer.OnlineGradientDescent: return TrainerName.OnlineGradientDescentRegression; case RegressionTrainer.Ols: return TrainerName.OlsRegression; case RegressionTrainer.LbfgsPoissonRegression: return TrainerName.LbfgsPoissonRegression; case RegressionTrainer.StochasticDualCoordinateAscent: return TrainerName.SdcaRegression; } // never expected to reach here throw new NotSupportedException($"{regressionTrainer} not supported"); } public static TrainerName GetTrainerName(RecommendationTrainer recommendationTrainer) { switch (recommendationTrainer) { case RecommendationTrainer.MatrixFactorization: return TrainerName.MatrixFactorization; } // never expected to reach here throw new NotSupportedException($"{recommendationTrainer} not supported"); } public static IEnumerable<TrainerName> GetTrainerNames(IEnumerable<BinaryClassificationTrainer> binaryTrainers) { return binaryTrainers?.Select(t => GetTrainerName(t)); } public static IEnumerable<TrainerName> GetTrainerNames(IEnumerable<MulticlassClassificationTrainer> multiTrainers) { return multiTrainers?.Select(t => GetTrainerName(t)); } public static IEnumerable<TrainerName> GetTrainerNames(IEnumerable<RegressionTrainer> regressionTrainers) { return regressionTrainers?.Select(t => GetTrainerName(t)); } public static IEnumerable<TrainerName> GetTrainerNames(IEnumerable<RecommendationTrainer> recommendationTrainers) { return recommendationTrainers?.Select(t => GetTrainerName(t)); } } }
43.537713
164
0.598525
[ "MIT" ]
AhmedsafwatEwida/machinelearning
src/Microsoft.ML.AutoML/TrainerExtensions/TrainerExtensionUtil.cs
17,896
C#
namespace _01.FriendsOfPesho { using System; using System.Collections.Generic; using System.Linq; public class PriorityQueue<T> { private SortedSet<T> items; public PriorityQueue() { this.items = new SortedSet<T>(); } public int Count { get { return items.Count; } } public void Enqueue(T element) { this.items.Add(element); } public T Dequeue() { var minNode = this.items.Min; this.items.Remove(minNode); return minNode; } public void Remove(T element) { this.items.Remove(element); } } }
18.404762
44
0.469599
[ "Apache-2.0" ]
iliantrifonov/TelerikAcademy
DataStructuresAndAlgorithms/11.GraphsAndGraphAlgorithms/01.FriendsOfPesho/PriorityQueue.cs
775
C#
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // 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. #endregion namespace Grpc.AspNetCore.FunctionalTests.Infrastructure { public enum TestServerEndpointName { Http2, Http1, Http2WithTls, Http1WithTls } }
28.62069
75
0.724096
[ "Apache-2.0" ]
Erguotou/grpc-dotnet
test/FunctionalTests/Infrastructure/TestServerEndpointName.cs
832
C#
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information. namespace Remote.Linq { using Aqua.TypeExtensions; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; partial class MethodInfos { internal static class Queryable { internal static readonly MethodInfo AsQueryable = GetQueryableMethod( nameof(System.Linq.Queryable.AsQueryable), typeof(IEnumerable<TSource>)); internal static readonly MethodInfo OrderBy = GetQueryableMethod( nameof(System.Linq.Queryable.OrderBy), new[] { typeof(TSource), typeof(TKey) }, typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, TKey>>)); internal static readonly MethodInfo OrderByDescending = GetQueryableMethod( nameof(System.Linq.Queryable.OrderByDescending), new[] { typeof(TSource), typeof(TKey) }, typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, TKey>>)); internal static readonly MethodInfo ThenBy = GetQueryableMethod( nameof(System.Linq.Queryable.ThenBy), new[] { typeof(TSource), typeof(TKey) }, typeof(IOrderedQueryable<TSource>), typeof(Expression<Func<TSource, TKey>>)); internal static readonly MethodInfo ThenByDescending = GetQueryableMethod( nameof(System.Linq.Queryable.ThenByDescending), new[] { typeof(TSource), typeof(TKey) }, typeof(IOrderedQueryable<TSource>), typeof(Expression<Func<TSource, TKey>>)); internal static readonly MethodInfo Aggregate = GetQueryableMethod( nameof(System.Linq.Queryable.Aggregate), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, TSource, TSource>>)); internal static readonly MethodInfo AggregateWithSeed = GetQueryableMethod( nameof(System.Linq.Queryable.Aggregate), new[] { typeof(TSource), typeof(TAccumulate) }, typeof(IQueryable<TSource>), typeof(TAccumulate), typeof(Expression<Func<TAccumulate, TSource, TAccumulate>>)); internal static readonly MethodInfo AggregateWithSeedAndSelector = GetQueryableMethod( nameof(System.Linq.Queryable.Aggregate), new[] { typeof(TSource), typeof(TAccumulate), typeof(TResult) }, typeof(IQueryable<TSource>), typeof(TAccumulate), typeof(Expression<Func<TAccumulate, TSource, TAccumulate>>), typeof(Expression<Func<TAccumulate, TResult>>)); internal static readonly MethodInfo All = GetQueryableMethod( nameof(System.Linq.Queryable.All), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo Any = GetQueryableMethod( nameof(System.Linq.Queryable.Any), typeof(IQueryable<TSource>)); internal static readonly MethodInfo AnyWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.Any), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo AverageInt32 = GetAverage<int>(); internal static readonly MethodInfo AverageNullableInt32 = GetAverage<int?>(); internal static readonly MethodInfo AverageInt64 = GetAverage<long>(); internal static readonly MethodInfo AverageNullableInt64 = GetAverage<long?>(); internal static readonly MethodInfo AverageSingle = GetAverage<float>(); internal static readonly MethodInfo AverageNullableSingle = GetAverage<float?>(); internal static readonly MethodInfo AverageDouble = GetAverage<double>(); internal static readonly MethodInfo AverageNullableDouble = GetAverage<double?>(); internal static readonly MethodInfo AverageDecimal = GetAverage<decimal>(); internal static readonly MethodInfo AverageNullableDecimal = GetAverage<decimal?>(); internal static readonly MethodInfo AverageInt32WithSelector = GetAverageWithSelector<int>(); internal static readonly MethodInfo AverageNullableInt32WithSelector = GetAverageWithSelector<int?>(); internal static readonly MethodInfo AverageSingleWithSelector = GetAverageWithSelector<float>(); internal static readonly MethodInfo AverageNullableSingleWithSelector = GetAverageWithSelector<float?>(); internal static readonly MethodInfo AverageInt64WithSelector = GetAverageWithSelector<long>(); internal static readonly MethodInfo AverageNullableInt64WithSelector = GetAverageWithSelector<long?>(); internal static readonly MethodInfo AverageDoubleWithSelector = GetAverageWithSelector<double>(); internal static readonly MethodInfo AverageNullableDoubleWithSelector = GetAverageWithSelector<double?>(); internal static readonly MethodInfo AverageDecimalWithSelector = GetAverageWithSelector<decimal>(); internal static readonly MethodInfo AverageNullableDecimalWithSelector = GetAverageWithSelector<decimal?>(); internal static readonly MethodInfo ContainsWithComparer = GetQueryableMethod( nameof(System.Linq.Queryable.Contains), typeof(IQueryable<TSource>), typeof(TSource), typeof(IEqualityComparer<TSource>)); internal static readonly MethodInfo Contains = GetQueryableMethod( nameof(System.Linq.Queryable.Contains), typeof(IQueryable<TSource>), typeof(TSource)); internal static readonly MethodInfo CountWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.Count), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo Count = GetQueryableMethod( nameof(System.Linq.Queryable.Count), typeof(IQueryable<TSource>)); internal static readonly MethodInfo ElementAt = GetQueryableMethod( nameof(System.Linq.Queryable.ElementAt), typeof(IQueryable<TSource>), typeof(int)); internal static readonly MethodInfo ElementAtOrDefault = GetQueryableMethod( nameof(System.Linq.Queryable.ElementAtOrDefault), typeof(IQueryable<TSource>), typeof(int)); internal static readonly MethodInfo First = GetQueryableMethod( nameof(System.Linq.Queryable.First), typeof(IQueryable<TSource>)); internal static readonly MethodInfo FirstWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.First), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo FirstOrDefaultWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.FirstOrDefault), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo FirstOrDefault = GetQueryableMethod( nameof(System.Linq.Queryable.FirstOrDefault), typeof(IQueryable<TSource>)); internal static readonly MethodInfo Last = GetQueryableMethod( nameof(System.Linq.Queryable.Last), typeof(IQueryable<TSource>)); internal static readonly MethodInfo LastWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.Last), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo LastOrDefault = GetQueryableMethod( nameof(System.Linq.Queryable.LastOrDefault), typeof(IQueryable<TSource>)); internal static readonly MethodInfo LastOrDefaultWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.LastOrDefault), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo LongCountWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.LongCount), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo LongCount = GetQueryableMethod( nameof(System.Linq.Queryable.LongCount), typeof(IQueryable<TSource>)); internal static readonly MethodInfo MaxWithSelector = GetQueryableMethod( nameof(System.Linq.Queryable.Max), new[] { typeof(TSource), typeof(TResult) }, typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, TResult>>)); internal static readonly MethodInfo Max = GetQueryableMethod( nameof(System.Linq.Queryable.Max), typeof(IQueryable<TSource>)); internal static readonly MethodInfo MinWithSelector = GetQueryableMethod( nameof(System.Linq.Queryable.Min), new[] { typeof(TSource), typeof(TResult) }, typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, TResult>>)); internal static readonly MethodInfo Min = GetQueryableMethod( nameof(System.Linq.Queryable.Min), typeof(IQueryable<TSource>)); internal static readonly MethodInfo SequenceEqualWithComparer = GetQueryableMethod( nameof(System.Linq.Queryable.SequenceEqual), typeof(IQueryable<TSource>), typeof(IEnumerable<TSource>), typeof(IEqualityComparer<TSource>)); internal static readonly MethodInfo SequenceEqual = GetQueryableMethod( nameof(System.Linq.Queryable.SequenceEqual), typeof(IQueryable<TSource>), typeof(IEnumerable<TSource>)); internal static readonly MethodInfo SingleWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.Single), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo Single = GetQueryableMethod( nameof(System.Linq.Queryable.Single), typeof(IQueryable<TSource>)); internal static readonly MethodInfo SingleOrDefault = GetQueryableMethod( nameof(System.Linq.Queryable.SingleOrDefault), typeof(IQueryable<TSource>)); internal static readonly MethodInfo SingleOrDefaultWithPredicate = GetQueryableMethod( nameof(System.Linq.Queryable.SingleOrDefault), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, bool>>)); internal static readonly MethodInfo SumWithInt32Selector = GetSumWithSelector<int>(); internal static readonly MethodInfo SumWithNullableInt32Selector = GetSumWithSelector<int?>(); internal static readonly MethodInfo SumWithInt64Selector = GetSumWithSelector<long>(); internal static readonly MethodInfo SumWithNullableInt64Selector = GetSumWithSelector<long?>(); internal static readonly MethodInfo SumWithSingleSelector = GetSumWithSelector<float>(); internal static readonly MethodInfo SumWithNullableSingleSelector = GetSumWithSelector<float?>(); internal static readonly MethodInfo SumWithDoubleSelector = GetSumWithSelector<double>(); internal static readonly MethodInfo SumWithNullableDoubleSelector = GetSumWithSelector<double?>(); internal static readonly MethodInfo SumWithDecimalSelector = GetSumWithSelector<decimal>(); internal static readonly MethodInfo SumWithNullableDecimalSelector = GetSumWithSelector<decimal?>(); internal static readonly MethodInfo SumInt32 = GetSum<int>(); internal static readonly MethodInfo SumNullableInt32 = GetSum<int?>(); internal static readonly MethodInfo SumInt64 = GetSum<long>(); internal static readonly MethodInfo SumNullableInt64 = GetSum<long?>(); internal static readonly MethodInfo SumSingle = GetSum<float>(); internal static readonly MethodInfo SumNullableSingle = GetSum<float?>(); internal static readonly MethodInfo SumDouble = GetSum<double>(); internal static readonly MethodInfo SumNullableDouble = GetSum<double?>(); internal static readonly MethodInfo SumDecimal = GetSum<decimal>(); internal static readonly MethodInfo SumNullableDecimal = GetSum<decimal?>(); internal static readonly MethodInfo Select = GetQueryableMethod( nameof(System.Linq.Queryable.Select), new[] { typeof(TSource), typeof(TResult) }, typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, TResult>>)); private static MethodInfo GetAverage<T>() => GetQueryableMethod( nameof(System.Linq.Queryable.Average), Array.Empty<Type>(), typeof(IQueryable<T>)); private static MethodInfo GetAverageWithSelector<T>() => GetQueryableMethod( nameof(System.Linq.Queryable.Average), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, T>>)); private static MethodInfo GetSum<T>() => GetQueryableMethod( nameof(System.Linq.Queryable.Sum), Array.Empty<Type>(), typeof(IQueryable<T>)); private static MethodInfo GetSumWithSelector<T>() => GetQueryableMethod( nameof(System.Linq.Queryable.Sum), typeof(IQueryable<TSource>), typeof(Expression<Func<TSource, T>>)); private static MethodInfo GetQueryableMethod(string name, params Type[] parameterTypes) => GetQueryableMethod(name, new[] { typeof(TSource) }, parameterTypes); private static MethodInfo GetQueryableMethod(string name, Type[] genericArgumentTypes, params Type[] parameterTypes) => typeof(System.Linq.Queryable).GetMethodEx(name, genericArgumentTypes, parameterTypes); } } }
53.774194
128
0.647071
[ "MIT" ]
6bee/Remote.Linq
src/Remote.Linq/MethodInfos.Queryable.cs
15,005
C#
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("StructureMap.Integrations.Owin.WebApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StructureMap.Integrations.Owin.WebApi")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("2ed7e760-e989-413a-b19c-1daf26efbf34")] // 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("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.081081
85
0.731625
[ "MIT" ]
benfoster/StructureMap.Integrations
src/StructureMap.Integrations.Owin.WebApi/Properties/AssemblyInfo.cs
1,486
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Bindings; using Microsoft.Azure.WebJobs.Host.Bindings; using Microsoft.Azure.WebJobs.Host.Executors; using Microsoft.Azure.WebJobs.Host.Listeners; using Microsoft.Azure.WebJobs.Host.Protocols; using Microsoft.Azure.WebJobs.Host.Triggers; namespace Sample.Extension { internal class SampleTriggerAttributeBindingProvider : ITriggerBindingProvider { public Task<ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { if (context == null) { throw new ArgumentNullException("context"); } ParameterInfo parameter = context.Parameter; SampleTriggerAttribute attribute = parameter.GetCustomAttribute<SampleTriggerAttribute>(inherit: false); if (attribute == null) { return Task.FromResult<ITriggerBinding>(null); } // TODO: Define the types your binding supports here if (parameter.ParameterType != typeof(SampleTriggerValue) && parameter.ParameterType != typeof(string)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Can't bind SampleTriggerAttribute to type '{0}'.", parameter.ParameterType)); } return Task.FromResult<ITriggerBinding>(new SampleTriggerBinding(context.Parameter)); } private class SampleTriggerBinding : ITriggerBinding { private readonly ParameterInfo _parameter; private readonly IReadOnlyDictionary<string, Type> _bindingContract; public SampleTriggerBinding(ParameterInfo parameter) { _parameter = parameter; _bindingContract = CreateBindingDataContract(); } public IReadOnlyDictionary<string, Type> BindingDataContract { get { return _bindingContract; } } public Type TriggerValueType { get { return typeof(SampleTriggerValue); } } public Task<ITriggerData> BindAsync(object value, ValueBindingContext context) { // TODO: Perform any required conversions on the value // E.g. convert from Dashboard invoke string to our trigger // value type SampleTriggerValue triggerValue = value as SampleTriggerValue; IValueBinder valueBinder = new SampleValueBinder(_parameter, triggerValue); return Task.FromResult<ITriggerData>(new TriggerData(valueBinder, GetBindingData(triggerValue))); } public Task<IListener> CreateListenerAsync(ListenerFactoryContext context) { return Task.FromResult<IListener>(new Listener(context.Executor)); } public ParameterDescriptor ToParameterDescriptor() { return new SampleTriggerParameterDescriptor { Name = _parameter.Name, DisplayHints = new ParameterDisplayHints { // TODO: Customize your Dashboard display strings Prompt = "Sample", Description = "Sample trigger fired", DefaultValue = "Sample" } }; } private IReadOnlyDictionary<string, object> GetBindingData(SampleTriggerValue value) { Dictionary<string, object> bindingData = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); bindingData.Add("SampleTrigger", value); // TODO: Add any additional binding data return bindingData; } private IReadOnlyDictionary<string, Type> CreateBindingDataContract() { Dictionary<string, Type> contract = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); contract.Add("SampleTrigger", typeof(SampleTriggerValue)); // TODO: Add any additional binding contract members return contract; } private class SampleTriggerParameterDescriptor : TriggerParameterDescriptor { public override string GetTriggerReason(IDictionary<string, string> arguments) { // TODO: Customize your Dashboard display string return string.Format("Sample trigger fired at {0}", DateTime.Now.ToString("o")); } } private class SampleValueBinder : ValueBinder { private readonly object _value; public SampleValueBinder(ParameterInfo parameter, SampleTriggerValue value) : base(parameter.ParameterType) { _value = value; } public override Task<object> GetValueAsync() { // TODO: Perform any required conversions if (Type == typeof(string)) { return Task.FromResult<object>(_value.ToString()); } return Task.FromResult(_value); } public override string ToInvokeString() { // TODO: Customize your Dashboard invoke string return "Sample"; } } private class Listener : IListener { private ITriggeredFunctionExecutor _executor; private System.Timers.Timer _timer; public Listener(ITriggeredFunctionExecutor executor) { _executor = executor; // TODO: For this sample, we're using a timer to generate // trigger events. You'll replace this with your event source. _timer = new System.Timers.Timer(5 * 1000) { AutoReset = true }; _timer.Elapsed += OnTimer; } public Task StartAsync(CancellationToken cancellationToken) { // TODO: Start monitoring your event source _timer.Start(); return Task.FromResult(true); } public Task StopAsync(CancellationToken cancellationToken) { // TODO: Stop monitoring your event source _timer.Stop(); return Task.FromResult(true); } public void Dispose() { // TODO: Perform any final cleanup _timer.Dispose(); } public void Cancel() { // TODO: cancel any outstanding tasks initiated by this listener } private void OnTimer(object sender, System.Timers.ElapsedEventArgs e) { // TODO: When you receive new events from your event source, // invoke the function executor TriggeredFunctionData input = new TriggeredFunctionData { TriggerValue = new SampleTriggerValue() }; _executor.TryExecuteAsync(input, CancellationToken.None).Wait(); } } } } }
38.218009
122
0.552207
[ "MIT" ]
david-driscoll/azure-webjobs-sdk-extensions
src/Sample.Extension/SampleTriggerAttributeBindingProvider.cs
8,066
C#
namespace Fabric.Terminology.API.Logging { using System.IO; using Fabric.Terminology.API.Configuration; using Serilog; using Serilog.Core; /// <summary> /// Responsible for creating the <see cref="ILogger"/> /// </summary> /// <remarks> /// This class should be removed with Fabric.Platform logging has been finalized. /// </remarks> internal class LogFactory { public static ILogger CreateTraceLogger(LoggingLevelSwitch levelSwitch, ApplicationInsightsSettings appInsightsConfig) { var loggerConfiguration = CreateLoggerConfiguration(levelSwitch); if (appInsightsConfig != null && appInsightsConfig.Enabled && !string.IsNullOrEmpty(appInsightsConfig.InstrumentationKey)) { loggerConfiguration.WriteTo.ApplicationInsightsTraces(appInsightsConfig.InstrumentationKey); } return loggerConfiguration.CreateLogger(); } public static ILogger CreateEventLogger(LoggingLevelSwitch levelSwitch, ApplicationInsightsSettings appInsightsConfig) { var loggerConfiguration = CreateLoggerConfiguration(levelSwitch); if (appInsightsConfig != null && appInsightsConfig.Enabled && !string.IsNullOrEmpty(appInsightsConfig.InstrumentationKey)) { loggerConfiguration.WriteTo.ApplicationInsightsEvents(appInsightsConfig.InstrumentationKey); } return loggerConfiguration.CreateLogger(); } private static LoggerConfiguration CreateLoggerConfiguration(LoggingLevelSwitch levelSwitch) => new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .Enrich.FromLogContext() .WriteTo.ColoredConsole() .WriteTo.RollingFile(Path.Combine("Logs", "fabric-terminology-{Date}.txt")); } }
37.960784
126
0.667872
[ "Apache-2.0" ]
HealthCatalyst/Fabric.Terminology
Fabric.Terminology.API/Logging/LogFactory.cs
1,936
C#
using Microsoft.Xna.Framework; namespace Pentacorn.Vision.Graphics { interface IRenderable { void Render(object obj, Matrix view, Matrix projection); } }
17.6
64
0.698864
[ "MIT" ]
JaapSuter/Pentacorn
Backup/Nuke/Graphics/IRenderable.cs
178
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014 Ingo Herbote * http://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ namespace YAF.Core.Services.Cache { using YAF.Types.Attributes; using YAF.Types.Constants; using YAF.Types.EventProxies; using YAF.Types.Extensions; using YAF.Types.Interfaces; /// <summary> /// The attachment event handle file delete. /// </summary> [ExportService(ServiceLifetimeScope.OwnedByContainer)] public class NewUserClearActiveLazyEvent : IHandleEvent<NewUserRegisteredEvent> { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="NewUserClearActiveLazyEvent"/> class. /// </summary> /// <param name="dataCache"> /// The data cache. /// </param> public NewUserClearActiveLazyEvent(IDataCache dataCache) { this.DataCache = dataCache; } #endregion #region Public Properties /// <summary> /// Gets or sets the data cache. /// </summary> public IDataCache DataCache { get; set; } /// <summary> /// Gets the order. /// </summary> public int Order { get { return 10000; } } #endregion #region Public Methods and Operators /// <summary> /// The handle. /// </summary> /// <param name="event"> /// The event. /// </param> public void Handle(NewUserRegisteredEvent @event) { this.DataCache.Remove(Constants.Cache.ActiveUserLazyData.FormatWith(@event.UserId)); this.DataCache.Remove(Constants.Cache.ForumActiveDiscussions); } #endregion } }
31.258427
97
0.608555
[ "Apache-2.0" ]
azarbara/YAFNET
yafsrc/YAF.Core/Services/Cache/NewUserClearActiveLazyEvent.cs
2,695
C#
// ************************************************************************************* // SCICHART® Copyright SciChart Ltd. 2011-2021. All rights reserved. // // Web: http://www.scichart.com // Support: support@scichart.com // Sales: sales@scichart.com // // ChartTypeViewModel.cs is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. // ************************************************************************************* using System; using System.Collections.Generic; using SciChart.Charting.Model.ChartSeries; using SciChart.Charting.Visuals.RenderableSeries; using SciChart.Examples.ExternalDependencies.Common; namespace SciChart.Examples.Examples.CreateMultiseriesChart.DashboardStyleCharts { public class ChartTypeViewModel : BaseViewModel { private string _typeName; private bool _isOneHundredPercent; private readonly bool _isSideBySide; public ChartTypeViewModel(IEnumerable<IRenderableSeriesViewModel> rSeriesViewModels, Type type, bool isOneHundredPercent, bool isSideBySide) { RenderableSeriesViewModels = rSeriesViewModels; _isOneHundredPercent = isOneHundredPercent; _isSideBySide = isSideBySide; _typeName = GenerateChartName(type); } #region Properties public IEnumerable<IRenderableSeriesViewModel> RenderableSeriesViewModels { get; set; } public string TypeName { get { return _typeName; } set { _typeName = value; OnPropertyChanged("TypeName"); } } public bool IsOneHundredPercent { get { return _isOneHundredPercent; } set { _isOneHundredPercent = value; OnPropertyChanged("TypeName"); } } public bool IsSideBySide { get { return _isSideBySide; } } public string AxisFormatting { get { return _isOneHundredPercent ? "#0'%'" : ""; } } #endregion private string GenerateChartName(Type type) { string result = _isOneHundredPercent ? "100% " : ""; if (type == typeof (IStackedColumnRenderableSeries)) { result += "Stacked columns"; if (_isSideBySide) { result += " side-by-side"; } } else { result += "Stacked mountains"; } return result; } } }
31.946237
148
0.564793
[ "MIT" ]
SHAREVIEW/SciChart.Wpf.Examples
Examples/SciChart.Examples/Examples/CreateMultiseriesChart/DashboardStyleCharts/ChartTypeViewModel.cs
2,976
C#
using System.ComponentModel.DataAnnotations; namespace CharlieBackend.Panel.Models.Mentor { public class MentorViewModel { [Required] public long Id { get; set; } [Required] [EmailAddress] [StringLength(50)] public string Email { get; set; } [Required] [StringLength(30)] public string FirstName { get; set; } [Required] [StringLength(30)] public string LastName { get; set; } public bool IsActive { get; set; } } }
20.692308
45
0.576208
[ "MIT" ]
ViktorMarhitich/WhatBackend
CharlieBackend.Panel/Models/Mentor/MentorViewModel.cs
540
C#
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("GSMultiManagerConfig")] [assembly: AssemblyDescription("GS Multi Manager Configuration Tool")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Schneider Electric")] [assembly: AssemblyProduct("GSMultiManagerConfig")] [assembly: AssemblyCopyright("Copyright © Schneider Electric 2022")] [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("f7f0949e-1b8a-418c-b7f7-aff5f2102fa2")] // 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("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.108108
84
0.756065
[ "MIT" ]
GeoSCADA/GSMultiManager
GSMultiManagerConfig/Properties/AssemblyInfo.cs
1,487
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class UnityEngineCanvasGroupWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(UnityEngine.CanvasGroup); Utils.BeginObjectRegister(type, L, translator, 0, 1, 4, 4); Utils.RegisterFunc(L, Utils.METHOD_IDX, "IsRaycastLocationValid", _m_IsRaycastLocationValid); Utils.RegisterFunc(L, Utils.GETTER_IDX, "alpha", _g_get_alpha); Utils.RegisterFunc(L, Utils.GETTER_IDX, "interactable", _g_get_interactable); Utils.RegisterFunc(L, Utils.GETTER_IDX, "blocksRaycasts", _g_get_blocksRaycasts); Utils.RegisterFunc(L, Utils.GETTER_IDX, "ignoreParentGroups", _g_get_ignoreParentGroups); Utils.RegisterFunc(L, Utils.SETTER_IDX, "alpha", _s_set_alpha); Utils.RegisterFunc(L, Utils.SETTER_IDX, "interactable", _s_set_interactable); Utils.RegisterFunc(L, Utils.SETTER_IDX, "blocksRaycasts", _s_set_blocksRaycasts); Utils.RegisterFunc(L, Utils.SETTER_IDX, "ignoreParentGroups", _s_set_ignoreParentGroups); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { UnityEngine.CanvasGroup gen_ret = new UnityEngine.CanvasGroup(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to UnityEngine.CanvasGroup constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_IsRaycastLocationValid(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); { UnityEngine.Vector2 _sp;translator.Get(L, 2, out _sp); UnityEngine.Camera _eventCamera = (UnityEngine.Camera)translator.GetObject(L, 3, typeof(UnityEngine.Camera)); bool gen_ret = gen_to_be_invoked.IsRaycastLocationValid( _sp, _eventCamera ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_alpha(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushnumber(L, gen_to_be_invoked.alpha); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_interactable(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushboolean(L, gen_to_be_invoked.interactable); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_blocksRaycasts(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushboolean(L, gen_to_be_invoked.blocksRaycasts); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_ignoreParentGroups(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushboolean(L, gen_to_be_invoked.ignoreParentGroups); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_alpha(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); gen_to_be_invoked.alpha = (float)LuaAPI.lua_tonumber(L, 2); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_interactable(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); gen_to_be_invoked.interactable = LuaAPI.lua_toboolean(L, 2); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_blocksRaycasts(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); gen_to_be_invoked.blocksRaycasts = LuaAPI.lua_toboolean(L, 2); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_ignoreParentGroups(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.CanvasGroup gen_to_be_invoked = (UnityEngine.CanvasGroup)translator.FastGetCSObj(L, 1); gen_to_be_invoked.ignoreParentGroups = LuaAPI.lua_toboolean(L, 2); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 0; } } }
35.3125
129
0.593274
[ "Apache-2.0" ]
IdolMenendez/KSFramework
KSFramework/Assets/XLua/Gen/UnityEngine_CanvasGroupWrap.cs
8,477
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Return the disk space being used. /// /// The response is either a GroupAnnouncementRepositoryGetSettingsResponse or an ErrorResponse. /// <see cref="GroupAnnouncementRepositoryGetSettingsResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""f3a93cf15de4abd7903673e44ee3e07b:2102""}]")] public class GroupAnnouncementRepositoryGetSettingsRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _serviceProviderId; [XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")] [Group(@"f3a93cf15de4abd7903673e44ee3e07b:2102")] [MinLength(1)] [MaxLength(30)] public string ServiceProviderId { get => _serviceProviderId; set { ServiceProviderIdSpecified = true; _serviceProviderId = value; } } [XmlIgnore] protected bool ServiceProviderIdSpecified { get; set; } private string _groupId; [XmlElement(ElementName = "groupId", IsNullable = false, Namespace = "")] [Group(@"f3a93cf15de4abd7903673e44ee3e07b:2102")] [MinLength(1)] [MaxLength(30)] public string GroupId { get => _groupId; set { GroupIdSpecified = true; _groupId = value; } } [XmlIgnore] protected bool GroupIdSpecified { get; set; } } }
29.730159
130
0.616658
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupAnnouncementRepositoryGetSettingsRequest.cs
1,873
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. namespace NuGet.Services.FeatureFlags { public interface IFeatureFlagClient { /// <summary> /// Get whether a feature is enabled. This method does not throw. /// </summary> /// <param name="feature">The unique identifier for this feature. This is case insensitive.</param> /// <param name="defaultValue">The value to return if the status of the feature is unknown.</param> /// <returns>Whether the feature is enabled.</returns> bool IsEnabled(string feature, bool defaultValue); /// <summary> /// Get whether a flight is enabled for a user. This method does not throw. /// </summary> /// <remarks> /// Enabling a flight for all users will include anonymous users. If the flight should never be /// enabled for logged out users, perform an "is logged in" check before calling this API. /// </remarks> /// <param name="flight">The unique identifier for this flight. This is case insensitive.</param> /// <param name="user">The user whose status should be determined, or null if the user is anonymous.</param> /// <param name="defaultValue">The value to return if the status of the flight is unknown.</param> /// <returns>Whether the flight is enabled for this user.</returns> bool IsEnabled(string flight, IFlightUser user, bool defaultValue); } }
52.666667
116
0.663291
[ "Apache-2.0" ]
NuGet/ServerCommon
src/NuGet.Services.FeatureFlags/IFeatureFlagClient.cs
1,582
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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; namespace System { // Provides Unix-based support for System.Console. // // NOTE: The test class reflects over this class to run the tests due to limitations in // the test infrastructure that prevent OS-specific builds of test binaries. If you // change any of the class / struct / function names, parameters, etc then you need // to also change the test class. internal static class ConsolePal { public static Stream OpenStandardInput() { return new UnixConsoleStream(SafeFileHandleHelper.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDIN_FILENO)), FileAccess.Read); } public static Stream OpenStandardOutput() { return new UnixConsoleStream(SafeFileHandleHelper.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDOUT_FILENO)), FileAccess.Write); } public static Stream OpenStandardError() { return new UnixConsoleStream(SafeFileHandleHelper.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDERR_FILENO)), FileAccess.Write); } public static Encoding InputEncoding { get { return GetConsoleEncoding(); } } public static Encoding OutputEncoding { get { return GetConsoleEncoding(); } } private static SyncTextReader s_stdInReader; private const int DefaultBufferSize = 255; private static SyncTextReader StdInReader { get { EnsureInitialized(); return Console.EnsureInitialized( ref s_stdInReader, () => SyncTextReader.GetSynchronizedTextReader( new StdInReader( encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream. bufferSize: DefaultBufferSize))); } } private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers internal static TextReader GetOrCreateReader() { if (Console.IsInputRedirected) { Stream inputStream = OpenStandardInput(); return SyncTextReader.GetSynchronizedTextReader( inputStream == Stream.Null ? StreamReader.Null : new StreamReader( stream: inputStream, encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream. detectEncodingFromByteOrderMarks: false, bufferSize: DefaultConsoleBufferSize, leaveOpen: true) ); } else { return StdInReader; } } public static bool KeyAvailable { get { return StdInReader.KeyAvailable; } } public static ConsoleKeyInfo ReadKey(bool intercept) { if (Console.IsInputRedirected) { // We could leverage Console.Read() here however // windows fails when stdin is redirected. throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile); } bool previouslyProcessed; ConsoleKeyInfo keyInfo = StdInReader.ReadKey(out previouslyProcessed); // Replace the '\n' char for Enter by '\r' to match Windows behavior. if (keyInfo.Key == ConsoleKey.Enter && keyInfo.KeyChar == '\n') { bool shift = (keyInfo.Modifiers & ConsoleModifiers.Shift) != 0; bool alt = (keyInfo.Modifiers & ConsoleModifiers.Alt) != 0; bool control = (keyInfo.Modifiers & ConsoleModifiers.Control) != 0; keyInfo = new ConsoleKeyInfo('\r', keyInfo.Key, shift, alt, control); } if (!intercept && !previouslyProcessed) Console.Write(keyInfo.KeyChar); return keyInfo; } public static bool TreatControlCAsInput { get { if (Console.IsInputRedirected) return false; EnsureInitialized(); return !Interop.Sys.GetSignalForBreak(); } set { if (!Console.IsInputRedirected) { EnsureInitialized(); if (!Interop.Sys.SetSignalForBreak(signalForBreak: !value)) throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo()); } } } private static ConsoleColor s_trackedForegroundColor = Console.UnknownColor; private static ConsoleColor s_trackedBackgroundColor = Console.UnknownColor; public static ConsoleColor ForegroundColor { get { return s_trackedForegroundColor; } set { RefreshColors(ref s_trackedForegroundColor, value); } } public static ConsoleColor BackgroundColor { get { return s_trackedBackgroundColor; } set { RefreshColors(ref s_trackedBackgroundColor, value); } } public static void ResetColor() { lock (Console.Out) // synchronize with other writers { s_trackedForegroundColor = Console.UnknownColor; s_trackedBackgroundColor = Console.UnknownColor; WriteResetColorString(); } } public static bool NumberLock { get { throw new PlatformNotSupportedException(); } } public static bool CapsLock { get { throw new PlatformNotSupportedException(); } } public static int CursorSize { get { return 100; } set { throw new PlatformNotSupportedException(); } } public static string Title { get { throw new PlatformNotSupportedException(); } set { if (Console.IsOutputRedirected) return; string titleFormat = TerminalFormatStrings.Instance.Title; if (!string.IsNullOrEmpty(titleFormat)) { string ansiStr = TermInfo.ParameterizedStrings.Evaluate(titleFormat, value); WriteStdoutAnsiString(ansiStr); } } } public static void Beep() { if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(TerminalFormatStrings.Instance.Bell); } } public static void Beep(int frequency, int duration) { throw new PlatformNotSupportedException(); } public static void Clear() { if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(TerminalFormatStrings.Instance.Clear); } } public static void SetCursorPosition(int left, int top) { if (Console.IsOutputRedirected) return; string cursorAddressFormat = TerminalFormatStrings.Instance.CursorAddress; if (!string.IsNullOrEmpty(cursorAddressFormat)) { string ansiStr = TermInfo.ParameterizedStrings.Evaluate(cursorAddressFormat, top, left); WriteStdoutAnsiString(ansiStr); } } public static int BufferWidth { get { return WindowWidth; } set { throw new PlatformNotSupportedException(); } } public static int BufferHeight { get { return WindowHeight; } set { throw new PlatformNotSupportedException(); } } public static void SetBufferSize(int width, int height) { throw new PlatformNotSupportedException(); } public static int LargestWindowWidth { get { return WindowWidth; } set { throw new PlatformNotSupportedException(); } } public static int LargestWindowHeight { get { return WindowHeight; } set { throw new PlatformNotSupportedException(); } } public static int WindowLeft { get { return 0; } set { throw new PlatformNotSupportedException(); } } public static int WindowTop { get { return 0; } set { throw new PlatformNotSupportedException(); } } public static int WindowWidth { get { Interop.Sys.WinSize winsize; return Interop.Sys.GetWindowSize(out winsize) == 0 ? winsize.Col : TerminalFormatStrings.Instance.Columns; } set { throw new PlatformNotSupportedException(); } } public static int WindowHeight { get { Interop.Sys.WinSize winsize; return Interop.Sys.GetWindowSize(out winsize) == 0 ? winsize.Row : TerminalFormatStrings.Instance.Lines; } set { throw new PlatformNotSupportedException(); } } public static void SetWindowPosition(int left, int top) { throw new PlatformNotSupportedException(); } public static void SetWindowSize(int width, int height) { throw new PlatformNotSupportedException(); } public static bool CursorVisible { get { throw new PlatformNotSupportedException(); } set { if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(value ? TerminalFormatStrings.Instance.CursorVisible : TerminalFormatStrings.Instance.CursorInvisible); } } } // TODO: It's quite expensive to use the request/response protocol each time CursorLeft/Top is accessed. // We should be able to (mostly) track the position of the cursor in locals, doing the request/response infrequently. public static int CursorLeft { get { int left, top; GetCursorPosition(out left, out top); return left; } } public static int CursorTop { get { int left, top; GetCursorPosition(out left, out top); return top; } } /// <summary>Gets the current cursor position. This involves both writing to stdout and reading stdin.</summary> private static unsafe void GetCursorPosition(out int left, out int top) { left = top = 0; // Getting the cursor position involves both writing out a request string and // parsing a response string from the terminal. So if anything is redirected, bail. if (Console.IsInputRedirected || Console.IsOutputRedirected) return; // Get the cursor position request format string. Debug.Assert(!string.IsNullOrEmpty(TerminalFormatStrings.CursorPositionReport)); // Synchronize with all other stdin readers. We need to do this in case multiple threads are // trying to read/write concurrently, and to minimize the chances of resulting conflicts. // This does mean that Console.get_CursorLeft/Top can't be used concurrently Console.Read*, etc.; // attempting to do so will block one of them until the other completes, but in doing so we prevent // one thread's get_CursorLeft/Top from providing input to the other's Console.Read*. lock (StdInReader) { Interop.Sys.InitializeConsoleBeforeRead(minChars: 0, decisecondsTimeout: 10); try { // Write out the cursor position report request. WriteStdoutAnsiString(TerminalFormatStrings.CursorPositionReport); // Read the cursor position report reponse, of the form \ESC[row;colR. There's a race // condition here if the user is typing, or if other threads are accessing the console; // to try to avoid losing such data, we push unexpected inputs into the stdin buffer, but // even with that, there's a potential that we could misinterpret data from the user as // being part of the cursor position response. This is inherent to the nature of the protocol. StdInReader r = StdInReader.Inner; byte b; while (true) // \ESC { if (r.ReadStdin(&b, 1) != 1) return; if (b == 0x1B) break; r.AppendExtraBuffer(&b, 1); } while (true) // [ { if (r.ReadStdin(&b, 1) != 1) return; if (b == '[') break; r.AppendExtraBuffer(&b, 1); } try { int row = 0; while (true) // row until ';' { if (r.ReadStdin(&b, 1) != 1) return; if (b == ';') break; if (IsDigit((char)b)) { row = checked((row * 10) + (b - '0')); } else { r.AppendExtraBuffer(&b, 1); } } if (row >= 1) top = row - 1; int col = 0; while (true) // col until 'R' { if (r.ReadStdin(&b, 1) == 0) return; if (b == 'R') break; if (IsDigit((char)b)) { col = checked((col * 10) + (b - '0')); } else { r.AppendExtraBuffer(&b, 1); } } if (col >= 1) left = col - 1; } catch (OverflowException) { return; } } finally { Interop.Sys.UninitializeConsoleAfterRead(); } } } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { throw new PlatformNotSupportedException(); } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { throw new PlatformNotSupportedException(); } /// <summary>Gets whether the specified character is a digit 0-9.</summary> private static bool IsDigit(char c) { return c >= '0' && c <= '9'; } /// <summary> /// Gets whether the specified file descriptor was redirected. /// It's considered redirected if it doesn't refer to a terminal. /// </summary> private static bool IsHandleRedirected(SafeFileHandle fd) { return !Interop.Sys.IsATty(fd); } /// <summary> /// Gets whether Console.In is redirected. /// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device. /// </summary> public static bool IsInputRedirectedCore() { return IsHandleRedirected(Interop.Sys.FileDescriptors.STDIN_FILENO); } /// <summary>Gets whether Console.Out is redirected. /// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device. /// </summary> public static bool IsOutputRedirectedCore() { return IsHandleRedirected(Interop.Sys.FileDescriptors.STDOUT_FILENO); } /// <summary>Gets whether Console.Error is redirected. /// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device. /// </summary> public static bool IsErrorRedirectedCore() { return IsHandleRedirected(Interop.Sys.FileDescriptors.STDERR_FILENO); } /// <summary>Creates an encoding from the current environment.</summary> /// <returns>The encoding.</returns> private static Encoding GetConsoleEncoding() { Encoding enc = EncodingHelper.GetEncodingFromCharset(); return enc ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); } public static void SetConsoleInputEncoding(Encoding enc) { // No-op. // There is no good way to set the terminal console encoding. } public static void SetConsoleOutputEncoding(Encoding enc) { // No-op. // There is no good way to set the terminal console encoding. } /// <summary> /// Refreshes the foreground and background colors in use by the terminal by resetting /// the colors and then reissuing commands for both foreground and background, if necessary. /// Before doing so, the <paramref name="toChange"/> ref is changed to <paramref name="value"/> /// if <paramref name="value"/> is valid. /// </summary> private static void RefreshColors(ref ConsoleColor toChange, ConsoleColor value) { if (((int)value & ~0xF) != 0 && value != Console.UnknownColor) { throw new ArgumentException(SR.Arg_InvalidConsoleColor); } lock (Console.Out) { toChange = value; // toChange is either s_trackedForegroundColor or s_trackedBackgroundColor WriteResetColorString(); if (s_trackedForegroundColor != Console.UnknownColor) { WriteSetColorString(foreground: true, color: s_trackedForegroundColor); } if (s_trackedBackgroundColor != Console.UnknownColor) { WriteSetColorString(foreground: false, color: s_trackedBackgroundColor); } } } /// <summary>Outputs the format string evaluated and parameterized with the color.</summary> /// <param name="foreground">true for foreground; false for background.</param> /// <param name="color">The color to store into the field and to use as an argument to the format string.</param> private static void WriteSetColorString(bool foreground, ConsoleColor color) { // Changing the color involves writing an ANSI character sequence out to the output stream. // We only want to do this if we know that sequence will be interpreted by the output. // rather than simply displayed visibly. if (Console.IsOutputRedirected) return; // See if we've already cached a format string for this foreground/background // and specific color choice. If we have, just output that format string again. int fgbgIndex = foreground ? 0 : 1; int ccValue = (int)color; string evaluatedString = s_fgbgAndColorStrings[fgbgIndex, ccValue]; // benign race if (evaluatedString != null) { WriteStdoutAnsiString(evaluatedString); return; } // We haven't yet computed a format string. Compute it, use it, then cache it. string formatString = foreground ? TerminalFormatStrings.Instance.Foreground : TerminalFormatStrings.Instance.Background; if (!string.IsNullOrEmpty(formatString)) { int maxColors = TerminalFormatStrings.Instance.MaxColors; // often 8 or 16; 0 is invalid if (maxColors > 0) { int ansiCode = _consoleColorToAnsiCode[ccValue] % maxColors; evaluatedString = TermInfo.ParameterizedStrings.Evaluate(formatString, ansiCode); WriteStdoutAnsiString(evaluatedString); s_fgbgAndColorStrings[fgbgIndex, ccValue] = evaluatedString; // benign race } } } /// <summary>Writes out the ANSI string to reset colors.</summary> private static void WriteResetColorString() { // We only want to send the reset string if we're targeting a TTY device if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(TerminalFormatStrings.Instance.Reset); } } /// <summary> /// The values of the ConsoleColor enums unfortunately don't map to the /// corresponding ANSI values. We need to do the mapping manually. /// See http://en.wikipedia.org/wiki/ANSI_escape_code#Colors /// </summary> private static readonly int[] _consoleColorToAnsiCode = new int[] { // Dark/Normal colors 0, // Black, 4, // DarkBlue, 2, // DarkGreen, 6, // DarkCyan, 1, // DarkRed, 5, // DarkMagenta, 3, // DarkYellow, 7, // Gray, // Bright colors 8, // DarkGray, 12, // Blue, 10, // Green, 14, // Cyan, 9, // Red, 13, // Magenta, 11, // Yellow, 15 // White }; /// <summary>Cache of the format strings for foreground/background and ConsoleColor.</summary> private static readonly string[,] s_fgbgAndColorStrings = new string[2, 16]; // 2 == fg vs bg, 16 == ConsoleColor values public static bool TryGetSpecialConsoleKey(char[] givenChars, int startIndex, int endIndex, out ConsoleKeyInfo key, out int keyLength) { int unprocessedCharCount = endIndex - startIndex; // First process special control character codes. These override anything from terminfo. if (unprocessedCharCount > 0) { // Is this an erase / backspace? char c = givenChars[startIndex]; if (c != s_posixDisableValue && c == s_veraseCharacter) { key = new ConsoleKeyInfo(c, ConsoleKey.Backspace, shift: false, alt: false, control: false); keyLength = 1; return true; } } // Then process terminfo mappings. int minRange = TerminalFormatStrings.Instance.MinKeyFormatLength; if (unprocessedCharCount >= minRange) { int maxRange = Math.Min(unprocessedCharCount, TerminalFormatStrings.Instance.MaxKeyFormatLength); for (int i = maxRange; i >= minRange; i--) { var currentString = new StringOrCharArray(givenChars, startIndex, i); // Check if the string prefix matches. if (TerminalFormatStrings.Instance.KeyFormatToConsoleKey.TryGetValue(currentString, out key)) { keyLength = currentString.Length; return true; } } } // Otherwise, not a known special console key. key = default(ConsoleKeyInfo); keyLength = 0; return false; } /// <summary>Whether keypad_xmit has already been written out to the terminal.</summary> private static volatile bool s_initialized; /// <summary>Value used to indicate that a special character code isn't available.</summary> internal static byte s_posixDisableValue; /// <summary>Special control character code used to represent an erase (backspace).</summary> private static byte s_veraseCharacter; /// <summary>Special control character that represents the end of a line.</summary> internal static byte s_veolCharacter; /// <summary>Special control character that represents the end of a line.</summary> internal static byte s_veol2Character; /// <summary>Special control character that represents the end of a file.</summary> internal static byte s_veofCharacter; /// <summary>Ensures that the console has been initialized for use.</summary> private static void EnsureInitialized() { if (!s_initialized) { EnsureInitializedCore(); // factored out for inlinability } } /// <summary>Ensures that the console has been initialized for use.</summary> private static void EnsureInitializedCore() { lock (Console.Out) // ensure that writing the ANSI string and setting initialized to true are done atomically { if (!s_initialized) { // Ensure the console is configured appropriately. This will start // signal handlers, etc. if (!Interop.Sys.InitializeConsole()) { throw new Win32Exception(); } // Provide the native lib with the correct code from the terminfo to transition us into // "application mode". This will both transition it immediately, as well as allow // the native lib later to handle signals that require re-entering the mode. if (!Console.IsOutputRedirected) { string keypadXmit = TerminalFormatStrings.Instance.KeypadXmit; if (keypadXmit != null) { Interop.Sys.SetKeypadXmit(keypadXmit); } } // Load special control character codes used for input processing var controlCharacterNames = new Interop.Sys.ControlCharacterNames[4] { Interop.Sys.ControlCharacterNames.VERASE, Interop.Sys.ControlCharacterNames.VEOL, Interop.Sys.ControlCharacterNames.VEOL2, Interop.Sys.ControlCharacterNames.VEOF }; var controlCharacterValues = new byte[controlCharacterNames.Length]; Interop.Sys.GetControlCharacters(controlCharacterNames, controlCharacterValues, controlCharacterNames.Length, out s_posixDisableValue); s_veraseCharacter = controlCharacterValues[0]; s_veolCharacter = controlCharacterValues[1]; s_veol2Character = controlCharacterValues[2]; s_veofCharacter = controlCharacterValues[3]; // Mark us as initialized s_initialized = true; } } } /// <summary>Provides format strings and related information for use with the current terminal.</summary> internal class TerminalFormatStrings { /// <summary>Gets the lazily-initialized terminal information for the terminal.</summary> public static TerminalFormatStrings Instance { get { return s_instance.Value; } } private static readonly Lazy<TerminalFormatStrings> s_instance = new Lazy<TerminalFormatStrings>(() => new TerminalFormatStrings(TermInfo.Database.ReadActiveDatabase())); /// <summary>The format string to use to change the foreground color.</summary> public readonly string Foreground; /// <summary>The format string to use to change the background color.</summary> public readonly string Background; /// <summary>The format string to use to reset the foreground and background colors.</summary> public readonly string Reset; /// <summary>The maximum number of colors supported by the terminal.</summary> public readonly int MaxColors; /// <summary>The number of columns in a format.</summary> public readonly int Columns; /// <summary>The number of lines in a format.</summary> public readonly int Lines; /// <summary>The format string to use to make cursor visible.</summary> public readonly string CursorVisible; /// <summary>The format string to use to make cursor invisible</summary> public readonly string CursorInvisible; /// <summary>The format string to use to set the window title.</summary> public readonly string Title; /// <summary>The format string to use for an audible bell.</summary> public readonly string Bell; /// <summary>The format string to use to clear the terminal.</summary> public readonly string Clear; /// <summary>The format string to use to set the position of the cursor.</summary> public readonly string CursorAddress; /// <summary>The format string to use to move the cursor to the left.</summary> public readonly string CursorLeft; /// <summary>The ANSI-compatible string for the Cursor Position report request.</summary> /// <remarks> /// This should really be in user string 7 in the terminfo file, but some terminfo databases /// are missing it. As this is defined to be supported by any ANSI-compatible terminal, /// we assume it's available; doing so means CursorTop/Left will work even if the terminfo database /// doesn't contain it (as appears to be the case with e.g. screen and tmux on Ubuntu), at the risk /// of outputting the sequence on some terminal that's not compatible. /// </remarks> public const string CursorPositionReport = "\x1B[6n"; /// <summary> /// The dictionary of keystring to ConsoleKeyInfo. /// Only some members of the ConsoleKeyInfo are used; in particular, the actual char is ignored. /// </summary> public readonly Dictionary<StringOrCharArray, ConsoleKeyInfo> KeyFormatToConsoleKey = new Dictionary<StringOrCharArray, ConsoleKeyInfo>(); /// <summary> Max key length </summary> public readonly int MaxKeyFormatLength; /// <summary> Min key length </summary> public readonly int MinKeyFormatLength; /// <summary>The ANSI string used to enter "application" / "keypad transmit" mode.</summary> public readonly string KeypadXmit; public TerminalFormatStrings(TermInfo.Database db) { if (db == null) return; KeypadXmit = db.GetString(TermInfo.WellKnownStrings.KeypadXmit); Foreground = db.GetString(TermInfo.WellKnownStrings.SetAnsiForeground); Background = db.GetString(TermInfo.WellKnownStrings.SetAnsiBackground); Reset = db.GetString(TermInfo.WellKnownStrings.OrigPairs) ?? db.GetString(TermInfo.WellKnownStrings.OrigColors); Bell = db.GetString(TermInfo.WellKnownStrings.Bell); Clear = db.GetString(TermInfo.WellKnownStrings.Clear); Columns = db.GetNumber(TermInfo.WellKnownNumbers.Columns); Lines = db.GetNumber(TermInfo.WellKnownNumbers.Lines); CursorVisible = db.GetString(TermInfo.WellKnownStrings.CursorVisible); CursorInvisible = db.GetString(TermInfo.WellKnownStrings.CursorInvisible); CursorAddress = db.GetString(TermInfo.WellKnownStrings.CursorAddress); CursorLeft = db.GetString(TermInfo.WellKnownStrings.CursorLeft); Title = GetTitle(db); Debug.WriteLineIf(db.GetString(TermInfo.WellKnownStrings.CursorPositionReport) != CursorPositionReport, "Getting the cursor position will only work if the terminal supports the CPR sequence," + "but the terminfo database does not contain an entry for it."); int maxColors = db.GetNumber(TermInfo.WellKnownNumbers.MaxColors); MaxColors = // normalize to either the full range of all ANSI colors, just the dark ones, or none maxColors >= 16 ? 16 : maxColors >= 8 ? 8 : 0; AddKey(db, TermInfo.WellKnownStrings.KeyF1, ConsoleKey.F1); AddKey(db, TermInfo.WellKnownStrings.KeyF2, ConsoleKey.F2); AddKey(db, TermInfo.WellKnownStrings.KeyF3, ConsoleKey.F3); AddKey(db, TermInfo.WellKnownStrings.KeyF4, ConsoleKey.F4); AddKey(db, TermInfo.WellKnownStrings.KeyF5, ConsoleKey.F5); AddKey(db, TermInfo.WellKnownStrings.KeyF6, ConsoleKey.F6); AddKey(db, TermInfo.WellKnownStrings.KeyF7, ConsoleKey.F7); AddKey(db, TermInfo.WellKnownStrings.KeyF8, ConsoleKey.F8); AddKey(db, TermInfo.WellKnownStrings.KeyF9, ConsoleKey.F9); AddKey(db, TermInfo.WellKnownStrings.KeyF10, ConsoleKey.F10); AddKey(db, TermInfo.WellKnownStrings.KeyF11, ConsoleKey.F11); AddKey(db, TermInfo.WellKnownStrings.KeyF12, ConsoleKey.F12); AddKey(db, TermInfo.WellKnownStrings.KeyF13, ConsoleKey.F13); AddKey(db, TermInfo.WellKnownStrings.KeyF14, ConsoleKey.F14); AddKey(db, TermInfo.WellKnownStrings.KeyF15, ConsoleKey.F15); AddKey(db, TermInfo.WellKnownStrings.KeyF16, ConsoleKey.F16); AddKey(db, TermInfo.WellKnownStrings.KeyF17, ConsoleKey.F17); AddKey(db, TermInfo.WellKnownStrings.KeyF18, ConsoleKey.F18); AddKey(db, TermInfo.WellKnownStrings.KeyF19, ConsoleKey.F19); AddKey(db, TermInfo.WellKnownStrings.KeyF20, ConsoleKey.F20); AddKey(db, TermInfo.WellKnownStrings.KeyF21, ConsoleKey.F21); AddKey(db, TermInfo.WellKnownStrings.KeyF22, ConsoleKey.F22); AddKey(db, TermInfo.WellKnownStrings.KeyF23, ConsoleKey.F23); AddKey(db, TermInfo.WellKnownStrings.KeyF24, ConsoleKey.F24); AddKey(db, TermInfo.WellKnownStrings.KeyBackspace, ConsoleKey.Backspace); AddKey(db, TermInfo.WellKnownStrings.KeyBackTab, ConsoleKey.Tab, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeyBegin, ConsoleKey.Home); AddKey(db, TermInfo.WellKnownStrings.KeyClear, ConsoleKey.Clear); AddKey(db, TermInfo.WellKnownStrings.KeyDelete, ConsoleKey.Delete); AddKey(db, TermInfo.WellKnownStrings.KeyDown, ConsoleKey.DownArrow); AddKey(db, TermInfo.WellKnownStrings.KeyEnd, ConsoleKey.End); AddKey(db, TermInfo.WellKnownStrings.KeyEnter, ConsoleKey.Enter); AddKey(db, TermInfo.WellKnownStrings.KeyHelp, ConsoleKey.Help); AddKey(db, TermInfo.WellKnownStrings.KeyHome, ConsoleKey.Home); AddKey(db, TermInfo.WellKnownStrings.KeyInsert, ConsoleKey.Insert); AddKey(db, TermInfo.WellKnownStrings.KeyLeft, ConsoleKey.LeftArrow); AddKey(db, TermInfo.WellKnownStrings.KeyPageDown, ConsoleKey.PageDown); AddKey(db, TermInfo.WellKnownStrings.KeyPageUp, ConsoleKey.PageUp); AddKey(db, TermInfo.WellKnownStrings.KeyPrint, ConsoleKey.Print); AddKey(db, TermInfo.WellKnownStrings.KeyRight, ConsoleKey.RightArrow); AddKey(db, TermInfo.WellKnownStrings.KeyScrollForward, ConsoleKey.PageDown, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeyScrollReverse, ConsoleKey.PageUp, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySBegin, ConsoleKey.Home, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySDelete, ConsoleKey.Delete, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySHome, ConsoleKey.Home, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySelect, ConsoleKey.Select); AddKey(db, TermInfo.WellKnownStrings.KeySLeft, ConsoleKey.LeftArrow, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySPrint, ConsoleKey.Print, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySRight, ConsoleKey.RightArrow, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeyUp, ConsoleKey.UpArrow); AddPrefixKey(db, "kLFT", ConsoleKey.LeftArrow); AddPrefixKey(db, "kRIT", ConsoleKey.RightArrow); AddPrefixKey(db, "kUP", ConsoleKey.UpArrow); AddPrefixKey(db, "kDN", ConsoleKey.DownArrow); AddPrefixKey(db, "kDC", ConsoleKey.Delete); AddPrefixKey(db, "kEND", ConsoleKey.End); AddPrefixKey(db, "kHOM", ConsoleKey.Home); AddPrefixKey(db, "kNXT", ConsoleKey.PageDown); AddPrefixKey(db, "kPRV", ConsoleKey.PageUp); if (KeyFormatToConsoleKey.Count > 0) { MaxKeyFormatLength = int.MinValue; MinKeyFormatLength = int.MaxValue; foreach (KeyValuePair<StringOrCharArray, ConsoleKeyInfo> entry in KeyFormatToConsoleKey) { if (entry.Key.Length > MaxKeyFormatLength) { MaxKeyFormatLength = entry.Key.Length; } if (entry.Key.Length < MinKeyFormatLength) { MinKeyFormatLength = entry.Key.Length; } } } } private static string GetTitle(TermInfo.Database db) { // Try to get the format string from tsl/fsl and use it if they're available string tsl = db.GetString(TermInfo.WellKnownStrings.ToStatusLine); string fsl = db.GetString(TermInfo.WellKnownStrings.FromStatusLine); if (tsl != null && fsl != null) { return tsl + "%p1%s" + fsl; } string term = db.Term; if (term == null) { return string.Empty; } if (term.StartsWith("xterm", StringComparison.Ordinal)) // normalize all xterms to enable easier matching { term = "xterm"; } switch (term) { case "aixterm": case "dtterm": case "linux": case "rxvt": case "xterm": return "\x1B]0;%p1%s\x07"; case "cygwin": return "\x1B];%p1%s\x07"; case "konsole": return "\x1B]30;%p1%s\x07"; case "screen": return "\x1Bk%p1%s\x1B"; default: return string.Empty; } } private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key) { AddKey(db, keyId, key, shift: false, alt: false, control: false); } private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key, bool shift, bool alt, bool control) { string keyFormat = db.GetString(keyId); if (!string.IsNullOrEmpty(keyFormat)) KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control); } private void AddPrefixKey(TermInfo.Database db, string extendedNamePrefix, ConsoleKey key) { AddKey(db, extendedNamePrefix + "3", key, shift: false, alt: true, control: false); AddKey(db, extendedNamePrefix + "4", key, shift: true, alt: true, control: false); AddKey(db, extendedNamePrefix + "5", key, shift: false, alt: false, control: true); AddKey(db, extendedNamePrefix + "6", key, shift: true, alt: false, control: true); AddKey(db, extendedNamePrefix + "7", key, shift: false, alt: false, control: true); } private void AddKey(TermInfo.Database db, string extendedName, ConsoleKey key, bool shift, bool alt, bool control) { string keyFormat = db.GetExtendedString(extendedName); if (!string.IsNullOrEmpty(keyFormat)) KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control); } } /// <summary>Reads data from the file descriptor into the buffer.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset at which to start writing into the buffer.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The number of bytes read, or a negative value if there's an error.</returns> internal static unsafe int Read(SafeFileHandle fd, byte[] buffer, int offset, int count) { fixed (byte* bufPtr = buffer) { int result = Interop.CheckIo(Interop.Sys.Read(fd, (byte*)bufPtr + offset, count)); Debug.Assert(result <= count); return result; } } /// <summary>Writes data from the buffer into the file descriptor.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="buffer">The buffer from which to write data.</param> /// <param name="offset">The offset at which the data to write starts in the buffer.</param> /// <param name="count">The number of bytes to write.</param> private static unsafe void Write(SafeFileHandle fd, byte[] buffer, int offset, int count) { fixed (byte* bufPtr = buffer) { Write(fd, bufPtr + offset, count); } } private static unsafe void Write(SafeFileHandle fd, byte* bufPtr, int count) { while (count > 0) { int bytesWritten = Interop.Sys.Write(fd, bufPtr, count); if (bytesWritten < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EPIPE) { // Broken pipe... likely due to being redirected to a program // that ended, so simply pretend we were successful. return; } else if (errorInfo.Error == Interop.Error.EAGAIN) // aka EWOULDBLOCK { // May happen if the file handle is configured as non-blocking. // In that case, we need to wait to be able to write and then // try again. We poll, but don't actually care about the result, // only the blocking behavior, and thus ignore any poll errors // and loop around to do another write (which may correctly fail // if something else has gone wrong). Interop.Sys.Poll(fd, Interop.Sys.PollEvents.POLLOUT, Timeout.Infinite, out Interop.Sys.PollEvents triggered); continue; } else { // Something else... fail. throw Interop.GetExceptionForIoErrno(errorInfo); } } count -= bytesWritten; bufPtr += bytesWritten; } } /// <summary>Writes a terminfo-based ANSI escape string to stdout.</summary> /// <param name="value">The string to write.</param> private static unsafe void WriteStdoutAnsiString(string value) { if (string.IsNullOrEmpty(value)) return; // Except for extremely rare cases, ANSI escape strings should be very short. const int StackAllocThreshold = 256; if (value.Length <= StackAllocThreshold) { int dataLen = Encoding.UTF8.GetMaxByteCount(value.Length); byte* data = stackalloc byte[dataLen]; fixed (char* chars = value) { int bytesToWrite = Encoding.UTF8.GetBytes(chars, value.Length, data, dataLen); Debug.Assert(bytesToWrite <= dataLen); lock (Console.Out) // synchronize with other writers { Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, bytesToWrite); } } } else { byte[] data = Encoding.UTF8.GetBytes(value); lock (Console.Out) // synchronize with other writers { Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, 0, data.Length); } } } /// <summary>Provides a stream to use for Unix console input or output.</summary> private sealed class UnixConsoleStream : ConsoleStream { /// <summary>The file descriptor for the opened file.</summary> private readonly SafeFileHandle _handle; /// <summary>The type of the underlying file descriptor.</summary> internal readonly int _handleType; /// <summary>Initialize the stream.</summary> /// <param name="handle">The file handle wrapped by this stream.</param> /// <param name="access">FileAccess.Read or FileAccess.Write.</param> internal UnixConsoleStream(SafeFileHandle handle, FileAccess access) : base(access) { Debug.Assert(handle != null, "Expected non-null console handle"); Debug.Assert(!handle.IsInvalid, "Expected valid console handle"); _handle = handle; // Determine the type of the descriptor (e.g. regular file, character file, pipe, etc.) Interop.Sys.FileStatus buf; _handleType = Interop.Sys.FStat(_handle, out buf) == 0 ? (buf.Mode & Interop.Sys.FileTypes.S_IFMT) : Interop.Sys.FileTypes.S_IFREG; // if something goes wrong, don't fail, just say it's a regular file } protected override void Dispose(bool disposing) { if (disposing) { _handle.Dispose(); } base.Dispose(disposing); } public override int Read(byte[] buffer, int offset, int count) { ValidateRead(buffer, offset, count); return ConsolePal.Read(_handle, buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { ValidateWrite(buffer, offset, count); ConsolePal.Write(_handle, buffer, offset, count); } public override void Flush() { if (_handle.IsClosed) { throw Error.GetFileNotOpen(); } base.Flush(); } } internal sealed class ControlCHandlerRegistrar { private static readonly Interop.Sys.CtrlCallback _handler = c => Console.HandleBreakEvent(c == Interop.Sys.CtrlCode.Break ? ConsoleSpecialKey.ControlBreak : ConsoleSpecialKey.ControlC); private bool _handlerRegistered; internal void Register() { EnsureInitialized(); Debug.Assert(!_handlerRegistered); Interop.Sys.RegisterForCtrl(_handler); _handlerRegistered = true; } internal void Unregister() { Debug.Assert(_handlerRegistered); _handlerRegistered = false; Interop.Sys.UnregisterForCtrl(); } } } }
44.836428
215
0.560126
[ "MIT" ]
BigBadBleuCheese/corefx
src/System.Console/src/System/ConsolePal.Unix.cs
50,710
C#
using System; using MySql.Data.MySqlClient; using System.Collections.Generic; namespace FavoriteRestaurants.Models { public class Cuisine { private int _id; private string _name; public Cuisine(string name, int id=0) { _id = id; _name = name; } public string GetName() { return _name; } public int GetId() { return _id; } public string GetDetails() { return "ID: " +_id + ", Name: " + _name; } public static List<Cuisine> GetAll() { List<Cuisine> allCuisine = new List<Cuisine> {}; MySqlConnection conn = DB.Connection(); conn.Open(); var cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"SELECT * FROM cuisines ORDER BY name ASC;"; var rdr = cmd.ExecuteReader() as MySqlDataReader; while(rdr.Read()) { int CuisineId = rdr.GetInt32(0); string CuisineName = rdr.GetString(1); Cuisine newCuisine = new Cuisine(CuisineName, CuisineId); allCuisine.Add(newCuisine); } conn.Close(); if (conn != null) { conn.Dispose(); } return allCuisine; } public static void DeleteAll() { MySqlConnection conn = DB.Connection(); conn.Open(); var cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"DELETE FROM cuisines;"; cmd.ExecuteNonQuery(); conn.Close(); if (conn != null) { conn.Dispose(); } } public override bool Equals(System.Object otherCuisine) { if(!(otherCuisine is Cuisine)) { return false; } else { Cuisine newCuisine = (Cuisine) otherCuisine; bool idEquality = (this.GetId() == newCuisine.GetId()); bool nameEquality = (this.GetName() == newCuisine.GetName()); return (idEquality && nameEquality); } } public override int GetHashCode() { return this.GetName().GetHashCode(); } public void Save() { MySqlConnection conn = DB.Connection(); conn.Open(); var cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"INSERT INTO cuisines (name) VALUES (@name);"; MySqlParameter name = new MySqlParameter(); name.ParameterName = "@name"; name.Value = this._name; cmd.Parameters.Add(name); cmd.ExecuteNonQuery(); _id = (int) cmd.LastInsertedId; conn.Close(); if (conn != null) { conn.Dispose(); } } public static Cuisine Find(int id) { MySqlConnection conn = DB.Connection(); conn.Open(); var cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"SELECT * FROM cuisines WHERE id = (@searchId);"; MySqlParameter searchId = new MySqlParameter(); searchId.ParameterName = "@searchId"; searchId.Value = id; cmd.Parameters.Add(searchId); var rdr = cmd.ExecuteReader() as MySqlDataReader; int CuisineId = 0; string CuisineName = ""; while(rdr.Read()) { CuisineId = rdr.GetInt32(0); CuisineName = rdr.GetString(1); } Cuisine newCuisine = new Cuisine(CuisineName, CuisineId); conn.Close(); if (conn != null) { conn.Dispose(); } return newCuisine; } public List<Restaurant> GetRestaurants() { List<Restaurant> allRestaurants = new List<Restaurant> (); MySqlConnection conn = DB.Connection(); conn.Open(); var cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"SELECT * FROM restaurants WHERE cuisine_id = @cuisine_id ORDER BY name ASC"; MySqlParameter cuisineId = new MySqlParameter(); cuisineId.ParameterName = "@cuisine_id"; cuisineId.Value = this._id; cmd.Parameters.Add(cuisineId); var rdr = cmd.ExecuteReader() as MySqlDataReader; while(rdr.Read()) { int restaurantId = rdr.GetInt32(0); string name = rdr.GetString(1); string location = rdr.GetString(2); string hours = rdr.GetString(3); int fk_cuisineId = rdr.GetInt32(4); Restaurant newRestaurant = new Restaurant(name, location, hours, fk_cuisineId , restaurantId); allRestaurants.Add(newRestaurant); } conn.Close(); if (conn != null) { conn.Dispose(); } return allRestaurants; } public void UpdateCuisineName(string newName) { MySqlConnection conn = DB.Connection(); conn.Open(); var cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"UPDATE cuisines SET name = @newName WHERE id = @searchId;"; MySqlParameter searchId = new MySqlParameter(); searchId.ParameterName = "@searchId"; searchId.Value = _id; cmd.Parameters.Add(searchId); MySqlParameter name = new MySqlParameter(); name.ParameterName = "@newName"; name.Value = newName; cmd.Parameters.Add(name); cmd.ExecuteNonQuery(); _name = newName; conn.Close(); if (conn != null) { conn.Dispose(); } } } }
25.586207
103
0.588949
[ "MIT" ]
ReconScout77/favorite-restaurants
FavoriteRestaurants/Models/Cuisine.cs
5,194
C#
using System; using System.Collections.Generic; using System.Text; namespace UHubApi.AspNetCore { public class UHubApiOptions { public string AppSecret { get; set; } public string UHubBaseUrl { get; set; } } }
17.214286
47
0.672199
[ "Apache-2.0" ]
yiyungent/UHub
src/Sdk/UHubApi.AspNetCore/UHubApiOptions.cs
243
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CBTTaskRiderNotifyScriptedActionOnHorseDef : IBehTreeRiderTaskDefinition { public CBTTaskRiderNotifyScriptedActionOnHorseDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBTTaskRiderNotifyScriptedActionOnHorseDef(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
33.826087
154
0.769923
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CBTTaskRiderNotifyScriptedActionOnHorseDef.cs
756
C#
// 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. // // Copyright (c) 2004-2005 Novell, Inc. // // Authors: // Jordi Mas i Hernandez, jordi@ximian.com // // // COMPLETE using System.ComponentModel; using System.Drawing; namespace System.Windows.Forms { [ToolboxItemFilter("System.Windows.Forms.MainMenu", ToolboxItemFilterType.Allow)] public class MainMenu : Menu { private RightToLeft right_to_left = RightToLeft.Inherit; private Form form = null; public MainMenu () : base (null) { } public MainMenu (MenuItem[] items) : base (items) { } #if NET_2_0 public MainMenu (IContainer container) : this () { container.Add (this); } #endif #region Events #if NET_2_0 static object CollapseEvent = new object (); public event EventHandler Collapse { add { Events.AddHandler (CollapseEvent, value); } remove { Events.RemoveHandler (CollapseEvent, value); } } #endif #endregion Events #region Public Properties [Localizable(true)] #if NET_2_0 [AmbientValue (RightToLeft.Inherit)] #endif public virtual RightToLeft RightToLeft { get { return right_to_left;} set { right_to_left = value; } } #endregion Public Properties #region Public Methods public virtual MainMenu CloneMenu () { MainMenu new_menu = new MainMenu (); new_menu.CloneMenu (this); return new_menu; } protected override IntPtr CreateMenuHandle () { return IntPtr.Zero; } protected override void Dispose (bool disposing) { base.Dispose (disposing); } public Form GetForm () { return form; } public override string ToString () { return base.ToString () + ", GetForm: " + form; } #if NET_2_0 protected internal virtual void OnCollapse (EventArgs e) { EventHandler eh = (EventHandler) (Events [CollapseEvent]); if (eh != null) eh (this, e); } #endif #endregion Public Methods #region Private Methods internal void Draw () { Message m = Message.Create (Wnd.window.Handle, (int) Msg.WM_PAINT, IntPtr.Zero, IntPtr.Zero); PaintEventArgs pe = XplatUI.PaintEventStart (ref m, Wnd.window.Handle, false); Draw (pe, Rect); } internal void Draw (Rectangle rect) { if (Wnd.IsHandleCreated) { Point pt = XplatUI.GetMenuOrigin (Wnd.window.Handle); Message m = Message.Create (Wnd.window.Handle, (int)Msg.WM_PAINT, IntPtr.Zero, IntPtr.Zero); PaintEventArgs pevent = XplatUI.PaintEventStart (ref m, Wnd.window.Handle, false); pevent.Graphics.SetClip (new Rectangle (rect.X + pt.X, rect.Y + pt.Y, rect.Width, rect.Height)); Draw (pevent, Rect); XplatUI.PaintEventEnd (ref m, Wnd.window.Handle, false); } } internal void Draw (PaintEventArgs pe) { Draw (pe, Rect); } internal void Draw (PaintEventArgs pe, Rectangle rect) { if (!Wnd.IsHandleCreated) return; X = rect.X; Y = rect.Y; Height = Rect.Height; ThemeEngine.Current.DrawMenuBar (pe.Graphics, this, rect); PaintEventHandler eh = (PaintEventHandler)(Events [PaintEvent]); if (eh != null) eh (this, pe); } internal override void InvalidateItem (MenuItem item) { Draw (item.bounds); } internal void SetForm (Form form) { this.form = form; Wnd = form; if (tracker == null) { tracker = new MenuTracker (this); tracker.GrabControl = form; } } internal override void OnMenuChanged (EventArgs e) { base.OnMenuChanged (EventArgs.Empty); if (form == null) return; Rectangle clip = Rect; Height = 0; /* need this so the theme code will re-layout the menu items (why is the theme code doing the layout? argh) */ if (!Wnd.IsHandleCreated) return; Message m = Message.Create (Wnd.window.Handle, (int) Msg.WM_PAINT, IntPtr.Zero, IntPtr.Zero); PaintEventArgs pevent = XplatUI.PaintEventStart (ref m, Wnd.window.Handle, false); pevent.Graphics.SetClip (clip); Draw (pevent, clip); } /* Mouse events from the form */ internal void OnMouseDown (object window, MouseEventArgs args) { tracker.OnMouseDown (args); } internal void OnMouseMove (object window, MouseEventArgs e) { MouseEventArgs args = new MouseEventArgs (e.Button, e.Clicks, Control.MousePosition.X, Control.MousePosition.Y, e.Delta); tracker.OnMotion (args); } static object PaintEvent = new object (); internal event PaintEventHandler Paint { add { Events.AddHandler (PaintEvent, value); } remove { Events.RemoveHandler (PaintEvent, value); } } #endregion Private Methods } }
24.982143
124
0.688885
[ "Apache-2.0" ]
Sectoid/debian-mono
mcs/class/Managed.Windows.Forms/System.Windows.Forms/MainMenu.cs
5,596
C#
// // ClientEngineTests.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2008 Alan McGovern // // 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. // using System; using System.IO; using System.Threading; using System.Threading.Tasks; using MonoTorrent.Dht; using NUnit.Framework; namespace MonoTorrent.Client { [TestFixture] public class ClientEngineTests { [SetUp] public void Setup () { DhtEngineFactory.Creator = listener => new ManualDhtEngine (); } [TearDown] public void Teardown () { DhtEngineFactory.Creator = listener => new DhtEngine (listener); } [Test] public async Task AddPeers_Dht () { using var rig = TestRig.CreateMultiFile (new TestWriter ()); var dht = (ManualDhtEngine) rig.Engine.DhtEngine; var tcs = new TaskCompletionSource<DhtPeersAdded> (); var manager = rig.Engine.Torrents[0]; manager.PeersFound += (o, e) => { if (e is DhtPeersAdded args) tcs.TrySetResult (args); }; dht.RaisePeersFound (manager.InfoHash, new[] { rig.CreatePeer (false).Peer }); var result = await tcs.Task.WithTimeout (TimeSpan.FromSeconds (5)); Assert.AreEqual (1, result.NewPeers, "#2"); Assert.AreEqual (0, result.ExistingPeers, "#3"); Assert.AreEqual (1, manager.Peers.AvailablePeers.Count, "#4"); } [Test] public async Task AddPeers_Dht_Private () { // You can't manually add peers to private torrents using var rig = TestRig.CreateMultiFile (new TestWriter ()); var editor = new TorrentEditor (rig.TorrentDict) { CanEditSecureMetadata = true, Private = true }; var manager = await rig.Engine.AddAsync (editor.ToTorrent (), "path", new TorrentSettings ()); var dht = (ManualDhtEngine) rig.Engine.DhtEngine; var tcs = new TaskCompletionSource<DhtPeersAdded> (); manager.PeersFound += (o, e) => { if (e is DhtPeersAdded args) tcs.TrySetResult (args); }; dht.RaisePeersFound (manager.InfoHash, new[] { rig.CreatePeer (false).Peer }); var result = await tcs.Task.WithTimeout (TimeSpan.FromSeconds (5)); Assert.AreEqual (0, result.NewPeers, "#2"); Assert.AreEqual (0, result.ExistingPeers, "#3"); Assert.AreEqual (0, manager.Peers.AvailablePeers.Count, "#4"); } [Test] public async Task AddPeers_LocalPeerDiscovery () { using var rig = TestRig.CreateMultiFile (new TestWriter ()); var localPeer = (ManualLocalPeerListener) rig.Engine.LocalPeerDiscovery; var tcs = new TaskCompletionSource<LocalPeersAdded> (); var manager = rig.Engine.Torrents[0]; manager.PeersFound += (o, e) => { if (e is LocalPeersAdded args) tcs.TrySetResult (args); }; localPeer.RaisePeerFound (manager.InfoHash, rig.CreatePeer (false).Uri); var result = await tcs.Task.WithTimeout (TimeSpan.FromSeconds (5)); Assert.AreEqual (1, result.NewPeers, "#2"); Assert.AreEqual (0, result.ExistingPeers, "#3"); Assert.AreEqual (1, manager.Peers.AvailablePeers.Count, "#4"); } [Test] public async Task AddPeers_LocalPeerDiscovery_Private () { // You can't manually add peers to private torrents using var rig = TestRig.CreateMultiFile (new TestWriter ()); var editor = new TorrentEditor (rig.TorrentDict) { CanEditSecureMetadata = true, Private = true }; var manager = await rig.Engine.AddAsync (editor.ToTorrent (), "path", new TorrentSettings ()); var localPeer = (ManualLocalPeerListener) rig.Engine.LocalPeerDiscovery; var tcs = new TaskCompletionSource<LocalPeersAdded> (); manager.PeersFound += (o, e) => { if (e is LocalPeersAdded args) tcs.TrySetResult (args); }; localPeer.RaisePeerFound (manager.InfoHash, rig.CreatePeer (false).Uri); var result = await tcs.Task.WithTimeout (TimeSpan.FromSeconds (5)); Assert.AreEqual (0, result.NewPeers, "#2"); Assert.AreEqual (0, result.ExistingPeers, "#3"); Assert.AreEqual (0, manager.Peers.AvailablePeers.Count, "#4"); } [Test] public void CacheDirectory_IsFile_Constructor() { var tmp = TempDir.Create (); var cachePath = Path.Combine (tmp.Path, "test.file"); using (var file = File.Create (cachePath)) { } Assert.Throws<ArgumentException> (() => new ClientEngine (new EngineSettingsBuilder { CacheDirectory = cachePath }.ToSettings ())); } [Test] public void CacheDirectory_IsFile_UpdateSettings () { var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ()); var tmp = TempDir.Create (); var cachePath = Path.Combine (tmp.Path, "test.file"); using (var file = File.Create (cachePath)) { } Assert.ThrowsAsync<ArgumentException> (() => engine.UpdateSettingsAsync (new EngineSettingsBuilder { CacheDirectory = cachePath }.ToSettings ())); } [Test] public void DownloadMetadata_Cancelled () { var cts = new CancellationTokenSource (); var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ()); var task = engine.DownloadMetadataAsync (new MagnetLink (new InfoHash (new byte[20])), cts.Token); cts.Cancel (); Assert.ThrowsAsync<OperationCanceledException> (() => task); } [Test] public async Task SaveRestoreState_NoTorrents () { var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ()); var restoredEngine = await ClientEngine.RestoreStateAsync (await engine.SaveStateAsync ()); Assert.AreEqual (engine.Settings, restoredEngine.Settings); } [Test] public async Task SaveRestoreState_OneInMemoryTorrent () { var pieceLength = Piece.BlockSize * 4; using var tmpDir = TempDir.Create (); var torrent = TestRig.CreateMultiFileTorrent (TorrentFile.Create (pieceLength, Piece.BlockSize, Piece.BlockSize * 2, Piece.BlockSize * 3), pieceLength, out BEncoding.BEncodedDictionary metadata); var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests (cacheDirectory: tmpDir.Path)); var torrentManager = await engine.AddAsync (torrent, "mySaveDirectory", new TorrentSettingsBuilder { CreateContainingDirectory = true }.ToSettings ()); await torrentManager.SetFilePriorityAsync (torrentManager.Files[0], Priority.High); await torrentManager.MoveFileAsync (torrentManager.Files[1], Path.GetFullPath ("some_fake_path.txt")); var restoredEngine = await ClientEngine.RestoreStateAsync (await engine.SaveStateAsync ()); Assert.AreEqual (engine.Settings, restoredEngine.Settings); Assert.AreEqual (engine.Torrents[0].Torrent.Name, restoredEngine.Torrents[0].Torrent.Name); Assert.AreEqual (engine.Torrents[0].SavePath, restoredEngine.Torrents[0].SavePath); Assert.AreEqual (engine.Torrents[0].Settings, restoredEngine.Torrents[0].Settings); Assert.AreEqual (engine.Torrents[0].InfoHash, restoredEngine.Torrents[0].InfoHash); Assert.AreEqual (engine.Torrents[0].MagnetLink.ToV1String (), restoredEngine.Torrents[0].MagnetLink.ToV1String ()); Assert.AreEqual (engine.Torrents[0].Files.Count, restoredEngine.Torrents[0].Files.Count); for (int i = 0; i < engine.Torrents.Count; i++) { Assert.AreEqual (engine.Torrents[0].Files[i].FullPath, restoredEngine.Torrents[0].Files[i].FullPath); Assert.AreEqual (engine.Torrents[0].Files[i].Priority, restoredEngine.Torrents[0].Files[i].Priority); } } [Test] public async Task SaveRestoreState_OneMagnetLink () { var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ()); await engine.AddAsync (new MagnetLink (new InfoHash (new byte[20]), "test"), "mySaveDirectory", new TorrentSettingsBuilder { CreateContainingDirectory = false }.ToSettings ()); var restoredEngine = await ClientEngine.RestoreStateAsync (await engine.SaveStateAsync ()); Assert.AreEqual (engine.Settings, restoredEngine.Settings); Assert.AreEqual (engine.Torrents[0].SavePath, restoredEngine.Torrents[0].SavePath); Assert.AreEqual (engine.Torrents[0].Settings, restoredEngine.Torrents[0].Settings); Assert.AreEqual (engine.Torrents[0].InfoHash, restoredEngine.Torrents[0].InfoHash); Assert.AreEqual (engine.Torrents[0].MagnetLink.ToV1Uri (), restoredEngine.Torrents[0].MagnetLink.ToV1Uri ()); Assert.AreEqual (engine.Torrents[0].Files, restoredEngine.Torrents[0].Files); } [Test] public async Task SaveRestoreState_OneTorrentFile_ContainingDirectory () { var pieceLength = Piece.BlockSize * 4; using var tmpDir = TempDir.Create (); TestRig.CreateMultiFileTorrent (TorrentFile.Create (pieceLength, Piece.BlockSize, Piece.BlockSize * 2, Piece.BlockSize * 3), pieceLength, out BEncoding.BEncodedDictionary metadata); var metadataFile = Path.Combine (tmpDir.Path, "test.torrent"); File.WriteAllBytes (metadataFile, metadata.Encode ()); var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests (cacheDirectory: tmpDir.Path)); var torrentManager = await engine.AddAsync (metadataFile, "mySaveDirectory", new TorrentSettingsBuilder { CreateContainingDirectory = true }.ToSettings ()); await torrentManager.SetFilePriorityAsync (torrentManager.Files[0], Priority.High); await torrentManager.MoveFileAsync (torrentManager.Files[1], Path.GetFullPath ("some_fake_path.txt")); var restoredEngine = await ClientEngine.RestoreStateAsync (await engine.SaveStateAsync ()); Assert.AreEqual (engine.Settings, restoredEngine.Settings); Assert.AreEqual (engine.Torrents[0].Torrent.Name, restoredEngine.Torrents[0].Torrent.Name); Assert.AreEqual (engine.Torrents[0].SavePath, restoredEngine.Torrents[0].SavePath); Assert.AreEqual (engine.Torrents[0].Settings, restoredEngine.Torrents[0].Settings); Assert.AreEqual (engine.Torrents[0].InfoHash, restoredEngine.Torrents[0].InfoHash); Assert.AreEqual (engine.Torrents[0].MagnetLink.ToV1String (), restoredEngine.Torrents[0].MagnetLink.ToV1String ()); Assert.AreEqual (engine.Torrents[0].Files.Count, restoredEngine.Torrents[0].Files.Count); for (int i = 0; i < engine.Torrents.Count; i ++) { Assert.AreEqual (engine.Torrents[0].Files[i].FullPath, restoredEngine.Torrents[0].Files[i].FullPath); Assert.AreEqual (engine.Torrents[0].Files[i].Priority, restoredEngine.Torrents[0].Files[i].Priority); } } [Test] public async Task SaveRestoreState_OneTorrentFile_NoContainingDirectory () { var pieceLength = Piece.BlockSize * 4; using var tmpDir = TempDir.Create (); TestRig.CreateMultiFileTorrent (TorrentFile.Create (pieceLength, Piece.BlockSize, Piece.BlockSize * 2, Piece.BlockSize * 3), pieceLength, out BEncoding.BEncodedDictionary metadata); var metadataFile = Path.Combine (tmpDir.Path, "test.torrent"); File.WriteAllBytes (metadataFile, metadata.Encode ()); var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests (cacheDirectory: tmpDir.Path)); await engine.AddAsync (metadataFile, "mySaveDirectory", new TorrentSettingsBuilder { CreateContainingDirectory = false }.ToSettings ()); var restoredEngine = await ClientEngine.RestoreStateAsync (await engine.SaveStateAsync ()); Assert.AreEqual (engine.Settings, restoredEngine.Settings); Assert.AreEqual (engine.Torrents[0].Torrent.Name, restoredEngine.Torrents[0].Torrent.Name); Assert.AreEqual (engine.Torrents[0].SavePath, restoredEngine.Torrents[0].SavePath); Assert.AreEqual (engine.Torrents[0].Settings, restoredEngine.Torrents[0].Settings); Assert.AreEqual (engine.Torrents[0].InfoHash, restoredEngine.Torrents[0].InfoHash); Assert.AreEqual (engine.Torrents[0].MagnetLink.ToV1String (), restoredEngine.Torrents[0].MagnetLink.ToV1String ()); Assert.AreEqual (engine.Torrents[0].Files.Count, restoredEngine.Torrents[0].Files.Count); for (int i = 0; i < engine.Torrents.Count; i++) { Assert.AreEqual (engine.Torrents[0].Files[i].FullPath, restoredEngine.Torrents[0].Files[i].FullPath); Assert.AreEqual (engine.Torrents[0].Files[i].Priority, restoredEngine.Torrents[0].Files[i].Priority); } } [Test] public async Task StopTest () { using var rig = TestRig.CreateMultiFile (new TestWriter ()); var hashingState = rig.Manager.WaitForState (TorrentState.Hashing); var stoppedState = rig.Manager.WaitForState (TorrentState.Stopped); await rig.Manager.StartAsync (); Assert.IsTrue (hashingState.Wait (5000), "Started"); await rig.Manager.StopAsync (); Assert.IsTrue (stoppedState.Wait (5000), "Stopped"); } } }
49.937294
207
0.64662
[ "MIT" ]
OneFingerCodingWarrior/monotorrent
src/MonoTorrent.Tests/Client/ClientEngineTests.cs
15,133
C#
using YggdrAshill.Nuadha.Signalization; using YggdrAshill.Nuadha.Unitization; using YggdrAshill.Nuadha.Conduction; using System; namespace YggdrAshill.Nuadha.Units { /// <summary> /// Defines conversion for <see cref="IHandControllerProtocol"/>, <see cref="IHandControllerHardware"/> and <see cref="IHandControllerSoftware"/>. /// </summary> public static class ConvertHandControllerInto { /// <summary> /// Converts <see cref="IHandControllerProtocol"/> into <see cref="ITransmission{TModule}"/> for <see cref="IHandControllerSoftware"/>. /// </summary> /// <param name="protocol"> /// <see cref="IHandControllerProtocol"/> to convert. /// </param> /// <param name="configuration"> /// <see cref="IHandControllerConfiguration"/> to convert. /// </param> /// <returns> /// <see cref="ITransmission{TModule}"/> for <see cref="IHandControllerSoftware"/> converted from <see cref="IHandControllerProtocol"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="protocol"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="configuration"/> is null. /// </exception> public static ITransmission<IHandControllerSoftware> Transmission(IHandControllerProtocol protocol, IHandControllerConfiguration configuration) { if (protocol == null) { throw new ArgumentNullException(nameof(protocol)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return new TransmitHandController(configuration, protocol); } private sealed class TransmitHandController : ITransmission<IHandControllerSoftware> { private readonly IEmission emission; private readonly IConnection<IHandControllerSoftware> connection; internal TransmitHandController(IHandControllerConfiguration configuration, IHandControllerProtocol protocol) { emission = Conduct(configuration, protocol.Software); connection = ConvertHandControllerInto.Connection(protocol.Hardware); } public ICancellation Connect(IHandControllerSoftware module) { if (module == null) { throw new ArgumentNullException(nameof(module)); } return connection.Connect(module); } public void Emit() { emission.Emit(); } } private static IEmission Conduct(IHandControllerConfiguration configuration, IHandControllerSoftware software) => EmissionSource .Default .Synthesize(ConductSignalTo.Consume(configuration.HandGrip.Touch, software.HandGrip.Touch)) .Synthesize(ConductSignalTo.Consume(configuration.HandGrip.Pull, software.HandGrip.Pull)) .Synthesize(ConductSignalTo.Consume(configuration.IndexFinger.Touch, software.IndexFinger.Touch)) .Synthesize(ConductSignalTo.Consume(configuration.IndexFinger.Pull, software.IndexFinger.Pull)) .Synthesize(ConductSignalTo.Consume(configuration.Thumb.Touch, software.Thumb.Touch)) .Synthesize(ConductSignalTo.Consume(configuration.Thumb.Tilt, software.Thumb.Tilt)) .Synthesize(ConductSignalTo.Consume(configuration.Pose.Position, software.Pose.Position)) .Synthesize(ConductSignalTo.Consume(configuration.Pose.Rotation, software.Pose.Rotation)) .Build(); /// <summary> /// Converts <see cref="IHandControllerSoftware"/> into <see cref="IConnection{TModule}"/> for <see cref="IHandControllerHardware"/>. /// </summary> /// <param name="software"> /// <see cref="IHandControllerSoftware"/> to convert. /// </param> /// <returns> /// <see cref="IConnection{TModule}"/> for <see cref="IHandControllerHardware"/> converted from <see cref="IHandControllerSoftware"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="software"/> is null. /// </exception> public static IConnection<IHandControllerHardware> Connection(IHandControllerSoftware software) { if (software == null) { throw new ArgumentNullException(nameof(software)); } return new ConnectHandControllerHardware(software); } private sealed class ConnectHandControllerHardware : IConnection<IHandControllerHardware> { private readonly IHandControllerSoftware software; internal ConnectHandControllerHardware(IHandControllerSoftware software) { this.software = software; } public ICancellation Connect(IHandControllerHardware module) { if (module == null) { throw new ArgumentNullException(nameof(module)); } return ConvertHandControllerInto.Connect(module, software); } } /// <summary> /// Converts <see cref="IHandControllerHardware"/> into <see cref="IConnection{TModule}"/> for <see cref="IHandControllerSoftware"/>. /// </summary> /// <param name="hardware"> /// <see cref="IHandControllerSoftware"/> to convert. /// </param> /// <returns> /// <see cref="IConnection{TModule}"/> for <see cref="IHandControllerSoftware"/> converted from <see cref="IHandControllerHardware"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="hardware"/> is null. /// </exception> public static IConnection<IHandControllerSoftware> Connection(IHandControllerHardware hardware) { if (hardware == null) { throw new ArgumentNullException(nameof(hardware)); } return new ConnectHandControllerSoftware(hardware); } private sealed class ConnectHandControllerSoftware : IConnection<IHandControllerSoftware> { private readonly IHandControllerHardware hardware; internal ConnectHandControllerSoftware(IHandControllerHardware hardware) { this.hardware = hardware; } public ICancellation Connect(IHandControllerSoftware module) { if (module == null) { throw new ArgumentNullException(nameof(module)); } return ConvertHandControllerInto.Connect(hardware, module); } } private static ICancellation Connect(IHandControllerHardware hardware, IHandControllerSoftware software) => CancellationSource .Default .Synthesize(hardware.HandGrip.Touch.Produce(software.HandGrip.Touch)) .Synthesize(hardware.HandGrip.Pull.Produce(software.HandGrip.Pull)) .Synthesize(hardware.IndexFinger.Touch.Produce(software.IndexFinger.Touch)) .Synthesize(hardware.IndexFinger.Pull.Produce(software.IndexFinger.Pull)) .Synthesize(hardware.Thumb.Touch.Produce(software.Thumb.Touch)) .Synthesize(hardware.Thumb.Tilt.Produce(software.Thumb.Tilt)) .Synthesize(hardware.Pose.Position.Produce(software.Pose.Position)) .Synthesize(hardware.Pose.Rotation.Produce(software.Pose.Rotation)) .Build(); /// <summary> /// Converts <see cref="IHandControllerHardware"/> into <see cref="IPulsatedHandControllerHardware"/>. /// </summary> /// <param name="hardware"> /// <see cref="IHandControllerHardware"/> to convert. /// </param> /// <param name="pulsation"> /// <see cref="IHandControllerPulsation"/> to convert. /// </param> /// <returns> /// <see cref="IPulsatedHandControllerHardware"/> converted from <see cref="IHandControllerHardware"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="hardware"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="pulsation"/> is null. /// </exception> public static IPulsatedHandControllerHardware PulsatedHandController(IHandControllerHardware hardware, IHandControllerPulsation pulsation) { if (hardware == null) { throw new ArgumentNullException(nameof(hardware)); } if (pulsation == null) { throw new ArgumentNullException(nameof(pulsation)); } return new PulsatedHandControllerHardware(hardware, pulsation); } private sealed class PulsatedHandControllerHardware : IPulsatedHandControllerHardware { internal PulsatedHandControllerHardware(IHandControllerHardware module, IHandControllerPulsation pulsation) { Thumb = ConvertStickInto.PulsatedStick(module.Thumb, pulsation.Thumb); IndexFinger = ConvertTriggerInto.PulsatedTrigger(module.IndexFinger, pulsation.IndexFinger); HandGrip = ConvertTriggerInto.PulsatedTrigger(module.HandGrip, pulsation.HandGrip); } public IPulsatedStickHardware Thumb { get; } public IPulsatedTriggerHardware IndexFinger { get; } public IPulsatedTriggerHardware HandGrip { get; } } } }
42.598291
151
0.618078
[ "MIT" ]
do-i-know-it/YggdrAshill.Nuadha
Units/HandController/ConvertHandControllerInto.cs
9,968
C#
/** * @File : TaskManager.cs * @Author : dtysky (dtysky@outlook.com) * @Link : dtysky.moe * @Date : 2019/09/09 0:00:00PM */ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; namespace SeinJS { public class TaskManager { List<IEnumerator> _tasks; IEnumerator _current = null; public TaskManager() { _tasks = new List<IEnumerator>(); } public void addTask(IEnumerator task) { _tasks.Add(task); } public void clear() { _tasks.Clear(); } public bool play() { if (_tasks.Count > 0) { if (_current == null || !_current.MoveNext()) { _current = _tasks[0]; _tasks.RemoveAt(0); } } if (_current != null) _current.MoveNext(); if (_current != null && !_current.MoveNext() && _tasks.Count == 0) return false; return true; } } }
20.654545
78
0.47007
[ "MIT" ]
FreesideStation/Nexus-Unity-Scenes
Assets/SeinJS/SeinJSUnityToolkit/Common/TaskManager.cs
1,138
C#
using Hobby.DomainEvents.Events; using Hobby.DomainEvents.Service; using Ninject; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hobby.Ninject.Containers { public class NinjectEventContainer : IEventDispatcher { private readonly IKernel _kernel; public NinjectEventContainer(IKernel kernel) { _kernel = kernel; } public void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent { foreach (var handler in _kernel.GetAll<IDomainHandler<TEvent>>()) { handler.Handle(eventToDispatch); } } } }
23.258065
88
0.656033
[ "Artistic-2.0" ]
Deith2/ProjectIntrduction
src/Hobby.Ninject/Containers/NinjectEventContainer.cs
723
C#
using System.Collections.Generic; using Orchard.Security; namespace Orchard.Roles.Models { public class RolesDocument { public List<Role> Roles { get; } = new List<Role>(); public int Serial { get; set; } } }
19.916667
60
0.644351
[ "BSD-3-Clause" ]
PinpointTownes/Orchard2
src/Orchard.Web/Modules/Orchard.Roles/Models/RolesDocument.cs
241
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace TButt.Editor { public static class TBEditorDefines { public static readonly string settingsPath = "Assets/Resources/"; // Location of the TButtSettings folder. public static readonly string versionNum = "1.1.0"; // Misc public static string logsDef = "TB_ENABLE_LOGS"; // SDKs public static string steamVRDef = "TB_STEAM_VR"; public static string oculusDef = "TB_OCULUS"; public static string googleDef = "TB_GOOGLE"; public static string psvrDef = "TB_PSVR"; public static string windowsDef = "TB_WINDOWS_MR"; static string buildDefString = ""; public static void SetScriptingDefines() { if (buildDefString.StartsWith(";")) buildDefString = buildDefString.Remove(0, 1); UnityEditor.PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, buildDefString); UnityEditor.PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, buildDefString); UnityEditor.PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.WSA, buildDefString); UnityEditor.PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, buildDefString); UnityEditor.PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.PS4, buildDefString); } public static void SetPlatformDefine(string platform, bool on) { if(string.IsNullOrEmpty(buildDefString)) buildDefString = UnityEditor.PlayerSettings.GetScriptingDefineSymbolsForGroup(UnityEditor.EditorUserBuildSettings.selectedBuildTargetGroup); if (on) { if (!buildDefString.Contains(platform)) { TBLogging.LogMessage("Adding " + platform); buildDefString += ";" + platform; } } else { if (buildDefString.Contains(platform)) { TBLogging.LogMessage("Removing " + platform); buildDefString = buildDefString.Remove(buildDefString.IndexOf(platform), platform.Length); } } } public static void SetUnityVirtualRealitySDKs(TBEditorSDKSettings.SDKs sdks) { #region PC / STANDALONE CHECKS string[] currentTargets = PlayerSettings.GetVirtualRealitySDKs(BuildTargetGroup.Standalone); string[] wantedTargets = new string[] { "None" }; // Kind of ugly, but the build platforms have to be set in a particular order for things to work properly. // Assume that if Oculus and Steam are both enabled, Oculus should be first in the list. if (sdks.oculus && sdks.steamVR) wantedTargets = new string[] { TBSettings.VRDeviceNames.Oculus, TBSettings.VRDeviceNames.SteamVR }; else if (sdks.oculus) { if(Settings.TBOculusSettings.LoadOculusSettings(Settings.TBOculusSettings.OculusDeviceFamily.Rift).allowViveEmulation) wantedTargets = new string[] { TBSettings.VRDeviceNames.Oculus, TBSettings.VRDeviceNames.SteamVR }; else wantedTargets = new string[] { TBSettings.VRDeviceNames.Oculus }; } else if (sdks.steamVR) wantedTargets = new string[] { TBSettings.VRDeviceNames.SteamVR }; SetPlayerSettingsSDKs(BuildTargetGroup.Standalone, wantedTargets, currentTargets); currentTargets = PlayerSettings.GetVirtualRealitySDKs(BuildTargetGroup.WSA); wantedTargets = new string[] { "None" }; if (sdks.windows) wantedTargets = new string[] { TBSettings.VRDeviceNames.WindowsMR }; SetPlayerSettingsSDKs(BuildTargetGroup.WSA, wantedTargets, currentTargets); #endregion #region ANDROID CHECKS currentTargets = PlayerSettings.GetVirtualRealitySDKs(BuildTargetGroup.Android); wantedTargets = new string[] { "None" }; if (sdks.oculus && sdks.googleVR) wantedTargets = new string[2] { TBSettings.VRDeviceNames.Oculus, TBSettings.VRDeviceNames.Daydream }; else if (sdks.oculus) wantedTargets = new string[1] { TBSettings.VRDeviceNames.Oculus }; else if (sdks.googleVR) wantedTargets = new string[1] { TBSettings.VRDeviceNames.Daydream }; SetPlayerSettingsSDKs(BuildTargetGroup.Android, wantedTargets, currentTargets); #endregion } public static void SetTButtSDKForPlatform(TButt.VRPlatform platform) { switch(platform) { case VRPlatform.OculusPC: case VRPlatform.OculusMobile: PlayerSettings.SetVirtualRealitySDKs(BuildTargetGroup.Standalone, new string[] { TBSettings.VRDeviceNames.Oculus }); PlayerSettings.SetVirtualRealitySDKs(BuildTargetGroup.Android, new string[] { TBSettings.VRDeviceNames.Oculus }); TBEditorDefines.SetPlatformDefine(steamVRDef, false); TBEditorDefines.SetPlatformDefine(oculusDef, true); break; case VRPlatform.SteamVR: PlayerSettings.SetVirtualRealitySDKs(BuildTargetGroup.Standalone, new string[] { TBSettings.VRDeviceNames.SteamVR }); TBEditorDefines.SetPlatformDefine(steamVRDef, true); TBEditorDefines.SetPlatformDefine(oculusDef, false); break; } } public static void SetPlayerSettingsSDKs(BuildTargetGroup group, string[] wantedSDKs, string[] targetSDKs) { bool needRefresh = false; if (wantedSDKs.Length != targetSDKs.Length) { needRefresh = true; } else { for (int i = 0; i < wantedSDKs.Length; i++) { if (wantedSDKs[i] != targetSDKs[i]) { needRefresh = true; break; } } } if (needRefresh) { string buildMessage = "TButt updated Unity XR Settings to match TButt settings...\n - Platform: " + group + "\n - Old SDKs:"; for (int i = 0; i < targetSDKs.Length; i++) { buildMessage += " " + targetSDKs[i]; } buildMessage += "\n - New SDKs"; for (int i = 0; i < wantedSDKs.Length; i++) { buildMessage += " " + wantedSDKs[i]; } Debug.Log(buildMessage); PlayerSettings.SetVirtualRealitySDKs(group, wantedSDKs); } } } }
44.742138
156
0.595164
[ "MIT" ]
jeff-chamberlain/tbutt-vr
Source/Assets/TButt/Core/Scripts/Editor/TBEditorDefines.cs
7,116
C#
/* * Copyright 2010-2013 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. */ using System.Collections.Generic; using Amazon.ElasticLoadBalancing.Model; using Amazon.Runtime.Internal.Transform; namespace Amazon.ElasticLoadBalancing.Model.Internal.MarshallTransformations { /// <summary> /// Instance Unmarshaller /// </summary> internal class InstanceUnmarshaller : IUnmarshaller<Instance, XmlUnmarshallerContext>, IUnmarshaller<Instance, JsonUnmarshallerContext> { public Instance Unmarshall(XmlUnmarshallerContext context) { Instance instance = new Instance(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("InstanceId", targetDepth)) { instance.InstanceId = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return instance; } } return instance; } public Instance Unmarshall(JsonUnmarshallerContext context) { return null; } private static InstanceUnmarshaller instance; public static InstanceUnmarshaller GetInstance() { if (instance == null) instance = new InstanceUnmarshaller(); return instance; } } }
31.88
140
0.585529
[ "Apache-2.0" ]
zz0733/aws-sdk-net
AWSSDK_DotNet35/Amazon.ElasticLoadBalancing/Model/Internal/MarshallTransformations/InstanceUnmarshaller.cs
2,391
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class DocumentationCommentStructureProvider : AbstractSyntaxNodeStructureProvider<DocumentationCommentTriviaSyntax> { protected override void CollectBlockSpans( DocumentationCommentTriviaSyntax documentationComment, ArrayBuilder<BlockSpan> spans, OptionSet options, CancellationToken cancellationToken) { var startPos = documentationComment.FullSpan.Start; // The trailing newline is included in XmlDocCommentSyntax, so we need to strip it. var endPos = documentationComment.SpanStart + documentationComment.ToString().TrimEnd().Length; var span = TextSpan.FromBounds(startPos, endPos); var bannerLength = options.GetOption(BlockStructureOptions.MaximumBannerLength, LanguageNames.CSharp); var bannerText = CSharpSyntaxFactsService.Instance.GetBannerText( documentationComment, bannerLength, cancellationToken); spans.Add(new BlockSpan( isCollapsible: true, textSpan: span, type: BlockTypes.Comment, bannerText: bannerText, autoCollapse: true)); } } }
41.75
161
0.705389
[ "Apache-2.0" ]
20chan/roslyn
src/Features/CSharp/Portable/Structure/Providers/DocumentationCommentStructureProvider.cs
1,672
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.AwsNative.AppFlow.Outputs { [OutputType] public sealed class ConnectorProfileGoogleAnalyticsConnectorProfileCredentials { /// <summary> /// The credentials used to access protected resources. /// </summary> public readonly string? AccessToken; /// <summary> /// The identifier for the desired client. /// </summary> public readonly string ClientId; /// <summary> /// The client secret used by the oauth client to authenticate to the authorization server. /// </summary> public readonly string ClientSecret; /// <summary> /// The oauth needed to request security tokens from the connector endpoint. /// </summary> public readonly Outputs.ConnectorProfileConnectorOAuthRequest? ConnectorOAuthRequest; /// <summary> /// The credentials used to acquire new access tokens. /// </summary> public readonly string? RefreshToken; [OutputConstructor] private ConnectorProfileGoogleAnalyticsConnectorProfileCredentials( string? accessToken, string clientId, string clientSecret, Outputs.ConnectorProfileConnectorOAuthRequest? connectorOAuthRequest, string? refreshToken) { AccessToken = accessToken; ClientId = clientId; ClientSecret = clientSecret; ConnectorOAuthRequest = connectorOAuthRequest; RefreshToken = refreshToken; } } }
32.807018
99
0.648663
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/AppFlow/Outputs/ConnectorProfileGoogleAnalyticsConnectorProfileCredentials.cs
1,872
C#
/* * Copyright 2020 Sage Intacct, 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 * * 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. */ using Intacct.SDK.Xml; namespace Intacct.SDK.Functions.AccountsReceivable { public class ArAdjustmentLineCreate : AbstractArAdjustmentLine { public ArAdjustmentLineCreate() { } public override void WriteXml(ref IaXmlWriter xml) { xml.WriteStartElement("lineitem"); if (!string.IsNullOrWhiteSpace(AccountLabel)) { xml.WriteElement("accountlabel", AccountLabel, true); } else { xml.WriteElement("glaccountno", GlAccountNumber, true); } xml.WriteElement("offsetglaccountno", OffsetGlAccountNumber); xml.WriteElement("amount", TransactionAmount); xml.WriteElement("allocationid", AllocationId); xml.WriteElement("memo", Memo); xml.WriteElement("locationid", LocationId); xml.WriteElement("departmentid", DepartmentId); xml.WriteElement("key", Key); xml.WriteElement("totalpaid", TotalPaid); xml.WriteElement("totaldue", TotalDue); xml.WriteCustomFieldsExplicit(CustomFields); xml.WriteElement("projectid", ProjectId); xml.WriteElement("customerid", CustomerId); xml.WriteElement("vendorid", VendorId); xml.WriteElement("employeeid", EmployeeId); xml.WriteElement("itemid", ItemId); xml.WriteElement("classid", ClassId); xml.WriteElement("contractid", ContractId); xml.WriteElement("warehouseid", WarehouseId); xml.WriteEndElement(); //lineitem } } }
34.2
80
0.62843
[ "Apache-2.0" ]
Intacct/intacct-sdk-net
Intacct.SDK/Functions/AccountsReceivable/ArAdjustmentLineCreate.cs
2,225
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using MethodRedirect; using System; using System.Reflection; namespace Scenarios_UT { [TestClass] public class Scenario2_UnitTests { [TestMethod] public void Redirect_InternalVirtualInstanceMethod_To_PrivateInstanceMethod_SameInstance() { Assembly assembly = Assembly.GetAssembly(typeof(Scenario2)); Type Scenario_Type = assembly.GetType("MethodRedirect.Scenario2"); MethodInfo Scenario_InternalVirtualInstanceMethod = Scenario_Type.GetMethod("InternalVirtualInstanceMethod", BindingFlags.Instance | BindingFlags.NonPublic); MethodInfo Scenario_PrivateInstanceMethod = Scenario_Type.GetMethod("PrivateInstanceMethod", BindingFlags.Instance | BindingFlags.NonPublic); var token = Scenario_InternalVirtualInstanceMethod.RedirectTo(Scenario_PrivateInstanceMethod); var scenario = (Scenario2)Activator.CreateInstance(Scenario_Type); string methodName = scenario.InternalVirtualInstanceMethod(); Assert.IsTrue(methodName == "MethodRedirect.Scenario2.PrivateInstanceMethod"); token.Restore(); methodName = scenario.InternalVirtualInstanceMethod(); Assert.IsTrue(methodName == "MethodRedirect.Scenario2.InternalVirtualInstanceMethod"); } } }
38.888889
169
0.725714
[ "MIT" ]
spinico/MethodRedirect
UnitTests/Scenario2_UnitTests.cs
1,402
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Online.Chat; namespace osu.Game.Tests.Online.Chat { [TestFixture] public class MessageNotifierTest { [Test] public void TestContainsUsernameAtSign() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("@username hi", "username")); } [Test] public void TestContainsUsernameBetweenPunctuation() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("Hello 'test'-message", "Test")); } [Test] public void TestContainsUsernameColon() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("username: hi", "username")); } [Test] public void TestContainsUsernameEndOfLineNegative() { Assert.IsFalse(MessageNotifier.CheckContainsUsername("This is a notificationtest", "Test")); } [Test] public void TestContainsUsernameEndOfLinePositive() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("This is a test", "Test")); } [Test] public void TestContainsUsernameMidlineNegative() { Assert.IsFalse(MessageNotifier.CheckContainsUsername("This is a testmessage for notifications", "Test")); } [Test] public void TestContainsUsernameMidlinePositive() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("This is a test message", "Test")); } [Test] public void TestContainsUsernameSpecialCharactersNegative() { Assert.IsFalse(MessageNotifier.CheckContainsUsername("Test pad[#^-^#]oru message", "[#^-^#]")); } [Test] public void TestContainsUsernameSpecialCharactersPositive() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("Test [#^-^#] message", "[#^-^#]")); } [Test] public void TestContainsUsernameStartOfLineNegative() { Assert.IsFalse(MessageNotifier.CheckContainsUsername("Testmessage", "Test")); } [Test] public void TestContainsUsernameStartOfLinePositive() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("Test message", "Test")); } [Test] public void TestContainsUsernameUnicode() { Assert.IsTrue(MessageNotifier.CheckContainsUsername("Test \u0460\u0460 message", "\u0460\u0460")); } [Test] public void TestContainsUsernameUnicodeNegative() { Assert.IsFalse(MessageNotifier.CheckContainsUsername("Test ha\u0460\u0460o message", "\u0460\u0460")); } } }
32.455556
118
0.602533
[ "MIT" ]
oldschool-otaku/osu
osu.Game.Tests/Online/Chat/MessageNotifierTest.cs
2,832
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Routing; namespace CompanyName.MyMeetings.API.Configuration.Authorization { public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement) { var attribute = (context.Resource as RouteEndpoint)?.Metadata.GetMetadata<TAttribute>(); return HandleRequirementAsync(context, requirement, attribute); } protected abstract Task HandleRequirementAsync( AuthorizationHandlerContext context, TRequirement requirement, TAttribute attribute); } }
36.72
117
0.736383
[ "MIT" ]
Ahmetcanb/modular-monolith-with-ddd
src/API/CompanyName.MyMeetings.API/Configuration/Authorization/AttributeAuthorizationHandler.cs
920
C#
/* _BEGIN_TEMPLATE_ { "id": "TB_LEAGUE_REVIVAL_FinleySandHero", "name": [ "被埋住的芬利", "Buried Finley" ], "text": [ null, null ], "cardClass": "NEUTRAL", "type": "HERO", "cost": null, "rarity": null, "set": "TB", "collectible": null, "dbfId": 56235 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_TB_LEAGUE_REVIVAL_FinleySandHero : SimTemplate { } }
15.074074
60
0.597052
[ "MIT" ]
chi-rei-den/Silverfish
cards/TB/TB/Sim_TB_LEAGUE_REVIVAL_FinleySandHero.cs
419
C#
#nullable enable using System; using System.Reflection; using Newtonsoft.Json.Linq; namespace Shared.Json { public class JsonMessageDispatcher : MessageDispatcher<JObject> { protected override TParam Deserialize<TParam>(JObject message) => JsonSerialization.Deserialize<TParam>(message); protected override object Deserialize(Type paramType, JObject message) => JsonSerialization.ToObject(paramType, message); protected override RouteAttribute? GetRouteAttribute(MethodInfo mi) => mi.GetCustomAttribute<JsonRouteAttribute>(); protected override bool IsMatch(RouteAttribute route, JObject message) => message.SelectToken(route.Path)?.ToString() == (route as JsonRouteAttribute)?.Value; protected override JObject? Serialize<T>(T instance) => JsonSerialization.Serialize(instance); } }
31.241379
99
0.708609
[ "MIT" ]
rucosmonaut/SpaceSystem
Shared/Json/JsonMessageDispatcher.cs
908
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class RandomSensor : MonoBehaviour, ISensor { public static IEnumerable<string> LABELS = new List<string> { "Random" }; [SerializeField] public int nReceptors; private float[] receptors; void Start() { receptors = new float[nReceptors]; } public float[] GetReceptors() => receptors; public void OnRefresh() => receptors.Randomize(-1f, 1f); public void OnReset() => Array.Clear(receptors, 0, receptors.Length); public IEnumerable<string> GetLabels() => LABELS; }
22.925926
77
0.691438
[ "MIT" ]
reubenjohn/AEvo2D
Assets/Creature/Sensor/RandomSensor.cs
621
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type ScheduleTimeOffReasonsCollectionResponse. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class ScheduleTimeOffReasonsCollectionResponse { /// <summary> /// Gets or sets the <see cref="IScheduleTimeOffReasonsCollectionPage"/> value. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)] public IScheduleTimeOffReasonsCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
40.735294
153
0.617329
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/ScheduleTimeOffReasonsCollectionResponse.cs
1,385
C#
using System; using Newtonsoft.Json; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// PublishChannel Data Structure. /// </summary> [Serializable] public class PublishChannel : AopObject { /// <summary> /// 当type为MERCHANT_CROWD时,config需填入口令送的密码和图片,样例如下:"config":"{\"PASSWORD\":\"口令送密码\",\"BACKGROUND_LOGO\":\"1T8Pp00AT7eo9NoAJkMR3AAAACMAAQEC\"}" /// </summary> [JsonProperty("config")] public string Config { get; set; } /// <summary> /// 扩展信息,无需配置 /// </summary> [JsonProperty("ext_info")] public string ExtInfo { get; set; } /// <summary> /// 渠道名称 /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// 渠道类型,目前支持以下类型 QR_CODE:二维码投放 SHORT_LINK:短连接投放 SHOP_DETAIL:店铺页投放 PAYMENT_RESULT:支付成功页 MERCHANT_CROWD:口令送 /// URL_WITH_TOKEN:外部发奖活动,只有活动类型为DIRECT_SEND时才支持 EXTERNAL:外部投放,口碑需要感知任何投放内容 /// </summary> [JsonProperty("type")] public string Type { get; set; } } }
26.540541
148
0.656823
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk.Core/Domain/PublishChannel.cs
1,218
C#
using System; using System.Collections.Generic; using Android.App; using Android.Views; using Android.Widget; using iChronoMe.Widgets; namespace iChronoMe.Droid.Adapters { public class ClickActionTypeAdapter : BaseAdapter<string> { List<string> items { get; } = new List<string>(); Dictionary<ClickActionType, int> positions = new Dictionary<ClickActionType, int>(); Dictionary<int, ClickActionType> values = new Dictionary<int, ClickActionType>(); Activity mContext; public ClickActionTypeAdapter(Activity context, bool allowSettings = true, bool allowAnimate = false) { mContext = context; int pos = 0; foreach (ClickActionType ca in Enum.GetValues(typeof(ClickActionType))) { if (ca == ClickActionType.OpenSettings && !allowSettings) continue; if (ca == ClickActionType.Animate && !allowAnimate) continue; if (ca == ClickActionType.CreateAlarm) continue; string c = ca.ToString(); var res = typeof(Resource.String).GetField("ClickActionType_" + c); if (res != null) c = context.Resources.GetString((int)res.GetValue(null)); items.Add(c); values.Add(pos, ca); positions.Add(ca, pos); pos++; } } public override string this[int position] => items[position]; public override int Count => items.Count; public override long GetItemId(int position) => position; public int GetPos(ClickActionType type) { if (!positions.ContainsKey(type)) return -1; return positions[type]; } public ClickActionType GetValue(int pos) { if (!values.ContainsKey(pos)) return ClickActionType.None; return values[pos]; } public override View GetView(int position, View convertView, ViewGroup parent) { var item = items[position]; if (convertView == null) { convertView = mContext.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null); } convertView.FindViewById<TextView>(Android.Resource.Id.Text1).Text = item; return convertView; } } }
31.884615
109
0.566546
[ "MIT-0" ]
maruhe/iChronoMe.Apps
iChronoMe.Android/Source/Adapters/ClickActionTypeAdapter.cs
2,489
C#
using System; using System.Linq; using BenchmarkDotNet.Attributes; using FastEnumUtility.Benchmark.Models; using FastEnumUtility.Internals; namespace FastEnumUtility.Benchmark.Scenarios { public class InitializeBenchmark { #region FastEnum [Benchmark(Baseline = true)] public void FastEnum_Init_All() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var underlyingType = Enum.GetUnderlyingType(type); var values = (Enum.GetValues(type) as T[]).AsReadOnly(); var names = Enum.GetNames(type).ToReadOnlyArray(); var members = names.Select(x => new Member<T>(x)).ToReadOnlyArray(); var minValue = values.DefaultIfEmpty().Min(); var maxValue = values.DefaultIfEmpty().Max(); var isEmpty = values.Count == 0; var isFlags = Attribute.IsDefined(type, typeof(FlagsAttribute)); var distinctedMembers = members.Distinct(new Member<T>.ValueComparer()).ToArray(); var memberByValue = distinctedMembers.ToFrozenDictionary(x => x.Value); var memberByName = members.ToFrozenStringKeyDictionary(x => x.Name); var underlyingOperation = Type.GetTypeCode(type) switch { TypeCode.SByte => SByteOperation<T>.Create(minValue, maxValue, distinctedMembers), TypeCode.Byte => ByteOperation<T>.Create(minValue, maxValue, distinctedMembers), TypeCode.Int16 => Int16Operation<T>.Create(minValue, maxValue, distinctedMembers), TypeCode.UInt16 => UInt16Operation<T>.Create(minValue, maxValue, distinctedMembers), TypeCode.Int32 => Int32Operation<T>.Create(minValue, maxValue, distinctedMembers), TypeCode.UInt32 => UInt32Operation<T>.Create(minValue, maxValue, distinctedMembers), TypeCode.Int64 => Int64Operation<T>.Create(minValue, maxValue, distinctedMembers), TypeCode.UInt64 => UInt64Operation<T>.Create(minValue, maxValue, distinctedMembers), _ => throw new InvalidOperationException(), }; } } [Benchmark] public void FastEnum_Init_Type() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var underlyingType = Enum.GetUnderlyingType(type); } } [Benchmark] public void FastEnum_Init_Values() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var values = Enum.GetValues(type) as T[]; var values2 = values.AsReadOnly(); var isEmpty = values.Length == 0; } } [Benchmark] public void FastEnum_Init_Names() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var names = Enum.GetNames(type).ToReadOnlyArray(); } } [Benchmark] public void FastEnum_Init_Members() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var names = Enum.GetNames(type).ToReadOnlyArray(); var members = names .Select(x => new Member<T>(x)) .ToReadOnlyArray(); } } [Benchmark] public void FastEnum_Init_MinMaxValues() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var values = Enum.GetValues(type) as T[]; var values2 = values.AsReadOnly(); var isEmpty = values.Length == 0; var minValue = values2.DefaultIfEmpty().Min(); var maxValue = values2.DefaultIfEmpty().Max(); } } [Benchmark] public void FastEnum_Init_IsFlags() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var isFlags = Attribute.IsDefined(type, typeof(FlagsAttribute)); } } [Benchmark] public void FastEnum_Init_MembersByName() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var names = Enum.GetNames(type).ToReadOnlyArray(); var members = names .Select(x => new Member<T>(x)) .ToReadOnlyArray(); var memberByName = members.ToFrozenStringKeyDictionary(x => x.Name); } } [Benchmark] public void FastEnum_Init_UnderlyingOperation() { Cache<Fruits>(); static void Cache<T>() where T : struct, Enum { var type = typeof(T); var values = Enum.GetValues(type) as T[]; var values2 = values.AsReadOnly(); var isEmpty = values.Length == 0; var min = values2.DefaultIfEmpty().Min(); var max = values2.DefaultIfEmpty().Max(); var names = Enum.GetNames(type).ToReadOnlyArray(); var members = names .Select(x => new Member<T>(x)) .ToReadOnlyArray(); var distincted = members.OrderBy(x => x.Value).Distinct(new Member<T>.ValueComparer()).ToArray(); var underlyingOperation = Type.GetTypeCode(type) switch { TypeCode.SByte => SByteOperation<T>.Create(min, max, distincted), TypeCode.Byte => ByteOperation<T>.Create(min, max, distincted), TypeCode.Int16 => Int16Operation<T>.Create(min, max, distincted), TypeCode.UInt16 => UInt16Operation<T>.Create(min, max, distincted), TypeCode.Int32 => Int32Operation<T>.Create(min, max, distincted), TypeCode.UInt32 => UInt32Operation<T>.Create(min, max, distincted), TypeCode.Int64 => Int64Operation<T>.Create(min, max, distincted), TypeCode.UInt64 => UInt64Operation<T>.Create(min, max, distincted), _ => throw new InvalidOperationException(), }; } } #endregion #region Enum [Benchmark] public void Enum_GetValues() => _ = Enum.GetValues(typeof(Fruits)) as Fruits[]; [Benchmark] public void Enum_GetNames() => _ = Enum.GetNames(typeof(Fruits)); [Benchmark] public void Enum_GetName() => _ = Enum.GetName(typeof(Fruits), Fruits.Lemon); [Benchmark] public void Enum_IsDefined() => _ = Enum.IsDefined(typeof(Fruits), Fruits.Melon); [Benchmark] public void Enum_Parse() => _ = Enum.Parse(typeof(Fruits), "Apple"); [Benchmark] public void Enum_ToString() => _ = Fruits.Grape.ToString(); #endregion } }
33.622881
113
0.501449
[ "MIT" ]
OronDF343/FastEnum
src/FastEnum.Benchmark/Scenarios/InitializeBenchmark.cs
7,937
C#
using UnityEngine; public class ChangeMaterial : MonoBehaviour { public Material otherMaterial = null; private MeshRenderer meshRenderer = null; private Material originalMaterial = null; private void Awake() { meshRenderer = GetComponent<MeshRenderer>(); originalMaterial = meshRenderer.material; } public void SetOtherMaterial() { meshRenderer.material = otherMaterial; } public void SetOriginalMaterial() { meshRenderer.material = originalMaterial; } }
20.807692
52
0.678373
[ "Apache-2.0" ]
C-Through/XR-SteamVRController
Assets/_SteamVRController/Scripts/Extra/ChangeMaterial.cs
543
C#
using System; using NControl.Abstractions; using Xamarin.Forms; namespace NControl.Controls { /// <summary> /// Paging view. /// </summary> public class PagingView: NControlView { /// <summary> /// Initializes a new instance of the <see cref="NControl.Controls.PagingView"/> class. /// </summary> public PagingView() { HeightRequest = 22; } /// <summary> /// Draw the specified canvas and rect. /// </summary> /// <param name="canvas">Canvas.</param> /// <param name="rect">Rect.</param> public override void Draw (NGraphics.ICanvas canvas, NGraphics.Rect rect) { base.Draw (canvas, rect); if (PageCount <= 0) return; var dotWidth = rect.Height - 16; var spacing = dotWidth; var totalWidthNeeded = (PageCount * (dotWidth + spacing)) - dotWidth; // Draw dots double midx = rect.Width / 2; double midy = rect.Height / 2; var x = midx - (totalWidthNeeded / 2); var pen = new NGraphics.Pen (IndicatorColor.ToNColor (), 0.5); var brush = new NGraphics.SolidBrush (IndicatorColor.ToNColor ()); for (int i = 0; i < PageCount; i++) { canvas.DrawEllipse (new NGraphics.Rect (x, midy - (dotWidth / 2), dotWidth, dotWidth), pen, i==Page ? brush : null); x += dotWidth + spacing; } } /// <summary> /// The PageCount property. /// </summary> public static BindableProperty PageCountProperty = BindableProperty.Create(nameof(PageCount), typeof(int), typeof(PagingView), 0, propertyChanged: (bindable, oldValue, newValue) => { var ctrl = (PagingView)bindable; ctrl.PageCount = (int)newValue; }); /// <summary> /// Gets or sets the PageCount of the PagingView instance. /// </summary> /// <value>The color of the buton.</value> public int PageCount { get{ return (int)GetValue (PageCountProperty); } set { SetValue (PageCountProperty, value); Invalidate (); } } /// <summary> /// The Page property. /// </summary> public static BindableProperty PageProperty = BindableProperty.Create(nameof(Page), typeof(int), typeof(PagingView), 0, BindingMode.TwoWay, propertyChanged: (bindable, oldValue, newValue) => { var ctrl = (PagingView)bindable; ctrl.Page = (int)newValue; }); /// <summary> /// Gets or sets the Page of the PagingView instance. /// </summary> /// <value>The color of the buton.</value> public int Page { get{ return (int)GetValue (PageProperty); } set { SetValue (PageProperty, value); Invalidate (); } } /// <summary> /// The IndicatorColor property. /// </summary> public static BindableProperty IndicatorColorProperty = BindableProperty.Create(nameof(IndicatorColor), typeof(Color), typeof(PagingView), Color.Gray, propertyChanged: (bindable, oldValue, newValue) => { var ctrl = (PagingView)bindable; ctrl.IndicatorColor = (Color)newValue; }); /// <summary> /// Gets or sets the IndicatorColor of the PagingView instance. /// </summary> /// <value>The color of the buton.</value> public Color IndicatorColor { get{ return (Color)GetValue (IndicatorColorProperty); } set { SetValue (IndicatorColorProperty, value); Invalidate (); } } } }
26.719008
97
0.646458
[ "MIT" ]
Neseek77/NControl.Controls
NControl.Controls/NControl.Controls/PagingView.cs
3,235
C#
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DataBindingDemo { public enum ProductCategory { Books, Computers, DvDs, Electronics, Home, Sports } }
21.933333
104
0.6231
[ "MIT" ]
21pages/WPF-Samples
Sample Applications/DataBindingDemo/ProductCategory.cs
329
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Meteor : MonoBehaviour { // Start is called before the first frame update public GameObject target; private Rigidbody rigidbody; [SerializeField] float speed; [SerializeField] HexController hexController; private Vector3 point; void Start() { target = GameObject.FindWithTag("Planet"); rigidbody = this.GetComponent<Rigidbody>(); Vector3 temp = (target.transform.position - this.transform.position).normalized * speed; //Debug.Log(temp); //Debug.Log(this.transform.position); rigidbody.AddForce(temp); } // Update is called once per frame void Update() { } private void OnCollisionEnter(Collision collision) { Collider[] hitColliders = Physics.OverlapSphere(collision.GetContact(0).point, 1); point = collision.GetContact(0).point; //hexController.effectedByMeteor.Add(col.gameObject); HexData hexData; if (hitColliders[0].gameObject.TryGetComponent<HexData>(out hexData)) { hexData.live(); //hexData.setDisaster(DisasterState.Fire); } Destroy(this.gameObject); } void OnDrawGizmos() { Gizmos.color = Color.blue; Gizmos.DrawSphere(point, 1); } }
27.54717
97
0.610274
[ "Apache-2.0" ]
olesgedz/globalgamejam2020
Assets/Scripts/Meteor.cs
1,462
C#
using System; using System.Collections; using System.Drawing; using System.IO; using System.Web; using CookComputing.Blogger; using CookComputing.MetaWeblog; using CookComputing.XmlRpc; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using umbraco.BusinessLogic; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.datatype; using umbraco.cms.businesslogic.media; using umbraco.cms.businesslogic.property; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using Umbraco.Core.Security; using umbraco.presentation.channels.businesslogic; using Post = CookComputing.MetaWeblog.Post; using System.Collections.Generic; using System.Web.Security; using Umbraco.Core.IO; using Umbraco.Core; namespace umbraco.presentation.channels { public abstract class UmbracoMetaWeblogAPI : XmlRpcService, IMetaWeblog { internal readonly MediaFileSystem _fs; protected UmbracoMetaWeblogAPI() { _fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>(); } [XmlRpcMethod("blogger.deletePost", Description = "Deletes a post.")] [return: XmlRpcReturnValue(Description = "Always returns true.")] public bool deletePost( string appKey, string postid, string username, string password, [XmlRpcParameter( Description = "Where applicable, this specifies whether the blog " + "should be republished after the post has been deleted.")] bool publish) { if (ValidateUser(username, password)) { Channel userChannel = new Channel(username); new Document(int.Parse(postid)) .delete(); return true; } return false; } public object editPost( string postid, string username, string password, Post post, bool publish) { if (ValidateUser(username, password)) { Channel userChannel = new Channel(username); Document doc = new Document(Convert.ToInt32(postid)); doc.Text = HttpContext.Current.Server.HtmlDecode(post.title); // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") doc.getProperty(userChannel.FieldExcerptAlias).Value = removeLeftUrl(post.mt_excerpt); if (UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent) doc.getProperty(userChannel.FieldDescriptionAlias).Value = library.Tidy(removeLeftUrl(post.description), false); else doc.getProperty(userChannel.FieldDescriptionAlias).Value = removeLeftUrl(post.description); updateCategories(doc, post, userChannel); if (publish) { doc.SaveAndPublish(new User(username)); } return true; } else { return false; } } private void updateCategories(Document doc, Post post, Channel userChannel) { if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "") { ContentType blogPostType = ContentType.GetByAlias(userChannel.DocumentTypeAlias); PropertyType categoryType = blogPostType.getPropertyType(userChannel.FieldCategoriesAlias); String[] categories = post.categories; string categoryValue = ""; interfaces.IUseTags tags = UseTags(categoryType); if (tags != null) { tags.RemoveTagsFromNode(doc.Id); for (int i = 0; i < categories.Length; i++) { tags.AddTagToNode(doc.Id, categories[i]); } //If the IUseTags provider manually set the property value to something on the IData interface then we should persist this //code commented as for some reason, even though the IUseTags control is setting IData.Value it is null here //could be a cache issue, or maybe it's a different instance of the IData or something, rather odd //doc.getProperty(userChannel.FieldCategoriesAlias).Value = categoryType.DataTypeDefinition.DataType.Data.Value; //Instead, set the document property to CSV of the tags - this WILL break custom editors for tags which don't adhere to the //pseudo standard that the .Value of the property contains CSV tags. doc.getProperty(userChannel.FieldCategoriesAlias).Value = string.Join(",", categories); } else { for (int i = 0; i < categories.Length; i++) { PreValue pv = new PreValue(categoryType.DataTypeDefinition.Id, categories[i]); categoryValue += pv.Id + ","; } if (categoryValue.Length > 0) categoryValue = categoryValue.Substring(0, categoryValue.Length - 1); doc.getProperty(userChannel.FieldCategoriesAlias).Value = categoryValue; } } } public CategoryInfo[] getCategories( string blogid, string username, string password) { if (ValidateUser(username, password)) { Channel userChannel = new Channel(username); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "") { // Find the propertytype via the document type ContentType blogPostType = ContentType.GetByAlias(userChannel.DocumentTypeAlias); PropertyType categoryType = blogPostType.getPropertyType(userChannel.FieldCategoriesAlias); // check if the datatype uses tags or prevalues CategoryInfo[] returnedCategories = null; interfaces.IUseTags tags = UseTags(categoryType); if (tags != null) { List<interfaces.ITag> alltags = tags.GetAllTags(); if (alltags != null) { returnedCategories = new CategoryInfo[alltags.Count]; int counter = 0; foreach (interfaces.ITag t in alltags) { CategoryInfo ci = new CategoryInfo(); ci.title = t.TagCaption; ci.categoryid = t.Id.ToString(); ci.description = ""; ci.rssUrl = ""; ci.htmlUrl = ""; returnedCategories[counter] = ci; counter++; } } else { returnedCategories = new CategoryInfo[0]; } } else { SortedList categories = PreValues.GetPreValues(categoryType.DataTypeDefinition.Id); returnedCategories = new CategoryInfo[categories.Count]; IDictionaryEnumerator ide = categories.GetEnumerator(); int counter = 0; while (ide.MoveNext()) { PreValue category = (PreValue)ide.Value; CategoryInfo ci = new CategoryInfo(); ci.title = category.Value; ci.categoryid = category.Id.ToString(); ci.description = ""; ci.rssUrl = ""; ci.htmlUrl = ""; returnedCategories[counter] = ci; counter++; } } return returnedCategories; } } throw new ArgumentException("Categories doesn't work for this channel, they might not have been activated. Contact your umbraco administrator."); } public static interfaces.IUseTags UseTags(PropertyType categoryType) { if (typeof(interfaces.IUseTags).IsAssignableFrom(categoryType.DataTypeDefinition.DataType.DataEditor.GetType())) { interfaces.IUseTags tags = (interfaces.IUseTags)categoryType.DataTypeDefinition.DataType.DataEditor as interfaces.IUseTags; return tags; } return null; } public Post getPost( string postid, string username, string password) { if (ValidateUser(username, password)) { Channel userChannel = new Channel(username); Document d = new Document(int.Parse(postid)); Post p = new Post(); p.title = d.Text; p.description = d.getProperty(userChannel.FieldDescriptionAlias).Value.ToString(); // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") p.mt_excerpt = d.getProperty(userChannel.FieldExcerptAlias).Value.ToString(); // Categories if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "" && d.getProperty(userChannel.FieldCategoriesAlias) != null && d.getProperty(userChannel.FieldCategoriesAlias).Value != null && d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString() != "") { String categories = d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString(); char[] splitter = { ',' }; String[] categoryIds = categories.Split(splitter); p.categories = categoryIds; } p.postid = postid; p.permalink = library.NiceUrl(d.Id); p.dateCreated = d.CreateDateTime; p.link = p.permalink; return p; } else throw new ArgumentException(string.Format("Error retriving post with id: '{0}'", postid)); } public Post[] getRecentPosts( string blogid, string username, string password, int numberOfPosts) { if (ValidateUser(username, password)) { ArrayList blogPosts = new ArrayList(); ArrayList blogPostsObjects = new ArrayList(); User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else { if (u.StartNodeId == -1) { rootDoc = Document.GetRootDocuments()[0]; } else { rootDoc = new Document(u.StartNodeId); } } //store children array here because iterating over an Array object is very inneficient. var c = rootDoc.Children; foreach (Document d in c) { int count = 0; blogPosts.AddRange( findBlogPosts(userChannel, d, u.Name, ref count, numberOfPosts, userChannel.FullTree)); } blogPosts.Sort(new DocumentSortOrderComparer()); foreach (Object o in blogPosts) { Document d = (Document)o; Post p = new Post(); p.dateCreated = d.CreateDateTime; p.userid = username; p.title = d.Text; p.permalink = library.NiceUrl(d.Id); p.description = d.getProperty(userChannel.FieldDescriptionAlias).Value.ToString(); p.link = library.NiceUrl(d.Id); p.postid = d.Id.ToString(); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "" && d.getProperty(userChannel.FieldCategoriesAlias) != null && d.getProperty(userChannel.FieldCategoriesAlias).Value != null && d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString() != "") { String categories = d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString(); char[] splitter = { ',' }; String[] categoryIds = categories.Split(splitter); p.categories = categoryIds; } // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") p.mt_excerpt = d.getProperty(userChannel.FieldExcerptAlias).Value.ToString(); blogPostsObjects.Add(p); } return (Post[])blogPostsObjects.ToArray(typeof(Post)); } else { return null; } } protected ArrayList findBlogPosts(Channel userChannel, Document d, String userName, ref int count, int max, bool fullTree) { ArrayList list = new ArrayList(); ContentType ct = d.ContentType; if (ct.Alias.Equals(userChannel.DocumentTypeAlias) & (count < max)) { list.Add(d); count = count + 1; } if (d.Children != null && d.Children.Length > 0 && fullTree) { //store children array here because iterating over an Array object is very inneficient. var c = d.Children; foreach (Document child in c) { if (count < max) { list.AddRange(findBlogPosts(userChannel, child, userName, ref count, max, true)); } } } return list; } public string newPost( string blogid, string username, string password, Post post, bool publish) { if (ValidateUser(username, password)) { Channel userChannel = new Channel(username); User u = new User(username); Document doc = Document.MakeNew(HttpContext.Current.Server.HtmlDecode(post.title), DocumentType.GetByAlias(userChannel.DocumentTypeAlias), u, userChannel.StartNode); // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") doc.getProperty(userChannel.FieldExcerptAlias).Value = removeLeftUrl(post.mt_excerpt); // Description if (UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent) doc.getProperty(userChannel.FieldDescriptionAlias).Value = library.Tidy(removeLeftUrl(post.description), false); else doc.getProperty(userChannel.FieldDescriptionAlias).Value = removeLeftUrl(post.description); // Categories updateCategories(doc, post, userChannel); // check release date if (post.dateCreated.Year > 0001) { publish = false; doc.ReleaseDate = post.dateCreated; } if (publish) { doc.SaveAndPublish(new User(username)); } return doc.Id.ToString(); } else throw new ArgumentException("Error creating post"); } protected MediaObjectInfo newMediaObjectLogicForWord( string blogid, string username, string password, FileData file) { UrlData ud = newMediaObjectLogic(blogid, username, password, file); MediaObjectInfo moi = new MediaObjectInfo(); moi.url = ud.url; return moi; } protected UrlData newMediaObjectLogic( string blogid, string username, string password, FileData file) { if (ValidateUser(username, password)) { User u = new User(username); Channel userChannel = new Channel(username); UrlData fileUrl = new UrlData(); if (userChannel.ImageSupport) { Media rootNode; if (userChannel.MediaFolder > 0) rootNode = new Media(userChannel.MediaFolder); else rootNode = new Media(u.StartMediaId); // Create new media Media m = Media.MakeNew(file.name, MediaType.GetByAlias(userChannel.MediaTypeAlias), u, rootNode.Id); Property fileObject = m.getProperty(userChannel.MediaTypeFileProperty); var filename = file.name.Replace("/", "_"); var relativeFilePath = _fs.GetRelativePath(fileObject.Id, filename); fileObject.Value = _fs.GetUrl(relativeFilePath); fileUrl.url = fileObject.Value.ToString(); if (!fileUrl.url.StartsWith("http")) { var protocol = GlobalSettings.UseSSL ? "https" : "http"; fileUrl.url = protocol + "://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + fileUrl.url; } _fs.AddFile(relativeFilePath, new MemoryStream(file.bits)); // Try updating standard file values try { string orgExt = ""; // Size if (m.getProperty(Constants.Conventions.Media.Bytes) != null) m.getProperty(Constants.Conventions.Media.Bytes).Value = file.bits.Length; // Extension if (m.getProperty(Constants.Conventions.Media.Extension) != null) { orgExt = ((string) file.name.Substring(file.name.LastIndexOf(".") + 1, file.name.Length - file.name.LastIndexOf(".") - 1)); m.getProperty(Constants.Conventions.Media.Extension).Value = orgExt.ToLower(); } // Width and Height // Check if image and then get sizes, make thumb and update database if (m.getProperty(Constants.Conventions.Media.Width) != null && m.getProperty(Constants.Conventions.Media.Height) != null && ",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt.ToLower() + ",") > 0) { int fileWidth; int fileHeight; var stream = _fs.OpenFile(relativeFilePath); Image image = Image.FromStream(stream); fileWidth = image.Width; fileHeight = image.Height; stream.Close(); try { m.getProperty(Constants.Conventions.Media.Width).Value = fileWidth.ToString(); m.getProperty(Constants.Conventions.Media.Height).Value = fileHeight.ToString(); } catch { } } } catch { } return fileUrl; } else throw new ArgumentException( "Image Support is turned off in this channel. Modify channel settings in umbraco to enable image support."); } return new UrlData(); } private static bool ValidateUser(string username, string password) { var provider = MembershipProviderExtensions.GetUsersMembershipProvider(); return provider.ValidateUser(username, password); } [XmlRpcMethod("blogger.getUsersBlogs", Description = "Returns information on all the blogs a given user " + "is a member.")] public BlogInfo[] getUsersBlogs( string appKey, string username, string password) { if (ValidateUser(username, password)) { BlogInfo[] blogs = new BlogInfo[1]; User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else rootDoc = new Document(u.StartNodeId); BlogInfo bInfo = new BlogInfo(); bInfo.blogName = userChannel.Name; bInfo.blogid = rootDoc.Id.ToString(); bInfo.url = library.NiceUrlWithDomain(rootDoc.Id, true); blogs[0] = bInfo; return blogs; } throw new ArgumentException(string.Format("No data found for user with username: '{0}'", username)); } private string removeLeftUrl(string text) { return text.Replace(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority), ""); } } }
42.298932
158
0.488221
[ "MIT" ]
bowserm/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/channels/UmbracoMetaWeblogAPI.cs
23,772
C#
namespace PartsUnlimited.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<PartsUnlimited.Models.PartsUnlimitedContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(PartsUnlimited.Models.PartsUnlimitedContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
32.25
112
0.571705
[ "MIT" ]
ALMTraining/MyPartsUnlimited
src/PartsUnlimitedWebsite/Migrations/Configuration.cs
1,032
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.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementGetArgs : Pulumi.ResourceArgs { /// <summary> /// The part of a web request that you want AWS WAF to inspect. See Field to Match below for details. /// </summary> [Input("fieldToMatch")] public Input<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementFieldToMatchGetArgs>? FieldToMatch { get; set; } /// <summary> /// The area within the portion of a web request that you want AWS WAF to search for `search_string`. Valid values include the following: `EXACTLY`, `STARTS_WITH`, `ENDS_WITH`, `CONTAINS`, `CONTAINS_WORD`. See the AWS [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_ByteMatchStatement.html) for more information. /// </summary> [Input("positionalConstraint", required: true)] public Input<string> PositionalConstraint { get; set; } = null!; /// <summary> /// A string value that you want AWS WAF to search for. AWS WAF searches only in the part of web requests that you designate for inspection in `field_to_match`. The maximum length of the value is 50 bytes. /// </summary> [Input("searchString", required: true)] public Input<string> SearchString { get; set; } = null!; [Input("textTransformations", required: true)] private InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementTextTransformationGetArgs>? _textTransformations; /// <summary> /// Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See Text Transformation below for details. /// </summary> public InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementTextTransformationGetArgs> TextTransformations { get => _textTransformations ?? (_textTransformations = new InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementTextTransformationGetArgs>()); set => _textTransformations = value; } public WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementGetArgs() { } } }
56.5
344
0.740177
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementGetArgs.cs
2,825
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Tools.Common; namespace Microsoft.DotNet.Tools.Sln.Remove { internal class RemoveProjectFromSolutionCommand : CommandBase { private readonly AppliedOption _appliedCommand; private readonly string _fileOrDirectory; public RemoveProjectFromSolutionCommand( AppliedOption appliedCommand, string fileOrDirectory, ParseResult parseResult) : base(parseResult) { if (appliedCommand == null) { throw new ArgumentNullException(nameof(appliedCommand)); } if (appliedCommand.Arguments.Count == 0) { throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneProjectToRemove); } _appliedCommand = appliedCommand; _fileOrDirectory = fileOrDirectory; } public override int Execute() { SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(_fileOrDirectory); var baseDirectory = PathUtility.EnsureTrailingSlash(slnFile.BaseDirectory); var relativeProjectPaths = _appliedCommand.Arguments.Select(p => { var fullPath = Path.GetFullPath(p); return Path.GetRelativePath( baseDirectory, Directory.Exists(fullPath) ? MsbuildProject.GetProjectFileFromDirectory(fullPath).FullName : fullPath ); }); bool slnChanged = false; foreach (var path in relativeProjectPaths) { slnChanged |= slnFile.RemoveProject(path); } slnFile.RemoveEmptyConfigurationSections(); slnFile.RemoveEmptySolutionFolders(); if (slnChanged) { slnFile.Write(); } return 0; } } }
32.222222
103
0.6125
[ "MIT" ]
5l1v3r1/sdk-1
src/Cli/dotnet/commands/dotnet-sln/remove/Program.cs
2,320
C#
using Orchard.ContentManagement; namespace Contrib.RewriteRules.Models { public class RedirectSettingsPart : ContentPart<RedirectSettingsPartRecord> { public string Rules { get { return Record.Rules; } set { Record.Rules = value; } } public bool Enabled { get { return Record.Enabled; } set { Record.Enabled = value; } } } }
27.6
81
0.596618
[ "BSD-3-Clause" ]
bill-cooper/catc-cms
src/Orchard.Web/Modules/Contrib.RewriteRules/Models/RedirectSettingsPart.cs
414
C#
using Microsoft.EntityFrameworkCore.Storage; using Mix.Cms.Lib.Models.Cms; using Mix.Cms.Lib.Repositories; using Mix.Cms.Lib.Services; using Mix.Cms.Lib.ViewModels.MixConfigurations; using Mix.Common.Helper; using Mix.Domain.Core.ViewModels; using Mix.Domain.Data.ViewModels; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using static Mix.Cms.Lib.MixEnums; namespace Mix.Cms.Lib.ViewModels.MixThemes { public class DeleteViewModel : ViewModelBase<MixCmsContext, MixTheme, DeleteViewModel> { #region Properties #region Models [JsonProperty("id")] public int Id { get; set; } [JsonProperty("specificulture")] public string Specificulture { get; set; } [JsonProperty("priority")] public int Priority { get; set; } [JsonProperty("name")] public string Name { get; set; } [Required] [JsonProperty("title")] public string Title { get; set; } [JsonProperty("image")] public string Image { get; set; } [JsonProperty("thumbnail")] public string Thumbnail { get; set; } [JsonProperty("createdBy")] public string CreatedBy { get; set; } [JsonProperty("createdDateTime")] public DateTime CreatedDateTime { get; set; } [JsonProperty("status")] public MixContentStatus Status { get; set; } #endregion Models #region Views [JsonProperty("domain")] public string Domain { get { return MixService.GetConfig<string>("Domain"); } } [JsonProperty("imageUrl")] public string ImageUrl { get { if (!string.IsNullOrEmpty(Image) && (Image.IndexOf("http") == -1) && Image[0] != '/') { return CommonHelper.GetFullPath(new string[] { Domain, Image }); } else { return Image; } } } [JsonProperty("thumbnailUrl")] public string ThumbnailUrl { get { if (Thumbnail != null && Thumbnail.IndexOf("http") == -1 && Thumbnail[0] != '/') { return CommonHelper.GetFullPath(new string[] { Domain, Thumbnail }); } else { return string.IsNullOrEmpty(Thumbnail) ? ImageUrl : Thumbnail; } } } [JsonProperty("isActived")] public bool IsActived { get; set; } [JsonProperty("templateAsset")] public FileViewModel TemplateAsset { get; set; } [JsonProperty("asset")] public FileViewModel Asset { get; set; } [JsonProperty("assetFolder")] public string AssetFolder { get { return $"wwwroot/content/templates/{Name}/assets"; } } public string UploadsFolder { get { return $"wwwroot/content/templates/{Name}/uploads"; } } [JsonProperty("templateFolder")] public string TemplateFolder { get { return $"{MixConstants.Folder.TemplatesFolder}/{Name}"; } } public List<MixTemplates.DeleteViewModel> Templates { get; set; } #endregion Views #endregion Properties #region Contructors public DeleteViewModel() : base() { } public DeleteViewModel(MixTheme model, MixCmsContext _context = null, IDbContextTransaction _transaction = null) : base(model, _context, _transaction) { } #endregion Contructors #region Overrides public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { Templates = MixTemplates.DeleteViewModel.Repository.GetModelListBy(t => t.ThemeId == Id, _context: _context, _transaction: _transaction).Data; TemplateAsset = new FileViewModel() { FileFolder = $"wwwroot/import/themes/{DateTime.UtcNow.ToShortDateString()}/{Name}" }; Asset = new FileViewModel() { FileFolder = AssetFolder }; } #region Async public override async Task<RepositoryResponse<bool>> RemoveRelatedModelsAsync(DeleteViewModel view, MixCmsContext _context = null, IDbContextTransaction _transaction = null) { var result = new RepositoryResponse<bool>() { IsSucceed = true }; foreach (var item in Templates) { if (result.IsSucceed) { var tmp = await item.RemoveModelAsync(true, _context, _transaction); ViewModelHelper.HandleResult(tmp, ref result); } } if (result.IsSucceed) { FileRepository.Instance.DeleteFolder(AssetFolder); } return result; } #endregion Async #endregion Overrides #region Expand private async Task<RepositoryResponse<bool>> ImportThemeAsync(MixTheme parent, MixCmsContext _context, IDbContextTransaction _transaction) { var result = new RepositoryResponse<bool>() { IsSucceed = true }; string filePath = $"wwwroot/{TemplateAsset.FileFolder}/{TemplateAsset.Filename}{TemplateAsset.Extension}"; if (File.Exists(filePath)) { string outputFolder = $"{TemplateAsset.FileFolder}/Extract"; FileRepository.Instance.DeleteFolder(outputFolder); FileRepository.Instance.CreateDirectoryIfNotExist(outputFolder); FileRepository.Instance.UnZipFile(filePath, outputFolder); //Move Unzip Asset folder FileRepository.Instance.CopyDirectory($"{outputFolder}/Assets", $"{AssetFolder}"); //Move Unzip Templates folder FileRepository.Instance.CopyDirectory($"{outputFolder}/Templates", TemplateFolder); //Move Unzip Uploads folder FileRepository.Instance.CopyDirectory($"{outputFolder}/Uploads", $"{UploadsFolder}"); // Get SiteStructure var strSchema = FileRepository.Instance.GetFile("schema.json", $"{outputFolder}/Data"); var siteStructures = JObject.Parse(strSchema.Content).ToObject<SiteStructureViewModel>(); FileRepository.Instance.DeleteFolder(outputFolder); FileRepository.Instance.DeleteFile(filePath); //Import Site Structures result = await siteStructures.ImportAsync(Specificulture); if (result.IsSucceed) { // Save template files to db var files = FileRepository.Instance.GetFilesWithContent(TemplateFolder); //TODO: Create default asset foreach (var file in files) { string content = file.Content.Replace($"/Content/Templates/{siteStructures.ThemeName}/", $"/Content/Templates/{Name}/"); MixTemplates.DeleteViewModel template = new MixTemplates.DeleteViewModel( new MixTemplate() { FileFolder = file.FileFolder, FileName = file.Filename, Content = file.Content, Extension = file.Extension, CreatedDateTime = DateTime.UtcNow, LastModified = DateTime.UtcNow, ThemeId = parent.Id, ThemeName = parent.Name, FolderType = file.FolderName, ModifiedBy = CreatedBy }); var saveResult = await template.SaveModelAsync(true, _context, _transaction); result.IsSucceed = result.IsSucceed && saveResult.IsSucceed; if (!saveResult.IsSucceed) { result.IsSucceed = false; result.Exception = saveResult.Exception; result.Errors.AddRange(saveResult.Errors); break; } } } } return result; } private async Task<RepositoryResponse<bool>> ActivedThemeAsync(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { var result = new RepositoryResponse<bool>() { IsSucceed = true }; SystemConfigurationViewModel config = (await SystemConfigurationViewModel.Repository.GetSingleModelAsync( c => c.Keyword == MixConstants.ConfigurationKeyword.ThemeName && c.Specificulture == Specificulture , _context, _transaction)).Data; if (config == null) { config = new SystemConfigurationViewModel() { Keyword = MixConstants.ConfigurationKeyword.ThemeName, Specificulture = Specificulture, Category = "Site", DataType = MixDataType.Text, Description = "Cms Theme", Value = Name }; } else { config.Value = Name; } var saveConfigResult = await config.SaveModelAsync(false, _context, _transaction); if (saveConfigResult.IsSucceed) { SystemConfigurationViewModel configFolder = (await SystemConfigurationViewModel.Repository.GetSingleModelAsync( c => c.Keyword == MixConstants.ConfigurationKeyword.ThemeFolder && c.Specificulture == Specificulture , _context, _transaction)).Data; configFolder.Value = Name; saveConfigResult = await configFolder.SaveModelAsync(false, _context, _transaction); } ViewModelHelper.HandleResult(saveConfigResult, ref result); if (result.IsSucceed) { SystemConfigurationViewModel configId = (await SystemConfigurationViewModel.Repository.GetSingleModelAsync( c => c.Keyword == MixConstants.ConfigurationKeyword.ThemeId && c.Specificulture == Specificulture, _context, _transaction)).Data; if (configId == null) { configId = new SystemConfigurationViewModel() { Keyword = MixConstants.ConfigurationKeyword.ThemeId, Specificulture = Specificulture, Category = "Site", DataType = MixDataType.Text, Description = "Cms Theme Id", Value = Model.Id.ToString() }; } else { configId.Value = Model.Id.ToString(); } var saveResult = await configId.SaveModelAsync(false, _context, _transaction); ViewModelHelper.HandleResult(saveResult, ref result); } return result; } private async Task<RepositoryResponse<bool>> CreateDefaultThemeTemplatesAsync(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { var result = new RepositoryResponse<bool>() { IsSucceed = true }; string defaultFolder = $"{MixService.GetConfig<string>(MixConstants.ConfigurationKeyword.DefaultBlankTemplateFolder) }"; //CommonHelper.GetFullPath(new string[] { // MixConstants.Folder.TemplatesFolder, // MixService.GetConfig<string>(MixConstants.ConfigurationKeyword.DefaultTemplateFolder) }); bool copyResult = FileRepository.Instance.CopyDirectory(defaultFolder, TemplateFolder); var files = FileRepository.Instance.GetFilesWithContent(TemplateFolder); var id = _context.MixTemplate.Count() + 1; //TODO: Create default asset foreach (var file in files) { MixTemplates.InitViewModel template = new MixTemplates.InitViewModel( new MixTemplate() { Id = id, FileFolder = file.FileFolder, FileName = file.Filename, Content = file.Content, Extension = file.Extension, CreatedDateTime = DateTime.UtcNow, LastModified = DateTime.UtcNow, ThemeId = Model.Id, ThemeName = Model.Name, FolderType = file.FolderName, ModifiedBy = CreatedBy }, _context, _transaction); var saveResult = await template.SaveModelAsync(true, _context, _transaction); ViewModelHelper.HandleResult(saveResult, ref result); if (!result.IsSucceed) { break; } else { id += 1; } } return result; } private RepositoryResponse<bool> ImportAssetsAsync(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { var result = new RepositoryResponse<bool>(); string fullPath = $"{Asset.FileFolder}/{Asset.Filename}{Asset.Extension}"; if (File.Exists(fullPath)) { FileRepository.Instance.UnZipFile(fullPath, Asset.FileFolder); //InitAssetStyle(); result.IsSucceed = true; } else { result.Errors.Add("Cannot saved asset file"); } return result; } private async Task InitAssetStyleAsync(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { var files = FileRepository.Instance.GetWebFiles(AssetFolder); StringBuilder strStyles = new StringBuilder(); foreach (var css in files.Where(f => f.Extension == ".css")) { strStyles.Append($" <link href='{css.FileFolder}/{css.Filename}{css.Extension}' rel='stylesheet'/>"); } StringBuilder strScripts = new StringBuilder(); foreach (var js in files.Where(f => f.Extension == ".js")) { strScripts.Append($" <script src='{js.FileFolder}/{js.Filename}{js.Extension}'></script>"); } var layout = MixTemplates.InitViewModel.Repository.GetSingleModel( t => t.FileName == "_Layout" && t.ThemeId == Model.Id , _context, _transaction); layout.Data.Content = layout.Data.Content.Replace("<!--[STYLES]-->" , string.Format(@"{0}" , strStyles)); layout.Data.Content = layout.Data.Content.Replace("<!--[SCRIPTS]-->" , string.Format(@"{0}" , strScripts)); await layout.Data.SaveModelAsync(true, _context, _transaction); } #endregion Expand } }
40.258228
181
0.54402
[ "MIT" ]
Noriffik/mix.core
src/Mix.Cms.Lib/ViewModels/MixThemes/DeleteViewModel.cs
15,904
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tizen.Wearable.CircularUI.Forms; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace WearableUIGallery.TC { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TCCircleSliderSurfaceItem1 : CirclePage { public TCCircleSliderSurfaceItem1() { InitializeComponent (); } void OnClick(object sender, EventArgs args) { var btn = sender as Button; if (btn.Text.Equals("Enable")) { slider.Value = 12; slider.IsEnabled = true; btn.Text = "Disable"; } else { slider.BarAngle = 60; slider.IsEnabled = false; btn.Text = "Enable"; } } } }
24.473684
64
0.558065
[ "SHL-0.51" ]
hj-na-park/Tizen.CircularUI
test/WearableUIGallery/WearableUIGallery/TC/TCCircleSliderSurfaceItem1.xaml.cs
932
C#
/* * Copyright 2010-2014 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 appconfig-2019-10-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AppConfig.Model { /// <summary> /// Container for the parameters to the DeleteDeploymentStrategy operation. /// Delete a deployment strategy. Deleting a deployment strategy does not delete a configuration /// from a host. /// </summary> public partial class DeleteDeploymentStrategyRequest : AmazonAppConfigRequest { private string _deploymentStrategyId; /// <summary> /// Gets and sets the property DeploymentStrategyId. /// <para> /// The ID of the deployment strategy you want to delete. /// </para> /// </summary> [AWSProperty(Required=true)] public string DeploymentStrategyId { get { return this._deploymentStrategyId; } set { this._deploymentStrategyId = value; } } // Check to see if DeploymentStrategyId property is set internal bool IsSetDeploymentStrategyId() { return this._deploymentStrategyId != null; } } }
32.288136
107
0.68084
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/AppConfig/Generated/Model/DeleteDeploymentStrategyRequest.cs
1,905
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VEF.Interfaces.Services { /// <summary> /// Interface IThemeManager /// </summary> public interface IThemeManager { /// <summary> /// The list of themes registered with the theme manager /// </summary> /// <value>The themes.</value> ObservableCollection<ITheme> Themes { get; } /// <summary> /// Adds a theme to the theme manager /// </summary> /// <param name="theme">The theme to add</param> /// <returns><c>true</c> if successful, <c>false</c> otherwise</returns> bool AddTheme(ITheme theme); /// <summary> /// Called to set the current theme from the list of themes /// </summary> /// <param name="name">The name of the theme</param> /// <returns><c>true</c> if successful, <c>false</c> otherwise</returns> bool SetCurrent(string name); /// <summary> /// Returns the current theme set in the theme manager /// </summary> /// <value>The current theme.</value> ITheme CurrentTheme { get; } } }
30.119048
80
0.589723
[ "MIT" ]
devxkh/FrankE
Editor/VEF/VEF.Shared/PCL/Interfaces/Services/IThemeManager.cs
1,267
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace TWX3 { /// <summary> /// Interaction logic for License.xaml /// </summary> public partial class About : Window { public About() { InitializeComponent(); } private void LicenseLinkClick(object sender, MouseButtonEventArgs e) { this.Hide(); Window license = new License(); license.ShowDialog(); this.Close(); } private void OkButtonClick(object sender, RoutedEventArgs e) { this.Close(); } private void GridMouseDown(object sender, MouseButtonEventArgs e) { try { DragMove(); } catch { } } } }
21.509434
76
0.59386
[ "MIT" ]
TW2002/TWX-Sharp
Source/TWX30/Proxy-old/Windows/About.xaml.cs
1,142
C#
using System.Text; namespace LinqToDB.DataProvider.Informix { using System.Collections.Generic; using SqlQuery; partial class InformixSqlBuilder { // VALUES(...) syntax not supported protected override bool IsValuesSyntaxSupported => false; // or also we can use sysmaster:sysdual added in 11.70 // // but SET present even in ancient 9.x versions (but not it 7.x it seems) protected override string FakeTable => "table(set{1})"; // Informix is too lazy to infer types itself from context protected override bool IsSqlValuesTableValueTypeRequired(SqlValuesTable source, IReadOnlyList<ISqlExpression[]> rows, int row, int column) => true; protected override void BuildMergeInto(SqlMergeStatement merge) { StringBuilder.Append("MERGE "); if (merge.Hint != null) { StringBuilder .Append("{+ ") .Append(merge.Hint) .Append(" } "); } StringBuilder.Append("INTO "); BuildTableName(merge.Target, true, true); StringBuilder.AppendLine(); } } }
27.5
151
0.686124
[ "MIT" ]
AndreyAndryushinPSB/linq2db
Source/LinqToDB/DataProvider/Informix/InformixSqlBuilder.Merge.cs
1,010
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class MediaDeviceControllerPS : ScriptableDeviceComponentPS { [Ordinal(0)] [RED("activeChannelName")] public CString ActiveChannelName { get; set; } [Ordinal(1)] [RED("activeStation")] public CInt32 ActiveStation { get; set; } [Ordinal(2)] [RED("amountOfStations")] public CInt32 AmountOfStations { get; set; } [Ordinal(3)] [RED("dataInitialized")] public CBool DataInitialized { get; set; } [Ordinal(4)] [RED("previousStation")] public CInt32 PreviousStation { get; set; } public MediaDeviceControllerPS(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
38.6
110
0.713731
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/MediaDeviceControllerPS.cs
753
C#
using System; class Program { unsafe static void UnsafeProcess() { int i = 123; int* p = &i; Console.WriteLine(*p); } static void Main() { UnsafeProcess(); } }
12.222222
38
0.490909
[ "MIT" ]
autumn009/CSharpSourceDance
Answers/LanguageKeywords/unsafe/unsafe/Program.cs
222
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 Aliyun.Acs.Core.Transform; using Aliyun.Acs.live.Model.V20161101; using System; using System.Collections.Generic; namespace Aliyun.Acs.live.Transform.V20161101 { public class DeleteLiveDetectNotifyConfigResponseUnmarshaller { public static DeleteLiveDetectNotifyConfigResponse Unmarshall(UnmarshallerContext context) { DeleteLiveDetectNotifyConfigResponse deleteLiveDetectNotifyConfigResponse = new DeleteLiveDetectNotifyConfigResponse(); deleteLiveDetectNotifyConfigResponse.HttpResponse = context.HttpResponse; deleteLiveDetectNotifyConfigResponse.RequestId = context.StringValue("DeleteLiveDetectNotifyConfig.RequestId"); return deleteLiveDetectNotifyConfigResponse; } } }
40.894737
123
0.777992
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-live/Live/Transform/V20161101/DeleteLiveDetectNotifyConfigResponseUnmarshaller.cs
1,554
C#