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.Web; using System.Web.Optimization; namespace DilMS_UI.Dispatch { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
38.551724
113
0.580501
[ "Apache-2.0" ]
kwkau/DilMS-UI
DilMS-UI.Dispatch/App_Start/BundleConfig.cs
1,120
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #nullable enable #pragma warning disable CS1591 #pragma warning disable CS0108 #pragma warning disable 618 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using JetBrains.Space.Common; using JetBrains.Space.Common.Json.Serialization; using JetBrains.Space.Common.Json.Serialization.Polymorphism; using JetBrains.Space.Common.Types; namespace JetBrains.Space.Client.IssueDueDateChangedDetailsPartialBuilder { public static class IssueDueDateChangedDetailsPartialExtensions { public static Partial<IssueDueDateChangedDetails> WithOldDueDate(this Partial<IssueDueDateChangedDetails> it) => it.AddFieldName("oldDueDate"); public static Partial<IssueDueDateChangedDetails> WithNewDueDate(this Partial<IssueDueDateChangedDetails> it) => it.AddFieldName("newDueDate"); } }
34
117
0.686047
[ "Apache-2.0" ]
PatrickRatzow/space-dotnet-sdk
src/JetBrains.Space.Client/Generated/Partials/IssueDueDateChangedDetailsPartialBuilder.generated.cs
1,462
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * Live-Video * 直播管理API * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Live.Apis { /// <summary> /// 查询直播流播放人数排行 /// </summary> public class DescribeLiveStreamPlayerRankingDataResponse : JdcloudResponse<DescribeLiveStreamPlayerRankingDataResult> { } }
26.219512
121
0.730233
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Live/Apis/DescribeLiveStreamPlayerRankingDataResponse.cs
1,105
C#
using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Scoring; using System; namespace osu.Game.Rulesets.Solosu.Objects.Drawables { public class DrawableHardBeat : DrawableSolosuHitObject<HardBeat> { Circle child; public DrawableHardBeat () { AddInternal( child = new Circle { Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, Width = 500, Height = 10 } ); Origin = Anchor.BottomCentre; AutoSizeAxes = Axes.Y; } protected override void Update () { base.Update(); Y = -(float)( Lanes[ SolosuLane.Center ].HeightAtTime( Math.Min( Clock.CurrentTime, HitObject.GetEndTime() ), HitObject.StartTime, 1.4 ) ); } protected override void OnApply () { base.OnApply(); Colour = Colours.Regular; } protected override void CheckForResult ( bool userTriggered, double timeOffset ) { if ( timeOffset > 0 ) { ApplyResult( j => j.Type = HitResult.IgnoreHit ); } } protected override void UpdateInitialTransforms () { this.FadeIn( 500 ); } protected override void UpdateHitStateTransforms ( ArmedState state ) { if ( state == ArmedState.Hit ) { this.FadeOut( 150 ).FadeColour( Colours.ColourFor( Result.Type ), 100 ); child.ResizeHeightTo( 100, 150, Easing.Out ); } else if ( state == ArmedState.Miss ) { this.FadeOut( 500 ).FadeColour( Colours.Miss, 200 ); } LifetimeEnd = HitStateUpdateTime + 500; } } }
27.763636
142
0.691552
[ "MIT" ]
Flutterish/Solosu
osu.Game.Rulesets.Solosu/Objects/Drawables/DrawableHardBeat.cs
1,529
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder.Skills; using Microsoft.Bot.Schema; using Newtonsoft.Json; namespace Microsoft.BotFrameworkFunctionalTests.SimpleHostBot { /// <summary> /// A <see cref="SkillConversationIdFactory"/> that uses an in memory <see cref="ConcurrentDictionary{TKey,TValue}"/> /// to store and retrieve <see cref="ConversationReference"/> instances. /// </summary> public class SkillConversationIdFactory : SkillConversationIdFactoryBase { private readonly ConcurrentDictionary<string, string> _conversationRefs = new ConcurrentDictionary<string, string>(); /// <summary> /// Creates a skill conversation id. /// </summary> /// <param name="conversationReference">The reference to a particular point of the conversation.</param> /// <param name="cancellationToken">CancellationToken propagates notifications that operations should be cancelled.</param> /// <returns>The generated conversation id.</returns> [Obsolete] public override Task<string> CreateSkillConversationIdAsync(ConversationReference conversationReference, CancellationToken cancellationToken) { var crJson = JsonConvert.SerializeObject(conversationReference); var key = $"{conversationReference.ChannelId}:{conversationReference.Conversation.Id}"; _conversationRefs.GetOrAdd(key, crJson); return Task.FromResult(key); } /// <summary> /// Gets the corresponding conversation reference of a conversation. /// </summary> /// <param name="skillConversationId">The id that identifies the skill conversation.</param> /// <param name="cancellationToken">CancellationToken propagates notifications that operations should be cancelled.</param> /// <returns>The generated conversation reference.</returns> [Obsolete] public override Task<ConversationReference> GetConversationReferenceAsync(string skillConversationId, CancellationToken cancellationToken) { var conversationReference = JsonConvert.DeserializeObject<ConversationReference>(_conversationRefs[skillConversationId]); return Task.FromResult(conversationReference); } /// <summary> /// Deletes the conversation reference of a conversation. /// </summary> /// <param name="skillConversationId">The id that identifies the skill conversation.</param> /// <param name="cancellationToken">CancellationToken propagates notifications that operations should be cancelled.</param> /// <returns>A task that represents the work queued to execute.</returns> public override Task DeleteConversationReferenceAsync(string skillConversationId, CancellationToken cancellationToken) { _conversationRefs.TryRemove(skillConversationId, out _); return Task.CompletedTask; } } }
50.031746
149
0.713198
[ "MIT" ]
CurlyBytes/BotFramework-FunctionalTests
Bots/DotNet/Consumers/CodeFirst/SimpleHostBot/SkillConversationIdFactory.cs
3,154
C#
using System.Runtime.CompilerServices; namespace System.Html.Media { [Imported, Serializable] public partial class MediaTrackConstraints { public object Mandatory { get; set; } public MediaTrackConstraintSet[] Optional { get; set; } } }
15.470588
45
0.711027
[ "Apache-2.0" ]
Saltarelle/SaltarelleWeb
Web/Generated/Html/Media/MediaTrackConstraints.cs
265
C#
using System; //{[{ using Param_RootNamespace.Core.Helpers; //}]} namespace Param_ItemNamespace.Services { internal class ActivationService { private IEnumerable<ActivationHandler> GetActivationHandlers() { //{[{ yield return Singleton<SchemeActivationHandler>.Instance; //}]} //{--{ yield break; //}--} } } }
18.857143
70
0.578283
[ "MIT" ]
AzureMentor/WindowsTemplateStudio
templates/Uwp/_composition/_shared/Feature.DeepLinking.AddActivationHandler/Services/ActivationService_postaction.cs
398
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 WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementGeoMatchStatementForwardedIpConfigGetArgs : Pulumi.ResourceArgs { /// <summary> /// - Match status to assign to the web request if the request doesn't have a valid IP address in the specified position. Valid values include: `MATCH` or `NO_MATCH`. /// </summary> [Input("fallbackBehavior", required: true)] public Input<string> FallbackBehavior { get; set; } = null!; /// <summary> /// - Name of the HTTP header to use for the IP address. /// </summary> [Input("headerName", required: true)] public Input<string> HeaderName { get; set; } = null!; public WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementGeoMatchStatementForwardedIpConfigGetArgs() { } } }
39.28125
174
0.703262
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementGeoMatchStatementForwardedIpConfigGetArgs.cs
1,257
C#
using System; namespace BehaviourInject.Internal { public interface IContextParent { bool TryResolve(Type resolvingType, out object dependency); event Action OnContextDestroyed; EventManager EventManager { get; } } public class ParentContextStub : IContextParent { public static readonly ParentContextStub STUB = new ParentContextStub(); public event Action OnContextDestroyed; public EventManager EventManager { get; private set; } public ParentContextStub() { EventManager = new EventManager(); } public bool TryResolve(Type resolvingType, out object dependency) { dependency = null; return false; } } }
21.34375
75
0.717423
[ "MIT" ]
Temka193/behaviour_inject
Assets/BInject/Scripts/BehaviourInject/IContextParent.cs
685
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; using System.Collections.Generic; using System.Net; using System.Text; using Amazon.Runtime; using Amazon.S3.Model; using System.Globalization; namespace Amazon.S3 { /// <summary> /// AmazonS3 exception. /// Thrown when DeleteObjects returns successfully, but some of the objects /// were not deleted. /// </summary> public class DeleteObjectsException : AmazonS3Exception { private DeleteObjectsResponse response; /// <summary> /// Gets and sets the ErrorResponse property. /// The DeleteObjectsErrorResponse associated with this exception. /// </summary> public DeleteObjectsResponse Response { get { return this.response; } set { this.response = value; } } /// <summary> /// Constructs an instance of DeleteObjectsException /// </summary> /// <param name="response"></param> public DeleteObjectsException(DeleteObjectsResponse response) : base(CreateMessage(response)) { this.response = response; } private static string CreateMessage(DeleteObjectsResponse response) { if (response == null) throw new ArgumentNullException("response"); string message = string.Format(CultureInfo.InvariantCulture, "Error deleting objects. Deleted objects: {0}. Delete errors: {1}", response.DeletedObjects == null ? 0 : response.DeletedObjects.Count, response.DeleteErrors == null ? 0 : response.DeleteErrors.Count); return message; } } }
32.753623
84
0.645575
[ "Apache-2.0" ]
jasoncwik/aws-sdk-net
sdk/src/Services/S3/Custom/Model/DeleteObjectsException.cs
2,262
C#
#if UNITY_EDITOR && (UNITY_2019_3_OR_NEWER || VALVE_UPDATE_FORCE) using System.IO; using System.Linq; using Unity.XR.OpenVR.SimpleJSON; using UnityEditor; using UnityEditor.PackageManager; using UnityEditor.PackageManager.Requests; using UnityEditor.PackageManager.UI; using UnityEngine; using UnityEngine.Networking; namespace Unity.XR.OpenVR { [InitializeOnLoad] public class OpenVRAutoUpdater : ScriptableObject { private const string valveOpenVRPackageStringOld = "com.valve.openvr"; private const string valveOpenVRPackageString = "com.valvesoftware.unity.openvr"; public const string npmRegistryStringValue = "\"name\": \"Valve\", \"url\": \"https://registry.npmjs.org\", \"scopes\": [ \"com.valvesoftware.unity.openvr\" ]"; public const string scopedRegisteryKey = "scopedRegistries"; private static ListRequest listRequest; private static AddRequest addRequest; private static RemoveRequest removeRequest; private static SearchRequest searchRequest; private static System.Diagnostics.Stopwatch packageTime = new System.Diagnostics.Stopwatch(); private const float estimatedTimeToInstall = 90; // in seconds private const string updaterKeyTemplate = "com.valvesoftware.unity.openvr.updateState.{0}"; private static string updaterKey { get { return string.Format(updaterKeyTemplate, Application.productName); } } private static UpdateStates updateState { get { return _updateState; } set { #if VALVE_DEBUG Debug.Log("[DEBUG] Update State: " + value.ToString()); #endif _updateState = value; EditorPrefs.SetInt(updaterKey, (int)value); } } private static UpdateStates _updateState = UpdateStates.Idle; private static double runningSeconds { get { if (packageTime.IsRunning == false) packageTime.Start(); return packageTime.Elapsed.TotalSeconds; } } static OpenVRAutoUpdater() { #if UNITY_2020_1_OR_NEWER || VALVE_UPDATE_FORCE Start(); #endif } public static void Start() { EditorApplication.update -= Update; EditorApplication.update += Update; } /// <summary> /// State Machine /// Idle: Start from last known state. If none is known go to request a removal of the current openvr package /// WaitingForList: enumerate the packages to see if we have an existing package that needs to be removed. If so, request removal, if not, add scoped registry /// WaitingForRemove: if the remove request has been nulled or completed successfully, request a list of packages for confirmation /// WaitingForRemoveConfirmation: enumerate the packages and verify the removal succeeded. If it failed, try again. /// If it succeeded, add the scoped registry. /// WaitingForScopedRegistry: search for available packages until the openvr package is available. Then add the package /// WaitingForAdd: if the add request has been nulled or completed successfully, request a list of packages for confirmation /// WaitingForAddConfirmation: enumerate the packages and verify the add succeeded. If it failed, try again. /// If it succeeded request removal of this script /// RemoveSelf: delete the key that we've been using to maintain state. Delete this script and the containing folder if it's empty. /// </summary> private static void Update() { switch (updateState) { case UpdateStates.Idle: if (EditorPrefs.HasKey(updaterKey)) { _updateState = (UpdateStates)EditorPrefs.GetInt(updaterKey); packageTime.Start(); } else { RequestList(); packageTime.Start(); } break; case UpdateStates.WaitingForList: if (listRequest == null) { //the list request got nulled for some reason. Request it again. RequestList(); } else if (listRequest != null && listRequest.IsCompleted) { if (listRequest.Error != null || listRequest.Status == UnityEditor.PackageManager.StatusCode.Failure) { DisplayErrorAndStop("Error while checking for an existing openvr package.", listRequest); } else { if (listRequest.Result.Any(package => package.name == valveOpenVRPackageString)) { //if it's there then remove it in preparation for adding the scoped registry RequestRemove(valveOpenVRPackageString); } else if (listRequest.Result.Any(package => package.name == valveOpenVRPackageStringOld)) { //if it's there then remove it in preparation for adding the scoped registry RequestRemove(valveOpenVRPackageStringOld); } else { AddScopedRegistry(); } } } else { if (runningSeconds > estimatedTimeToInstall) { DisplayErrorAndStop("Error while confirming package removal.", listRequest); } else DisplayProgressBar(); } break; case UpdateStates.WaitingForRemove: if (removeRequest == null) { //if our remove request was nulled out we should check if the package has already been removed. RequestRemoveConfirmation(); } else if (removeRequest != null && removeRequest.IsCompleted) { if (removeRequest.Error != null || removeRequest.Status == UnityEditor.PackageManager.StatusCode.Failure) { DisplayErrorAndStop("Error removing old version of OpenVR package.", removeRequest); } else { //verify that the package has been removed (then add) RequestRemoveConfirmation(); } } else { if (packageTime.Elapsed.TotalSeconds > estimatedTimeToInstall) DisplayErrorAndStop("Error removing old version of OpenVR package.", removeRequest); else DisplayProgressBar(); } break; case UpdateStates.WaitingForRemoveConfirmation: if (listRequest == null) { //the list request got nulled for some reason. Request it again. RequestRemoveConfirmation(); } else if (listRequest != null && listRequest.IsCompleted) { if (listRequest.Error != null || listRequest.Status == UnityEditor.PackageManager.StatusCode.Failure) { DisplayErrorAndStop("Error while confirming package removal.", listRequest); } else { if (listRequest.Result.Any(package => package.name == valveOpenVRPackageString)) { //try remove again if it didn't work and we don't know why. RequestRemove(valveOpenVRPackageString); } else if (listRequest.Result.Any(package => package.name == valveOpenVRPackageStringOld)) { //try remove again if it didn't work and we don't know why. RequestRemove(valveOpenVRPackageStringOld); } else { AddScopedRegistry(); } } } else { if (runningSeconds > estimatedTimeToInstall) { DisplayErrorAndStop("Error while confirming package removal.", listRequest); } else DisplayProgressBar(); } break; case UpdateStates.WaitingForScopedRegistry: if (searchRequest == null) { //the search request got nulled for some reason, request again RequestScope(); } else if (searchRequest != null && searchRequest.IsCompleted) { if (searchRequest.Error != null || searchRequest.Status == UnityEditor.PackageManager.StatusCode.Failure) { DisplayErrorAndStop("Error adding Valve scoped registry to project.", searchRequest); } RequestAdd(); } else { if (packageTime.Elapsed.TotalSeconds > estimatedTimeToInstall) DisplayErrorAndStop("Error while trying to add scoped registry.", addRequest); else DisplayProgressBar(); } break; case UpdateStates.WaitingForAdd: if (addRequest == null) { //the add request got nulled for some reason. Request an add confirmation RequestAddConfirmation(); } else if (addRequest != null && addRequest.IsCompleted) { if (addRequest.Error != null || addRequest.Status == UnityEditor.PackageManager.StatusCode.Failure) { DisplayErrorAndStop("Error adding new version of OpenVR package.", addRequest); } else { //verify that the package has been added (then stop) RequestAddConfirmation(); } } else { if (packageTime.Elapsed.TotalSeconds > estimatedTimeToInstall) DisplayErrorAndStop("Error while trying to add package.", addRequest); else DisplayProgressBar(); } break; case UpdateStates.WaitingForAddConfirmation: if (listRequest == null) { //the list request got nulled for some reason. Request it again. RequestAddConfirmation(); } else if (listRequest != null && listRequest.IsCompleted) { if (listRequest.Error != null || listRequest.Status == UnityEditor.PackageManager.StatusCode.Failure) { DisplayErrorAndStop("Error while confirming the OpenVR package has been added.", listRequest); } else { if (listRequest.Result.Any(package => package.name == valveOpenVRPackageString)) { updateState = UpdateStates.RemoveSelf; UnityEditor.EditorUtility.DisplayDialog("OpenVR", "OpenVR Unity XR successfully updated.", "Ok"); } else { //try to add again if it's not there and we don't know why RequestAdd(); } } } else { if (runningSeconds > estimatedTimeToInstall) { DisplayErrorAndStop("Error while confirming the OpenVR package has been added.", listRequest); } else DisplayProgressBar(); } break; case UpdateStates.RemoveSelf: EditorPrefs.DeleteKey(updaterKey); EditorUtility.ClearProgressBar(); EditorApplication.update -= Update; #if VALVE_SKIP_DELETE Debug.Log("[DEBUG] skipping script deletion. Complete."); return; #endif var script = MonoScript.FromScriptableObject(OpenVRAutoUpdater.CreateInstance<OpenVRAutoUpdater>()); var path = AssetDatabase.GetAssetPath(script); FileInfo updaterScript = new FileInfo(path); FileInfo updaterScriptMeta = new FileInfo(path + ".meta"); FileInfo simpleJSONScript = new FileInfo(Path.Combine(updaterScript.Directory.FullName, "OpenVRSimpleJSON.cs")); FileInfo simpleJSONScriptMeta = new FileInfo(Path.Combine(updaterScript.Directory.FullName, "OpenVRSimpleJSON.cs.meta")); updaterScript.Delete(); updaterScriptMeta.Delete(); simpleJSONScript.Delete(); simpleJSONScriptMeta.Delete(); if (updaterScript.Directory.GetFiles().Length == 0 && updaterScript.Directory.GetDirectories().Length == 0) { path = updaterScript.Directory.FullName + ".meta"; updaterScript.Directory.Delete(); File.Delete(path); } AssetDatabase.Refresh(); break; } } private const string packageManifestPath = "Packages/manifest.json"; private const string scopedRegistryKey = "scopedRegistries"; private const string scopedRegistryValue = "{ \"name\": \"Valve\",\n" + "\"url\": \"https://registry.npmjs.org/\"," + "\"scopes\": [" + "\"com.valvesoftware\", \"com.valvesoftware.unity.openvr\"" + "] }"; private const string scopedRegistryNodeTemplate = "[ {0} ]"; //load packages.json //check for existing scoped registries //check for our scoped registry //if no to either then add it //save file //reload private static void AddScopedRegistry() { if (File.Exists(packageManifestPath) == false) { Debug.LogError("[OpenVR Installer] Could not find package manifest at: " + packageManifestPath); return; } bool needsSave = false; string jsonText = File.ReadAllText(packageManifestPath); JSONNode manifest = JSON.Parse(jsonText); if (manifest.HasKey(scopedRegistryKey) == false) { manifest.Add(scopedRegistryKey, JSON.Parse(string.Format(scopedRegistryNodeTemplate, scopedRegistryValue))); needsSave = true; } else { bool alreadyExists = false; foreach (var scopedRegistry in manifest[scopedRegistryKey].AsArray) { if (scopedRegistry.Value != null && scopedRegistry.Value.HasKey("name") && scopedRegistry.Value["name"] == "Valve") { alreadyExists = true; break; } } if (alreadyExists == false) { manifest[scopedRegistryKey].Add(JSON.Parse(scopedRegistryValue)); needsSave = true; } } if (needsSave) { File.WriteAllText(packageManifestPath, manifest.ToString(2)); Debug.Log("[OpenVR Installer] Wrote scoped registry file."); } RequestScope(); } private static void RequestList() { updateState = UpdateStates.WaitingForList; listRequest = Client.List(); } private static void RequestRemove(string packageName) { updateState = UpdateStates.WaitingForRemove; removeRequest = UnityEditor.PackageManager.Client.Remove(packageName); } private static void RequestAdd() { updateState = UpdateStates.WaitingForAdd; addRequest = UnityEditor.PackageManager.Client.Add(valveOpenVRPackageString); } private static void RequestRemoveConfirmation() { updateState = UpdateStates.WaitingForRemoveConfirmation; listRequest = Client.List(); } private static void RequestAddConfirmation() { updateState = UpdateStates.WaitingForAddConfirmation; listRequest = Client.List(); } private static string dialogText = "Installing OpenVR Unity XR package from github using Unity Package Manager..."; private static void DisplayProgressBar() { bool cancel = UnityEditor.EditorUtility.DisplayCancelableProgressBar("SteamVR", dialogText, (float)packageTime.Elapsed.TotalSeconds / estimatedTimeToInstall); if (cancel) Stop(); } private static void RequestScope() { searchRequest = Client.SearchAll(false); updateState = UpdateStates.WaitingForScopedRegistry; } private static void DisplayErrorAndStop(string stepInfo, Request request) { string error = ""; if (request != null) error = request.Error.message; string errorMessage = string.Format("{0}:\n\t{1}\n\nPlease manually reinstall the package through the package manager.", stepInfo, error); UnityEngine.Debug.LogError(errorMessage); Stop(); UnityEditor.EditorUtility.DisplayDialog("OpenVR Error", errorMessage, "Ok"); } private static void Stop() { updateState = UpdateStates.RemoveSelf; } private enum UpdateStates { Idle, WaitingForList, WaitingForRemove, WaitingForRemoveConfirmation, WaitingForScopedRegistry, WaitingForAdd, WaitingForAddConfirmation, RemoveSelf, } } } #endif
44.063425
171
0.483063
[ "MIT" ]
dimdallas/VR_ThetaV_WifiStreaming
Assets/SteamVR/OpenVRAutoUpdater/Editor/OpenVRAutoUpdater.cs
20,844
C#
using System; using System.Collections.Generic; using System.Linq; using Extensions; using Interactivity.Pickup; using JetBrains.Annotations; using UI.HUD; using UnityEngine; using Utility.Attributes; namespace Player.Weapons.NewWeaponSystem { [CreateAssetMenu(menuName = "Weapons/New Weapon", fileName = "New Weapon", order = 0)] public class Weapon : ScriptableObject { public int price = 1; public string description = "Insert description here"; [Space] public float maxAmmo; [Expose] public AmmoType ammoType; [Space] public float fireRate; [Space] [SerializeField] private GameObject weaponModelPrefab; public Sprite weaponIcon; [Space] [Expose] public FireType fireType; #region Static Methods public static Weapon GetWeaponViaName(GameObject owner, string name) { Weapon foundWeapon = Resources.Load<Weapon>($"Weapons/{name}"); if (foundWeapon && owner) foundWeapon.Setup(owner); return foundWeapon; } public static List<Weapon> GetAllWeapons(GameObject owner = null) { List<Weapon> results = Resources.LoadAll<Weapon>("Weapons/").ToList(); if (results != null && owner) { results.ApplyAction(w => w.Setup(owner)); } return results; } #endregion GameObject _currentOwner; private float _tempFireRate; private float currentAmmo; public float currentAmunition => currentAmmo; public GameObject Owner => _currentOwner; public GameObject WeaponModelPrefab => weaponModelPrefab; public GameObject InstancedWeaponModel { get; set; } public void Setup(GameObject owner) { if (owner) { _currentOwner = owner; currentAmmo = maxAmmo; return; } throw new NullReferenceException($"Owner is null: {owner}"); } public int TriggerFire(bool input) { _tempFireRate += Time.deltaTime; if (input && _tempFireRate >= fireRate && currentAmmo > 0) { _tempFireRate = 0; OnFire(InstancedWeaponModel.transform.GetChild(0)); currentAmmo--; HUDManager.UpdateWeaponAmmoUI(Owner, this); return 200; } return 199; } void OnFire(Transform barrel) { fireType.Fire(barrel.transform.position, barrel.forward.normalized, Owner); } public int AddAmmo(int amount) { float previousAmmoAmm = currentAmmo; currentAmmo += amount; currentAmmo = Mathf.Clamp(currentAmmo, 0, maxAmmo); return (int) (maxAmmo - previousAmmoAmm); } } public static class WeaponExtensions { public static Weapon SwapWeaponTo(List<Weapon> weaponLibrary, [NotNull] Weapon newWeapon) { // if (originalWeapon == null) throw new ArgumentNullException(nameof(originalWeapon)); HUDManager.UpdateWeaponIconUI(newWeapon.Owner, newWeapon.weaponIcon); HUDManager.UpdateWeaponAmmoUI(newWeapon.Owner, newWeapon); WeaponVisualiser.UpdateWeaponModel(newWeapon.Owner, weaponLibrary, newWeapon); return newWeapon; } } }
28.585366
99
0.59215
[ "CC0-1.0" ]
sarisman84/Doing-the-thing
Assets/Scripts/Player/Weapons/Weapon.cs
3,518
C#
using Code.BattleSimulation.Actor; namespace Code.BattleSimulation.Model { public interface IBsSelection : IBsSubModel { void Select(IBsActor actor); IBsActor SelectedActor(); } public class BsSelection : IBsSelection { private IBsActor _selectedActor; public void Select(IBsActor actor) { _selectedActor = actor; } public IBsActor SelectedActor() { return _selectedActor; } } }
20.12
47
0.604374
[ "MIT" ]
andrievsky/inner-game
Assets/Code/BattleSimulation/Model/BsSelection.cs
505
C#
using System.Threading.Tasks; namespace Getfitnessinfo.Core.Interfaces { public interface IEmailSender { Task SendEmailAsync(string to, string from, string subject, string body); } }
20.5
81
0.721951
[ "MIT" ]
simionbulat/getfitnessinfo
src/Getfitnessinfo.Core/Interfaces/IEmailSender.cs
207
C#
using System; using Microsoft.Practices.Unity; using WorkflowEngine.Interfaces; using WorkflowEngine.Tests.Schemas; using WorkflowEngine.Tests.Workflows; using Xunit; using ThreadingTask = System.Threading.Tasks.Task; namespace WorkflowEngine.Tests { public class CancellationTests : IClassFixture<UnityContainerFixture>, IDisposable { private readonly UnityContainerFixture _fixture; public CancellationTests(UnityContainerFixture fixture) { _fixture = fixture; } [Fact] public async ThreadingTask NoCancellation() { var pluginServices = _fixture.Container.Resolve<IPluginServices>(); pluginServices.Initialize(); var workflow = pluginServices.GetOrCreatePlugin<CancellationWorkflow>(); var workflowInput = pluginServices.CreatePluginData<CancellationWorkflowInput>(); var workflowOutput = await workflow.Execute<CancellableTaskOutput>(new PluginInputs { { "input", workflowInput } }); Assert.NotNull(workflowOutput); Assert.False(workflowOutput.Data.Cancelled); } [Fact] public async ThreadingTask PluginCancellation() { var pluginServices = _fixture.Container.Resolve<IPluginServices>(); pluginServices.Initialize(); var workflow = pluginServices.GetOrCreatePlugin<CancellationWorkflow>(); var workflowInput = pluginServices.CreatePluginData<CancellationWorkflowInput>(); workflowInput.Data.CancelPlugin = true; var workflowOutput = await workflow.Execute<CancellableTaskOutput>(new PluginInputs { { "input", workflowInput } }); Assert.NotNull(workflowOutput); Assert.True(workflowOutput.Data.Cancelled); } [Fact] public async ThreadingTask ExecutionCancellation() { var pluginServices = _fixture.Container.Resolve<IPluginServices>(); pluginServices.Initialize(); var workflow = pluginServices.GetOrCreatePlugin<CancellationWorkflow>(); var workflowInput = pluginServices.CreatePluginData<CancellationWorkflowInput>(); workflowInput.Data.CancelExecution = true; var workflowOutput = await workflow.Execute<CancellableTaskOutput>(new PluginInputs { { "input", workflowInput } }); Assert.NotNull(workflowOutput); Assert.True(workflowOutput.Data.Cancelled); } public void Dispose() { _fixture.Dispose(); } } }
36.957143
128
0.671821
[ "MIT" ]
fuselabs/WorkflowEngine
Src/WorkflowEngine.Tests/CancellationTests.cs
2,589
C#
// // Author: Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2009 Novell, Inc (http://www.novell.com) // // 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.Collections.Generic; using System.Collections.ObjectModel; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.ServiceModel.Discovery.Version11; using System.ServiceModel.Discovery.VersionApril2005; using System.ServiceModel.Discovery.VersionCD1; namespace System.ServiceModel.Discovery { public sealed class DiscoveryVersion { internal const string Namespace11 = "http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01"; internal const string NamespaceApril2005 = "http://schemas.xmlsoap.org/ws/2005/04/discovery"; internal const string NamespaceCD1 = "http://docs.oasis-open.org/ws-dd/ns/discovery/2008/09"; static DiscoveryVersion () { v11 = new DiscoveryVersion ("WSDiscovery11", Namespace11, "urn:docs-oasis-open-org:ws-dd:ns:discovery:2009:01", MessageVersion.Soap12WSAddressing10, typeof (Version11.IAnnouncementContract11), typeof (AnnouncementClient11), typeof (IDiscoveryProxyContract11), typeof (DiscoveryProxyClient11), typeof (IDiscoveryTargetContract11), typeof (DiscoveryTargetClient11)); april2005 = new DiscoveryVersion ("WSDiscoveryApril2005", NamespaceApril2005, "urn:schemas-xmlsoap-org:ws:2005:04:discovery", MessageVersion.Soap12WSAddressingAugust2004, typeof (IAnnouncementContractApril2005), typeof (AnnouncementClientApril2005), typeof (IDiscoveryProxyContractApril2005), typeof (DiscoveryProxyClientApril2005), typeof (IDiscoveryTargetContractApril2005), typeof (DiscoveryTargetClientApril2005)); cd1 = new DiscoveryVersion ("WSDiscoveryCD1", NamespaceCD1, "urn:docs-oasis-open-org:ws-dd:discovery:2008:09", MessageVersion.Soap12WSAddressingAugust2004, typeof (IAnnouncementContractCD1), typeof (AnnouncementClientCD1), typeof (IDiscoveryProxyContractCD1), typeof (DiscoveryProxyClientCD1), typeof (IDiscoveryTargetContractCD1), typeof (DiscoveryTargetClientCD1)); } static readonly DiscoveryVersion v11, april2005, cd1; public static DiscoveryVersion WSDiscovery11 { get { return v11; } } public static DiscoveryVersion WSDiscoveryApril2005 { get { return april2005; } } public static DiscoveryVersion WSDiscoveryCD1 { get { return cd1; } } public static DiscoveryVersion FromName (string name) { if (name == null) throw new ArgumentNullException ("name"); switch (name) { case "WSDiscovery11": return v11; case "WSDiscoveryApril2005": return april2005; case "WSDiscoveryCD1": return cd1; default: throw new ArgumentOutOfRangeException (String.Format ("Invalid version name: {0}", name)); } } internal DiscoveryVersion (string name, string ns, string adhoc, MessageVersion version, Type announcementContractType, Type announcementClientType, Type discoveryProxyContractType, Type discoveryProxyClientType, Type discoveryTargetContractType, Type discoveryTargetClientType) { this.Name = name; this.Namespace = ns; AdhocAddress = new Uri (adhoc); MessageVersion = version; AnnouncementContractType = announcementContractType; AnnouncementClientType = announcementClientType; DiscoveryProxyContractType = discoveryProxyContractType; DiscoveryProxyClientType = discoveryProxyClientType; DiscoveryTargetContractType = discoveryTargetContractType; DiscoveryTargetClientType = discoveryTargetClientType; } public Uri AdhocAddress { get; private set; } public MessageVersion MessageVersion { get; private set; } public string Name { get; private set; } public string Namespace { get; private set; } internal Type AnnouncementContractType { get; private set; } internal Type AnnouncementClientType { get; private set; } internal Type DiscoveryProxyContractType { get; private set; } internal Type DiscoveryProxyClientType { get; private set; } internal Type DiscoveryTargetContractType { get; private set; } internal Type DiscoveryTargetClientType { get; private set; } public override string ToString () { return Name; } } }
37.661972
280
0.764585
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryVersion.cs
5,348
C#
using System; using System.IO; using System.Collections.Generic; using System.Globalization; using System.Reflection; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; using Microsoft.Samples.VisualStudio.IronPythonTasks.Properties; using CoreIronPython = IronPython; namespace Microsoft.Samples.VisualStudio.IronPython.CompilerTasks { ///////////////////////////////////////////////////////////////////////////// // My MSBuild Task public class IronPythonCompilerTask : Task { private ICompiler compiler = null; #region Constructors /// <summary> /// Constructor. This is the constructor that will be used /// when the task run. /// </summary> public IronPythonCompilerTask() { } /// <summary> /// Constructor. The goal of this constructor is to make /// it easy to test the task. /// </summary> public IronPythonCompilerTask(ICompiler compilerToUse) { compiler = compilerToUse; } #endregion #region Public Properties and related Fields private string[] sourceFiles; /// <summary> /// List of Python source files that should be compiled into the assembly /// </summary> [Required()] public string[] SourceFiles { get { return sourceFiles; } set { sourceFiles = value; } } private string outputAssembly; /// <summary> /// Output Assembly (including extension) /// </summary> [Required()] public string OutputAssembly { get { return outputAssembly; } set { outputAssembly = value; } } private ITaskItem[] referencedAssemblies = new ITaskItem[0]; /// <summary> /// List of dependent assemblies /// </summary> public ITaskItem[] ReferencedAssemblies { get { return referencedAssemblies; } set { if (value != null) { referencedAssemblies = value; } else { referencedAssemblies = new ITaskItem[0]; } } } private ITaskItem[] resourceFiles = new ITaskItem[0]; /// <summary> /// List of resource files /// </summary> public ITaskItem[] ResourceFiles { get { return resourceFiles; } set { if (value != null) { resourceFiles = value; } else { resourceFiles = new ITaskItem[0]; } } } private string mainFile; /// <summary> /// For applications, which file is the entry point /// </summary> [Required()] public string MainFile { get { return mainFile; } set { mainFile = value; } } private string targetKind; /// <summary> /// Target type (exe, winexe, library) /// These will be mapped to System.Reflection.Emit.PEFileKinds /// </summary> public string TargetKind { get { return targetKind; } set { targetKind = value.ToLower(CultureInfo.InvariantCulture); } } private bool debugSymbols = true; /// <summary> /// Generate debug information /// </summary> public bool DebugSymbols { get { return debugSymbols; } set { debugSymbols = value; } } private string projectPath = null; /// <summary> /// This should be set to $(MSBuildProjectDirectory) /// </summary> public string ProjectPath { get { return projectPath; } set { projectPath = value; } } private bool useExperimentalCompiler; /// <summary> /// This property is only needed because Iron Python does not officially support building real .Net assemblies. /// For WAP scenarios, we need to support real assemblies and as such we use an alternate approach to build those assemblies. /// </summary> public bool UseExperimentalCompiler { get { return useExperimentalCompiler; } set { useExperimentalCompiler = value; } } #endregion /// <summary> /// Main entry point for the task /// </summary> /// <returns></returns> public override bool Execute() { Log.LogMessage(MessageImportance.Normal, "Iron Python Compilation Task"); // Create the compiler if it does not already exist CompilerErrorSink errorSink = new CompilerErrorSink(this.Log); errorSink.ProjectDirectory = ProjectPath; if (compiler == null) { if (UseExperimentalCompiler) compiler = new ExperimentalCompiler(new List<string>(this.SourceFiles), this.OutputAssembly, errorSink); else compiler = new Compiler(new List<string>(this.SourceFiles), this.OutputAssembly, errorSink); } if (!InitializeCompiler()) return false; // Call the compiler and report errors and warnings compiler.Compile(); return errorSink.BuildSucceeded; } /// <summary> /// Initialize compiler options based on task parameters /// </summary> /// <returns>false if failed</returns> private bool InitializeCompiler() { switch (TargetKind) { case "exe": { compiler.TargetKind = System.Reflection.Emit.PEFileKinds.ConsoleApplication; break; } case "winexe": { compiler.TargetKind = System.Reflection.Emit.PEFileKinds.WindowApplication; break; } case "library": { compiler.TargetKind = System.Reflection.Emit.PEFileKinds.Dll; break; } default: { this.Log.LogError(Resources.InvalidTargetType, TargetKind); return false; } } compiler.IncludeDebugInformation = this.DebugSymbols; compiler.MainFile = this.MainFile; compiler.SourceFiles = new List<string>(this.SourceFiles); // References require a bit more work since our compiler expect us to pass the Assemblies (and not just paths) compiler.ReferencedAssemblies = new List<string>(); foreach (ITaskItem assemblyReference in this.ReferencedAssemblies) { compiler.ReferencedAssemblies.Add(assemblyReference.ItemSpec); } // Add each resource List<CoreIronPython.Hosting.ResourceFile> resourcesList = new List<CoreIronPython.Hosting.ResourceFile>(); foreach (ITaskItem resource in this.ResourceFiles) { bool publicVisibility = true; string access = resource.GetMetadata("Access"); if (String.CompareOrdinal("Private", access) == 0) publicVisibility = false; string filename = resource.ItemSpec; string logicalName = resource.GetMetadata("LogicalName"); if (String.IsNullOrEmpty(logicalName)) logicalName = Path.GetFileName(resource.ItemSpec); CoreIronPython.Hosting.ResourceFile resourceFile = new CoreIronPython.Hosting.ResourceFile(logicalName, filename, publicVisibility); resourcesList.Add(resourceFile); } compiler.ResourceFiles = resourcesList; return true; } } }
26.236735
136
0.67906
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
Visual Studio Product Team/IronPython Integration/[C#]-IronPython Integration/C#/integration/IronPython/src/IronPython.CompilerTask/IronPythonCompilerTask.cs
6,428
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: AssemblyCulture("")] // Framework-hidden interface methods [assembly: InternalsVisibleTo("Snowflake.Framework")] [assembly: InternalsVisibleTo("Snowflake.Framework.Services")] [assembly: InternalsVisibleTo("Snowflake.Framework.Remoting.GraphQL")] [assembly: InternalsVisibleTo("Snowflake.Support.GraphQL.Server")] [assembly: InternalsVisibleTo("Snowflake.Bootstrap.Windows")] [assembly: InternalsVisibleTo("Snowflake.Bootstrap.Linux")] // Needed for mocking purposes [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: InternalsVisibleTo("Snowflake.Framework.Tests")] // 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)]
41.888889
77
0.803714
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SnowflakePowered/snowflake
src/Snowflake.Framework.Primitives/AssemblyInfo.cs
1,133
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 System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using Newtonsoft.Json; using osu.Framework.Bindables; using osu.Game.Users; namespace osu.Game.Online.API.Requests.Responses { public class APIUser : IEquatable<APIUser>, IUser { [JsonProperty(@"id")] public int Id { get; set; } = 1; [JsonProperty(@"join_date")] public DateTimeOffset JoinDate; [JsonProperty(@"username")] public string Username { get; set; } [JsonProperty(@"previous_usernames")] public string[] PreviousUsernames; [JsonProperty(@"country")] public Country Country; public readonly Bindable<UserStatus> Status = new Bindable<UserStatus>(); public readonly Bindable<UserActivity> Activity = new Bindable<UserActivity>(); [JsonProperty(@"profile_colour")] public string Colour; [JsonProperty(@"avatar_url")] public string AvatarUrl; [JsonProperty(@"cover_url")] public string CoverUrl { get => Cover?.Url; set => Cover = new UserCover { Url = value }; } [JsonProperty(@"cover")] public UserCover Cover; public class UserCover { [JsonProperty(@"custom_url")] public string CustomUrl; [JsonProperty(@"url")] public string Url; [JsonProperty(@"id")] public int? Id; } [JsonProperty(@"is_admin")] public bool IsAdmin; [JsonProperty(@"is_supporter")] public bool IsSupporter; [JsonProperty(@"support_level")] public int SupportLevel; [JsonProperty(@"is_gmt")] public bool IsGMT; [JsonProperty(@"is_qat")] public bool IsQAT; [JsonProperty(@"is_bng")] public bool IsBNG; [JsonProperty(@"is_bot")] public bool IsBot { get; set; } [JsonProperty(@"is_active")] public bool Active; [JsonProperty(@"is_online")] public bool IsOnline; [JsonProperty(@"pm_friends_only")] public bool PMFriendsOnly; [JsonProperty(@"interests")] public string Interests; [JsonProperty(@"occupation")] public string Occupation; [JsonProperty(@"title")] public string Title; [JsonProperty(@"location")] public string Location; [JsonProperty(@"last_visit")] public DateTimeOffset? LastVisit; [JsonProperty(@"twitter")] public string Twitter; [JsonProperty(@"discord")] public string Discord; [JsonProperty(@"website")] public string Website; [JsonProperty(@"post_count")] public int PostCount; [JsonProperty(@"comments_count")] public int CommentsCount; [JsonProperty(@"follower_count")] public int FollowerCount; [JsonProperty(@"mapping_follower_count")] public int MappingFollowerCount; [JsonProperty(@"favourite_beatmapset_count")] public int FavouriteBeatmapsetCount; [JsonProperty(@"graveyard_beatmapset_count")] public int GraveyardBeatmapsetCount; [JsonProperty(@"loved_beatmapset_count")] public int LovedBeatmapsetCount; [JsonProperty(@"ranked_beatmapset_count")] public int RankedBeatmapsetCount; [JsonProperty(@"pending_beatmapset_count")] public int PendingBeatmapsetCount; [JsonProperty(@"scores_best_count")] public int ScoresBestCount; [JsonProperty(@"scores_first_count")] public int ScoresFirstCount; [JsonProperty(@"scores_recent_count")] public int ScoresRecentCount; [JsonProperty(@"beatmap_playcounts_count")] public int BeatmapPlaycountsCount; [JsonProperty] private string[] playstyle { set => PlayStyles = value?.Select(str => Enum.Parse(typeof(APIPlayStyle), str, true)).Cast<APIPlayStyle>().ToArray(); } public APIPlayStyle[] PlayStyles; [JsonProperty(@"playmode")] public string PlayMode; [JsonProperty(@"profile_order")] public string[] ProfileOrder; [JsonProperty(@"kudosu")] public KudosuCount Kudosu; public class KudosuCount { [JsonProperty(@"total")] public int Total; [JsonProperty(@"available")] public int Available; } private UserStatistics statistics; /// <summary> /// User statistics for the requested ruleset (in the case of a <see cref="GetUserRequest"/> or <see cref="GetFriendsRequest"/> response). /// Otherwise empty. /// </summary> [JsonProperty(@"statistics")] public UserStatistics Statistics { get => statistics ??= new UserStatistics(); set { if (statistics != null) // we may already have rank history populated value.RankHistory = statistics.RankHistory; statistics = value; } } [JsonProperty(@"rank_history")] private APIRankHistory rankHistory { set => statistics.RankHistory = value; } [JsonProperty("badges")] public Badge[] Badges; [JsonProperty("user_achievements")] public APIUserAchievement[] Achievements; [JsonProperty("monthly_playcounts")] public APIUserHistoryCount[] MonthlyPlaycounts; [JsonProperty("replays_watched_counts")] public APIUserHistoryCount[] ReplaysWatchedCounts; /// <summary> /// All user statistics per ruleset's short name (in the case of a <see cref="GetUsersRequest"/> response). /// Otherwise empty. Can be altered for testing purposes. /// </summary> // todo: this should likely be moved to a separate UserCompact class at some point. [JsonProperty("statistics_rulesets")] [CanBeNull] public Dictionary<string, UserStatistics> RulesetsStatistics { get; set; } public override string ToString() => Username; /// <summary> /// A user instance for displaying locally created system messages. /// </summary> public static readonly APIUser SYSTEM_USER = new APIUser { Id = 0, Username = "system", Colour = @"9c0101", }; public int OnlineID => Id; public bool Equals(APIUser other) => OnlineID == other?.OnlineID; } }
28.804878
147
0.578182
[ "MIT" ]
Azyyyyyy/osu
osu.Game/Online/API/Requests/Responses/APIUser.cs
6,843
C#
using System; using System.Collections.Generic; using System.Text; namespace Surging.Core.CPlatform { public enum CommunicationProtocol { None, Tcp, Http, WS, Mqtt } }
13.8125
36
0.597285
[ "MIT" ]
DotNetExample/Surging.GoodDemo
SurgingDemo/00.Surging.Core/Surging.Core.CPlatform/CommunicationProtocol.cs
223
C#
using System.Collections.Generic; using CashRegister.Offers; using CashRegister.Orders; namespace CashRegister.Checkouts { public abstract class CheckoutBase { public ICollection<OrderBase> Orders { get; set; } public ICollection<OfferBase> Offers { get; set; } public decimal Discount { get; set; } public decimal Fee { get; set; } public decimal Sum { get; set; } } }
28.133333
58
0.670616
[ "MIT" ]
Aemilivs/CashRegister
Checkouts/CheckoutBase.cs
422
C#
using System; using FluentAssertions; using Networking.Files.PcapNG; using Xunit; namespace Networking.Files.Tests.PcapNGTests.NameResolutionBlockTests.RecordTests { public class Record_Test { [Fact] public void record() { var record = new NameResolutionBlock.Record { IsLittleEndian = false, Bytes = new Byte[] { 0x00,0x01,0x00,0x0E, 0x7F,0x00,0x00,0x01, 0x6C,0x6F,0x63,0x61, 0x6C,0x68,0x6F,0x73, 0x74,0x00,0x00,0x00 } }; record.Type.Should().Be(NameResolutionBlock.RecordType.IPv4); record.ValueLength.Should().Be(14); record.IP.ToString().Should().Be("127.0.0.1"); record.Host.Should().Be("localhost"); } } }
27.8125
81
0.525843
[ "MIT" ]
heshang233/networking
test/networking.files.tests/PcapNGTests/NameResolutionBlockTests/RecordTests/Record_Test.cs
890
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; namespace SocialNetwork.Api.Controllers { [Authorize] [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { var claims = User.Claims; return new string[] {"value1", "value2"}; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
21.795455
56
0.520334
[ "MIT" ]
Jac21/CSharpMenagerie
Security/AspNetCoreAndOAuth/SocialNetwork/SocialNetwork.Api/Controllers/ValuesController.cs
961
C#
#if UNITY_PURCHASING #if UNITY_ANDROID || UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_TVOS // You must obfuscate your secrets using Window > Unity IAP > Receipt Validation Obfuscator // before receipt validation will compile in this sample. //#define RECEIPT_VALIDATION #endif //#define DELAY_CONFIRMATION // Returns PurchaseProcessingResult.Pending from ProcessPurchase, then calls ConfirmPendingPurchase after a delay //#define USE_PAYOUTS // Enables use of PayoutDefinitions to specify what the player should receive when a product is purchased //#define INTERCEPT_PROMOTIONAL_PURCHASES // Enables intercepting promotional purchases that come directly from the Apple App Store using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Purchasing; using UnityEngine.Store; // UnityChannel #if RECEIPT_VALIDATION using UnityEngine.Purchasing.Security; #endif /// <summary> /// An example of Unity IAP functionality. /// To use with your account, configure the product ids (AddProduct). /// </summary> [AddComponentMenu("Unity IAP/Demo")] public class IAPDemo : MonoBehaviour, IStoreListener { // Unity IAP objects private IStoreController m_Controller; private IAppleExtensions m_AppleExtensions; private IMoolahExtension m_MoolahExtensions; private ISamsungAppsExtensions m_SamsungExtensions; private IMicrosoftExtensions m_MicrosoftExtensions; private IUnityChannelExtensions m_UnityChannelExtensions; #pragma warning disable 0414 private bool m_IsGooglePlayStoreSelected; #pragma warning restore 0414 private bool m_IsSamsungAppsStoreSelected; private bool m_IsCloudMoolahStoreSelected; private bool m_IsUnityChannelSelected; private string m_LastTransactionID; private bool m_IsLoggedIn; private UnityChannelLoginHandler unityChannelLoginHandler; // Helper for interfacing with UnityChannel API private bool m_FetchReceiptPayloadOnPurchase = false; private bool m_PurchaseInProgress; private Dictionary<string, IAPDemoProductUI> m_ProductUIs = new Dictionary<string, IAPDemoProductUI>(); public GameObject productUITemplate; public RectTransform contentRect; public Button restoreButton; public Button loginButton; public Button validateButton; public Text versionText; #if RECEIPT_VALIDATION private CrossPlatformValidator validator; #endif /// <summary> /// This will be called when Unity IAP has finished initialising. /// </summary> public void OnInitialized(IStoreController controller, IExtensionProvider extensions) { m_Controller = controller; m_AppleExtensions = extensions.GetExtension<IAppleExtensions>(); m_SamsungExtensions = extensions.GetExtension<ISamsungAppsExtensions>(); m_MoolahExtensions = extensions.GetExtension<IMoolahExtension>(); m_MicrosoftExtensions = extensions.GetExtension<IMicrosoftExtensions>(); m_UnityChannelExtensions = extensions.GetExtension<IUnityChannelExtensions>(); InitUI(controller.products.all); // On Apple platforms we need to handle deferred purchases caused by Apple's Ask to Buy feature. // On non-Apple platforms this will have no effect; OnDeferred will never be called. m_AppleExtensions.RegisterPurchaseDeferredListener(OnDeferred); Debug.Log("Available items:"); foreach (var item in controller.products.all) { if (item.availableToPurchase) { Debug.Log(string.Join(" - ", new[] { item.metadata.localizedTitle, item.metadata.localizedDescription, item.metadata.isoCurrencyCode, item.metadata.localizedPrice.ToString(), item.metadata.localizedPriceString, item.transactionID, item.receipt })); #if INTERCEPT_PROMOTIONAL_PURCHASES // Set all these products to be visible in the user's App Store according to Apple's Promotional IAP feature // https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/PromotingIn-AppPurchases/PromotingIn-AppPurchases.html m_AppleExtensions.SetStorePromotionVisibility(item, AppleStorePromotionVisibility.Show); #endif } } // Populate the product menu now that we have Products AddProductUIs(m_Controller.products.all); LogProductDefinitions(); } /// <summary> /// This will be called when a purchase completes. /// </summary> public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e) { Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id); Debug.Log("Receipt: " + e.purchasedProduct.receipt); m_LastTransactionID = e.purchasedProduct.transactionID; m_PurchaseInProgress = false; // Decode the UnityChannelPurchaseReceipt, extracting the gameOrderId if (m_IsUnityChannelSelected) { var unifiedReceipt = JsonUtility.FromJson<UnifiedReceipt>(e.purchasedProduct.receipt); if (unifiedReceipt != null && !string.IsNullOrEmpty(unifiedReceipt.Payload)) { var purchaseReceipt = JsonUtility.FromJson<UnityChannelPurchaseReceipt>(unifiedReceipt.Payload); Debug.LogFormat( "UnityChannel receipt: storeSpecificId = {0}, transactionId = {1}, orderQueryToken = {2}", purchaseReceipt.storeSpecificId, purchaseReceipt.transactionId, purchaseReceipt.orderQueryToken); } } #if RECEIPT_VALIDATION // Local validation is available for GooglePlay, Apple, and UnityChannel stores if (m_IsGooglePlayStoreSelected || (m_IsUnityChannelSelected && m_FetchReceiptPayloadOnPurchase) || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.tvOS) { try { var result = validator.Validate(e.purchasedProduct.receipt); Debug.Log("Receipt is valid. Contents:"); foreach (IPurchaseReceipt productReceipt in result) { Debug.Log(productReceipt.productID); Debug.Log(productReceipt.purchaseDate); Debug.Log(productReceipt.transactionID); GooglePlayReceipt google = productReceipt as GooglePlayReceipt; if (null != google) { Debug.Log(google.purchaseState); Debug.Log(google.purchaseToken); } UnityChannelReceipt unityChannel = productReceipt as UnityChannelReceipt; if (null != unityChannel) { Debug.Log(unityChannel.productID); Debug.Log(unityChannel.purchaseDate); Debug.Log(unityChannel.transactionID); } AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt; if (null != apple) { Debug.Log(apple.originalTransactionIdentifier); Debug.Log(apple.subscriptionExpirationDate); Debug.Log(apple.cancellationDate); Debug.Log(apple.quantity); } // For improved security, consider comparing the signed // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data // embedded in the signed receipt objects to the data which the game is using // to make this purchase. } } catch (IAPSecurityException ex) { Debug.Log("Invalid receipt, not unlocking content. " + ex); return PurchaseProcessingResult.Complete; } } #endif // Unlock content from purchases here. #if USE_PAYOUTS if (e.purchasedProduct.definition.payouts != null) { Debug.Log("Purchase complete, paying out based on defined payouts"); foreach (var payout in e.purchasedProduct.definition.payouts) { Debug.Log(string.Format("Granting {0} {1} {2} {3}", payout.quantity, payout.typeString, payout.subtype, payout.data)); } } #endif // Indicate if we have handled this purchase. // PurchaseProcessingResult.Complete: ProcessPurchase will not be called // with this product again, until next purchase. // PurchaseProcessingResult.Pending: ProcessPurchase will be called // again with this product at next app launch. Later, call // m_Controller.ConfirmPendingPurchase(Product) to complete handling // this purchase. Use to transactionally save purchases to a cloud // game service. #if DELAY_CONFIRMATION StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct)); return PurchaseProcessingResult.Pending; #else UpdateProductUI(e.purchasedProduct); return PurchaseProcessingResult.Complete; #endif } #if DELAY_CONFIRMATION private HashSet<string> m_PendingProducts = new HashSet<string>(); private IEnumerator ConfirmPendingPurchaseAfterDelay(Product p) { m_PendingProducts.Add(p.definition.id); Debug.Log("Delaying confirmation of " + p.definition.id + " for 5 seconds."); var end = Time.time + 5f; while (Time.time < end) { yield return null; var remaining = Mathf.CeilToInt (end - Time.time); UpdateProductPendingUI (p, remaining); } Debug.Log("Confirming purchase of " + p.definition.id); m_Controller.ConfirmPendingPurchase(p); m_PendingProducts.Remove(p.definition.id); UpdateProductUI (p); } #endif /// <summary> /// This will be called if an attempted purchase fails. /// </summary> public void OnPurchaseFailed(Product item, PurchaseFailureReason r) { Debug.Log("Purchase failed: " + item.definition.id); Debug.Log(r); if (m_IsUnityChannelSelected) { var extra = m_UnityChannelExtensions.GetLastPurchaseError(); var purchaseError = JsonUtility.FromJson<UnityChannelPurchaseError>(extra); if (purchaseError != null && purchaseError.purchaseInfo != null) { // Additional information about purchase failure. var purchaseInfo = purchaseError.purchaseInfo; Debug.LogFormat( "UnityChannel purchaseInfo: productCode = {0}, gameOrderId = {1}, orderQueryToken = {2}", purchaseInfo.productCode, purchaseInfo.gameOrderId, purchaseInfo.orderQueryToken); } // Determine if the user already owns this item and that it can be added to // their inventory, if not already present. #if UNITY_5_6_OR_NEWER if (r == PurchaseFailureReason.DuplicateTransaction) { // Unlock `item` in inventory if not already present. Debug.Log("Duplicate transaction detected, unlock this item"); } #else // Building using Unity strictly less than 5.6; e.g 5.3-5.5. // In Unity 5.3 the enum PurchaseFailureReason.DuplicateTransaction // may not be available (is available in 5.6 ... specifically // 5.5.1p1+, 5.4.4p2+) and can be substituted with this call. if (r == PurchaseFailureReason.Unknown) { if (purchaseError != null && purchaseError.error != null && purchaseError.error.Equals("DuplicateTransaction")) { // Unlock `item` in inventory if not already present. Debug.Log("Duplicate transaction detected, unlock this item"); } } #endif } m_PurchaseInProgress = false; } public void OnInitializeFailed(InitializationFailureReason error) { Debug.Log("Billing failed to initialize!"); switch (error) { case InitializationFailureReason.AppNotKnown: Debug.LogError("Is your App correctly uploaded on the relevant publisher console?"); break; case InitializationFailureReason.PurchasingUnavailable: // Ask the user if billing is disabled in device settings. Debug.Log("Billing disabled!"); break; case InitializationFailureReason.NoProductsAvailable: // Developer configuration error; check product metadata. Debug.Log("No products available for purchase!"); break; } } [Serializable] public class UnityChannelPurchaseError { public string error; public UnityChannelPurchaseInfo purchaseInfo; } [Serializable] public class UnityChannelPurchaseInfo { public string productCode; // Corresponds to storeSpecificId public string gameOrderId; // Corresponds to transactionId public string orderQueryToken; } public void Awake() { var module = StandardPurchasingModule.Instance(); // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and // developer ui (initialization, purchase, failure code setting). These correspond to // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode. module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser; var builder = ConfigurationBuilder.Instance(module); // Set this to true to enable the Microsoft IAP simulator for local testing. builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = false; m_IsGooglePlayStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.GooglePlay; // CloudMoolah Configuration setings // All games must set the configuration. the configuration need to apply on the CloudMoolah Portal. // CloudMoolah APP Key builder.Configure<IMoolahConfiguration>().appKey = "d93f4564c41d463ed3d3cd207594ee1b"; // CloudMoolah Hash Key builder.Configure<IMoolahConfiguration>().hashKey = "cc"; // This enables the CloudMoolah test mode for local testing. // You would remove this, or set to CloudMoolahMode.Production, before building your release package. builder.Configure<IMoolahConfiguration>().SetMode(CloudMoolahMode.AlwaysSucceed); // This records whether we are using Cloud Moolah IAP. // Cloud Moolah requires logging in to access your Digital Wallet, so: // A) IAPDemo (this) displays the Cloud Moolah GUI button for Cloud Moolah m_IsCloudMoolahStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.CloudMoolah; // UnityChannel, provides access to Xiaomi MiPay. // Products are required to be set in the IAP Catalog window. The file "MiProductCatalog.prop" // is required to be generated into the project's // Assets/Plugins/Android/assets folder, based off the contents of the // IAP Catalog window, for MiPay. m_IsUnityChannelSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.XiaomiMiPay; // UnityChannel supports receipt validation through a backend fetch. builder.Configure<IUnityChannelConfiguration>().fetchReceiptPayloadOnPurchase = m_FetchReceiptPayloadOnPurchase; // Define our products. // Either use the Unity IAP Catalog, or manually use the ConfigurationBuilder.AddProduct API. // Use IDs from both the Unity IAP Catalog and hardcoded IDs via the ConfigurationBuilder.AddProduct API. // Use the products defined in the IAP Catalog GUI. // E.g. Menu: "Window" > "Unity IAP" > "IAP Catalog", then add products, then click "App Store Export". var catalog = ProductCatalog.LoadDefaultCatalog(); foreach (var product in catalog.allProducts) { if (product.allStoreIDs.Count > 0) { var ids = new IDs(); foreach (var storeID in product.allStoreIDs) { ids.Add(storeID.id, storeID.store); } builder.AddProduct(product.id, product.type, ids); } else { builder.AddProduct(product.id, product.type); } } // In this case our products have the same identifier across all the App stores, // except on the Mac App store where product IDs cannot be reused across both Mac and // iOS stores. // So on the Mac App store our products have different identifiers, // and we tell Unity IAP this by using the IDs class. builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs { {"100.gold.coins.mac", MacAppStore.Name}, {"000000596586", TizenStore.Name}, {"com.ff", MoolahAppStore.Name}, } #if USE_PAYOUTS , new PayoutDefinition(PayoutType.Currency, "gold", 100) #endif //USE_PAYOUTS ); builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs { {"500.gold.coins.mac", MacAppStore.Name}, {"000000596581", TizenStore.Name}, {"com.ee", MoolahAppStore.Name}, } #if USE_PAYOUTS , new PayoutDefinition(PayoutType.Currency, "gold", 500) #endif //USE_PAYOUTS ); builder.AddProduct("sword", ProductType.NonConsumable, new IDs { {"sword.mac", MacAppStore.Name}, {"000000596583", TizenStore.Name}, } #if USE_PAYOUTS , new List<PayoutDefinition> { new PayoutDefinition(PayoutType.Item, "", 1, "item_id:76543"), new PayoutDefinition(PayoutType.Currency, "gold", 50) } #endif //USE_PAYOUTS ); builder.AddProduct("subscription", ProductType.Subscription, new IDs { {"subscription.mac", MacAppStore.Name} }); // Write Amazon's JSON description of our products to storage when using Amazon's local sandbox. // This should be removed from a production build. builder.Configure<IAmazonConfiguration>().WriteSandboxJSON(builder.products); // This enables simulated purchase success for Samsung IAP. // You would remove this, or set to SamsungAppsMode.Production, before building your release package. builder.Configure<ISamsungAppsConfiguration>().SetMode(SamsungAppsMode.AlwaysSucceed); // This records whether we are using Samsung IAP. Currently ISamsungAppsExtensions.RestoreTransactions // displays a blocking Android Activity, so: // A) Unity IAP does not automatically restore purchases on Samsung Galaxy Apps // B) IAPDemo (this) displays the "Restore" GUI button for Samsung Galaxy Apps m_IsSamsungAppsStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.SamsungApps; // This selects the GroupId that was created in the Tizen Store for this set of products // An empty or non-matching GroupId here will result in no products available for purchase builder.Configure<ITizenStoreConfiguration>().SetGroupId("100000085616"); #if INTERCEPT_PROMOTIONAL_PURCHASES // On iOS and tvOS we can intercept promotional purchases that come directly from the App Store. // On other platforms this will have no effect; OnPromotionalPurchase will never be called. builder.Configure<IAppleConfiguration>().SetApplePromotionalPurchaseInterceptorCallback(OnPromotionalPurchase); Debug.Log("Setting Apple promotional purchase interceptor callback"); #endif #if RECEIPT_VALIDATION string appIdentifier; #if UNITY_5_6_OR_NEWER appIdentifier = Application.identifier; #else appIdentifier = Application.bundleIdentifier; #endif validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), UnityChannelTangle.Data(), appIdentifier); #endif Action initializeUnityIap = () => { // Now we're ready to initialize Unity IAP. UnityPurchasing.Initialize(this, builder); }; bool needExternalLogin = m_IsUnityChannelSelected; if (!needExternalLogin) { initializeUnityIap(); } else { // Call UnityChannel initialize and (later) login asynchronously // UnityChannel configuration settings. Required for Xiaomi MiPay. // Collect this app configuration from the Unity Developer website at // [2017-04-17 PENDING - Contact support representative] // https://developer.cloud.unity3d.com/ providing your Xiaomi MiPay App // ID, App Key, and App Secret. This permits Unity to proxy from the // user's device into the MiPay system. // IMPORTANT PRE-BUILD STEP: For mandatory Chinese Government app auditing // and for MiPay testing, enable debug mode (test mode) // using the `AppInfo.debug = true;` when initializing Unity Channel. AppInfo unityChannelAppInfo = new AppInfo(); unityChannelAppInfo.appId = "abc123appId"; unityChannelAppInfo.appKey = "efg456appKey"; unityChannelAppInfo.clientId = "hij789clientId"; unityChannelAppInfo.clientKey = "klm012clientKey"; unityChannelAppInfo.debug = false; // Shared handler for Unity Channel initialization, here, and login, later unityChannelLoginHandler = new UnityChannelLoginHandler(); unityChannelLoginHandler.initializeFailedAction = (string message) => { Debug.LogError("Failed to initialize and login to UnityChannel: " + message); }; unityChannelLoginHandler.initializeSucceededAction = () => { initializeUnityIap(); }; StoreService.Initialize(unityChannelAppInfo, unityChannelLoginHandler); } } // For handling initialization and login of UnityChannel, returning control to our store after. class UnityChannelLoginHandler : ILoginListener { internal Action initializeSucceededAction; internal Action<string> initializeFailedAction; internal Action<UserInfo> loginSucceededAction; internal Action<string> loginFailedAction; public void OnInitialized() { initializeSucceededAction(); } public void OnInitializeFailed(string message) { initializeFailedAction(message); } public void OnLogin(UserInfo userInfo) { loginSucceededAction(userInfo); } public void OnLoginFailed(string message) { loginFailedAction(message); } } /// <summary> /// This will be called after a call to IAppleExtensions.RestoreTransactions(). /// </summary> private void OnTransactionsRestored(bool success) { Debug.Log("Transactions restored."); } /// <summary> /// iOS Specific. /// This is called as part of Apple's 'Ask to buy' functionality, /// when a purchase is requested by a minor and referred to a parent /// for approval. /// /// When the purchase is approved or rejected, the normal purchase events /// will fire. /// </summary> /// <param name="item">Item.</param> private void OnDeferred(Product item) { Debug.Log("Purchase deferred: " + item.definition.id); } #if INTERCEPT_PROMOTIONAL_PURCHASES private void OnPromotionalPurchase(Product item) { Debug.Log("Attempted promotional purchase: " + item.definition.id); // Promotional purchase has been detected. Handle this event by, e.g. presenting a parental gate. // Here, for demonstration purposes only, we will wait five seconds before continuing the purchase. StartCoroutine(ContinuePromotionalPurchases()); } private IEnumerator ContinuePromotionalPurchases() { Debug.Log("Continuing promotional purchases in 5 seconds"); yield return new WaitForSeconds(5); Debug.Log("Continuing promotional purchases now"); m_AppleExtensions.ContinuePromotionalPurchases (); // iOS and tvOS only; does nothing on Mac } #endif private void InitUI(IEnumerable<Product> items) { // Show Restore, Register, Login, and Validate buttons on supported platforms restoreButton.gameObject.SetActive(NeedRestoreButton()); loginButton.gameObject.SetActive(NeedLoginButton()); validateButton.gameObject.SetActive(NeedValidateButton()); ClearProductUIs(); restoreButton.onClick.AddListener(RestoreButtonClick); loginButton.onClick.AddListener(LoginButtonClick); validateButton.onClick.AddListener(ValidateButtonClick); versionText.text = "Unity version: " + Application.unityVersion + "\n" + "IAP version: " + StandardPurchasingModule.k_PackageVersion; } public void PurchaseButtonClick(string productID) { if (m_PurchaseInProgress == true) { Debug.Log("Please wait, purchase in progress"); return; } if (m_Controller == null) { Debug.LogError("Purchasing is not initialized"); return; } if (m_Controller.products.WithID(productID) == null) { Debug.LogError("No product has id " + productID); return; } // For platforms needing Login, games utilizing a connected backend // game server may wish to login. // Standalone games may not need to login. if (NeedLoginButton() && m_IsLoggedIn == false) { Debug.LogWarning("Purchase notifications will not be forwarded server-to-server. Login incomplete."); } // Don't need to draw our UI whilst a purchase is in progress. // This is not a requirement for IAP Applications but makes the demo // scene tidier whilst the fake purchase dialog is showing. m_PurchaseInProgress = true; m_Controller.InitiatePurchase(m_Controller.products.WithID(productID), "aDemoDeveloperPayload"); } public void RestoreButtonClick() { if (m_IsCloudMoolahStoreSelected) { if (m_IsLoggedIn == false) { Debug.LogError("CloudMoolah purchase restoration aborted. Login incomplete."); } else { // Restore abnornal transaction identifer, if Client don't receive transaction identifer. m_MoolahExtensions.RestoreTransactionID((RestoreTransactionIDState restoreTransactionIDState) => { Debug.Log("restoreTransactionIDState = " + restoreTransactionIDState.ToString()); bool success = restoreTransactionIDState != RestoreTransactionIDState.RestoreFailed && restoreTransactionIDState != RestoreTransactionIDState.NotKnown; OnTransactionsRestored(success); }); } } else if (m_IsSamsungAppsStoreSelected) { m_SamsungExtensions.RestoreTransactions(OnTransactionsRestored); } else if (Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 || Application.platform == RuntimePlatform.WSAPlayerARM) { m_MicrosoftExtensions.RestoreTransactions(); } else { m_AppleExtensions.RestoreTransactions(OnTransactionsRestored); } } public void LoginButtonClick() { if (!m_IsUnityChannelSelected) { Debug.Log("Login is only required for the Xiaomi store"); return; } unityChannelLoginHandler.loginSucceededAction = (UserInfo userInfo) => { m_IsLoggedIn = true; Debug.LogFormat("Succeeded logging into UnityChannel. channel {0}, userId {1}, userLoginToken {2} ", userInfo.channel, userInfo.userId, userInfo.userLoginToken); }; unityChannelLoginHandler.loginFailedAction = (string message) => { m_IsLoggedIn = false; Debug.LogError("Failed logging into UnityChannel. " + message); }; StoreService.Login(unityChannelLoginHandler); } public void ValidateButtonClick() { // For local validation, see ProcessPurchase. if (!m_IsUnityChannelSelected) { Debug.Log("Remote purchase validation is only supported for the Xiaomi store"); return; } string txId = m_LastTransactionID; m_UnityChannelExtensions.ValidateReceipt(txId, (bool success, string signData, string signature) => { Debug.LogFormat("ValidateReceipt transactionId {0}, success {1}, signData {2}, signature {3}", txId, success, signData, signature); // May use signData and signature results to validate server-to-server }); } private void ClearProductUIs() { foreach (var productUIKVP in m_ProductUIs) { GameObject.Destroy(productUIKVP.Value.gameObject); } m_ProductUIs.Clear(); } private void AddProductUIs(Product[] products) { ClearProductUIs(); var templateRectTransform = productUITemplate.GetComponent<RectTransform>(); var height = templateRectTransform.rect.height; var currPos = templateRectTransform.localPosition; contentRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, products.Length * height); foreach (var p in products) { var newProductUI = GameObject.Instantiate(productUITemplate.gameObject) as GameObject; newProductUI.transform.SetParent(productUITemplate.transform.parent, false); var rect = newProductUI.GetComponent<RectTransform>(); rect.localPosition = currPos; currPos += Vector3.down * height; newProductUI.SetActive(true); var productUIComponent = newProductUI.GetComponent<IAPDemoProductUI>(); productUIComponent.SetProduct(p, PurchaseButtonClick); m_ProductUIs[p.definition.id] = productUIComponent; } } private void UpdateProductUI(Product p) { if (m_ProductUIs.ContainsKey(p.definition.id)) { m_ProductUIs[p.definition.id].SetProduct(p, PurchaseButtonClick); } } private void UpdateProductPendingUI(Product p, int secondsRemaining) { if (m_ProductUIs.ContainsKey(p.definition.id)) { m_ProductUIs[p.definition.id].SetPendingTime(secondsRemaining); } } private bool NeedRestoreButton() { return Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.tvOS || Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 || Application.platform == RuntimePlatform.WSAPlayerARM || m_IsSamsungAppsStoreSelected || m_IsCloudMoolahStoreSelected; } private bool NeedLoginButton() { return m_IsUnityChannelSelected; } private bool NeedValidateButton() { return m_IsUnityChannelSelected; } private void LogProductDefinitions() { var products = m_Controller.products.all; foreach (var product in products) { #if UNITY_5_6_OR_NEWER Debug.Log(string.Format("id: {0}\nstore-specific id: {1}\ntype: {2}\nenabled: {3}\n", product.definition.id, product.definition.storeSpecificId, product.definition.type.ToString(), product.definition.enabled ? "enabled" : "disabled")); #else Debug.Log(string.Format("id: {0}\nstore-specific id: {1}\ntype: {2}\n", product.definition.id, product.definition.storeSpecificId, product.definition.type.ToString())); #endif } } } #endif // UNITY_PURCHASING
41.177419
247
0.648016
[ "MIT" ]
casion0914/Assets
Plugins/UnityPurchasing/script/IAPDemo.cs
33,189
C#
using FlowScriptEngine; using System.Collections.Generic; namespace FlowScriptEngineBasic.TypeConverters { public class HashSetIEnumerableConverter : TemplateTypeConverter<HashSet<object>, IEnumerable<object>> { public override object Convert(object data) { return (IEnumerable<object>)data; } } }
23.266667
106
0.707736
[ "Apache-2.0" ]
KHCmaster/PPD
Win/FlowScriptEngineBasic/TypeConverters/HashSetIEnumerableConverter.cs
351
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="COCD_TP146337GB01.Author", Namespace="urn:hl7-org:v3")] public partial class COCD_TP146337GB01Author { private TemplateContent contentIdField; private COCD_TP146337GB01AuthorFunctionCode functionCodeField; private COCD_TP146337GB01AuthorTemplateId templateIdField; private TS timeField; private object itemField; private string nullFlavorField; private cs_UpdateMode updateModeField; private bool updateModeFieldSpecified; private string typeCodeField; private string contextControlCodeField; private static System.Xml.Serialization.XmlSerializer serializer; public COCD_TP146337GB01Author() { this.typeCodeField = "AUT"; this.contextControlCodeField = "OP"; } [System.Xml.Serialization.XmlElementAttribute(Namespace="NPFIT:HL7:Localisation")] public TemplateContent contentId { get { return this.contentIdField; } set { this.contentIdField = value; } } public COCD_TP146337GB01AuthorFunctionCode functionCode { get { return this.functionCodeField; } set { this.functionCodeField = value; } } public COCD_TP146337GB01AuthorTemplateId templateId { get { return this.templateIdField; } set { this.templateIdField = value; } } public TS time { get { return this.timeField; } set { this.timeField = value; } } [System.Xml.Serialization.XmlElementAttribute("COCD_TP145001UK03.AssignedAuthorSDS", typeof(COCD_TP145001UK03AssignedAuthorSDS))] [System.Xml.Serialization.XmlElementAttribute("COCD_TP145002UK03.AssignedAuthor", typeof(COCD_TP145002UK03AssignedAuthor))] [System.Xml.Serialization.XmlElementAttribute("COCD_TP145003UK03.AssignedAuthor", typeof(COCD_TP145003UK03AssignedAuthor))] [System.Xml.Serialization.XmlElementAttribute("COCD_TP145200GB01.AssignedAuthor", typeof(COCD_TP145200GB01AssignedAuthor))] public object Item { get { return this.itemField; } set { this.itemField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public cs_UpdateMode updateMode { get { return this.updateModeField; } set { this.updateModeField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool updateModeSpecified { get { return this.updateModeFieldSpecified; } set { this.updateModeFieldSpecified = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string typeCode { get { return this.typeCodeField; } set { this.typeCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string contextControlCode { get { return this.contextControlCodeField; } set { this.contextControlCodeField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(COCD_TP146337GB01Author)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current COCD_TP146337GB01Author object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an COCD_TP146337GB01Author object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output COCD_TP146337GB01Author object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out COCD_TP146337GB01Author obj, out System.Exception exception) { exception = null; obj = default(COCD_TP146337GB01Author); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out COCD_TP146337GB01Author obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static COCD_TP146337GB01Author Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((COCD_TP146337GB01Author)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current COCD_TP146337GB01Author object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an COCD_TP146337GB01Author object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output COCD_TP146337GB01Author object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out COCD_TP146337GB01Author obj, out System.Exception exception) { exception = null; obj = default(COCD_TP146337GB01Author); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out COCD_TP146337GB01Author obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static COCD_TP146337GB01Author LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this COCD_TP146337GB01Author object /// </summary> public virtual COCD_TP146337GB01Author Clone() { return ((COCD_TP146337GB01Author)(this.MemberwiseClone())); } #endregion } }
40.187898
1,368
0.573897
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/COCD_TP146337GB01Author.cs
12,619
C#
using Cauldron.Interception.Cecilator; namespace Cauldron.Interception.Fody.HelperTypes { public sealed class __Task : HelperTypeBase { public __Task(Builder builder) : base(builder, "System.Threading.Tasks.Task") { this.GetException = this.type.GetMethod("get_Exception"); } public Method GetException { get; private set; } } }
27.642857
85
0.669251
[ "MIT" ]
Capgemini/Cauldron
Old/Interception/Cauldron.Interception.Fody/HelperTypes/__Task.cs
389
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d12shader.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="D3D12_SHADER_VARIABLE_DESC" /> struct.</summary> public static unsafe class D3D12_SHADER_VARIABLE_DESCTests { /// <summary>Validates that the <see cref="D3D12_SHADER_VARIABLE_DESC" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<D3D12_SHADER_VARIABLE_DESC>(), Is.EqualTo(sizeof(D3D12_SHADER_VARIABLE_DESC))); } /// <summary>Validates that the <see cref="D3D12_SHADER_VARIABLE_DESC" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(D3D12_SHADER_VARIABLE_DESC).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="D3D12_SHADER_VARIABLE_DESC" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(D3D12_SHADER_VARIABLE_DESC), Is.EqualTo(48)); } else { Assert.That(sizeof(D3D12_SHADER_VARIABLE_DESC), Is.EqualTo(36)); } } } }
38.409091
145
0.657988
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/d3d12shader/D3D12_SHADER_VARIABLE_DESCTests.cs
1,692
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; namespace Develappers.BillomatNet.Types { public class InboxDocument : Document { public int UserId { get; set; } public DateTime Updated { get; set; } public int PageCount { get; set; } public Dictionary<string, string> Metadata { get; set; } public InboxDocumentType DocumentType { get; set; } } }
26.521739
71
0.686885
[ "MIT" ]
DevelappersGmbH/BillomatNet
Develappers.BillomatNet/Types/InboxDocument.cs
612
C#
//===================================================================================================================== // // ideMobi 2020© // //===================================================================================================================== // Define the use of Log and Benchmark only for this file! // Add NWD_VERBOSE in scripting define symbols (Edit->Project Settings…->Player->[Choose Plateform]->Other Settings->Scripting Define Symbols) #if NWD_VERBOSE #if UNITY_EDITOR #define NWD_LOG #define NWD_BENCHMARK #elif DEBUG //#define NWD_LOG //#define NWD_BENCHMARK #endif #else #undef NWD_LOG #undef NWD_BENCHMARK #endif //===================================================================================================================== #if UNITY_EDITOR using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; //===================================================================================================================== using UnityEditor; using NetWorkedData.NWDEditor; //===================================================================================================================== namespace NetWorkedData { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public partial class NWDBasis : NWDTypeClass { //------------------------------------------------------------------------------------------------------------- public override void NodeCardAnalyze(NWDNodeCard sCard) { //NWDBenchmark.Start(); sCard.ClassTexture = BasisHelper().TextureOfClass(); bool tDataAlReadyAnalyze = false; foreach (NWDNodeCard tCard in sCard.ParentDocument.AllCardsAnalyzed) { if (tCard.DataObject == sCard.DataObject) { tDataAlReadyAnalyze = true; break; } } // data is not in a preview card if (tDataAlReadyAnalyze == false) { // I add this card sCard.ParentDocument.AllCardsAnalyzed.Add(sCard); // I analyze this card and its properties (only the reference properties) Type tType = ClassType(); if (sCard.ParentDocument.AnalyzeStyleClasses[tType.Name] == NWDClasseAnalyseEnum.Analyze) { foreach (PropertyInfo tProp in tType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { Type tTypeOfThis = tProp.PropertyType; if (tProp.GetCustomAttributes(typeof(NWDHidden), true).Length > 0 || tProp.GetCustomAttributes(typeof(NWDNotVisible), true).Length > 0 ) { // hidden this property } else { if (tTypeOfThis != null) { if (tTypeOfThis.IsGenericType) { if ( tTypeOfThis.IsSubclassOf(typeof(NWDReferenceSimple)) || tTypeOfThis.IsSubclassOf(typeof(NWDReferenceMultiple)) ) { Type tSubType = tTypeOfThis.GetGenericArguments()[0]; sCard.ParentDocument.ClassesUsed.Add(tSubType.Name); var tVar = tProp.GetValue(this, null); if (tVar != null) { //object[] tObjects = tMethodInfo.Invoke(tVar, null) as object[]; object[] tObjects = new object[] { null }; if (tTypeOfThis.IsSubclassOf(typeof(NWDReferenceSimple))) { NWDReferenceSimple tTTVar = tVar as NWDReferenceSimple; tObjects = tTTVar.GetEditorDatas(); } if (tTypeOfThis.IsSubclassOf(typeof(NWDReferenceMultiple))) { NWDReferenceMultiple tTTVar = tVar as NWDReferenceMultiple; tObjects = tTTVar.GetEditorDatas(); } List<NWDNodeCard> tNewCards = sCard.AddPropertyResult(tObjects); // if (sCard.ParentDocument.AnalyzeStyleClasses[tSubType.Name] == NWDClasseAnalyseEnum.Show || //sCard.ParentDocument.AnalyzeStyleClasses[tSubType.Name] == NWDClasseAnalyseEnum.Analyze) { foreach (NWDNodeCard tNewCard in tNewCards) { tNewCard.Analyze(sCard.ParentDocument); } } } } } } } } } } //NWDBenchmark.Finish(); } //------------------------------------------------------------------------------------------------------------- } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ } //===================================================================================================================== #endif
49.706349
142
0.350471
[ "Apache-2.0" ]
NetWorkedData/NetWorkedData
NWDEditor/NWDNodeEditor/NWDBasis_DrawNode.cs
6,266
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Text; namespace OpenSim.Framework.Serialization { /// <summary> /// Temporary code to produce a tar archive in tar v7 format /// </summary> public class TarArchiveWriter { /// <summary> /// Binary writer for the underlying stream /// </summary> protected BinaryWriter m_bw; public TarArchiveWriter(Stream s) { m_bw = new BinaryWriter(s); } /// <summary> /// Write a directory entry to the tar archive. We can only handle one path level right now! /// </summary> /// <param name="dirName"></param> public void WriteDir(string dirName) { // Directories are signalled by a final / if (!dirName.EndsWith("/")) dirName += "/"; WriteFile(dirName, new byte[0]); } /// <summary> /// Write a file to the tar archive /// </summary> /// <param name="filePath"></param> /// <param name="data"></param> public void WriteFile(string filePath, string data) { WriteFile(filePath, Util.UTF8NoBomEncoding.GetBytes(data)); } /// <summary> /// Write a file to the tar archive /// </summary> /// <param name="filePath"></param> /// <param name="data"></param> public void WriteFile(string filePath, byte[] data) { if (filePath.Length > 100) WriteEntry("././@LongLink", Encoding.ASCII.GetBytes(filePath), 'L'); char fileType; if (filePath.EndsWith("/")) { fileType = '5'; } else { fileType = '0'; } WriteEntry(filePath, data, fileType); } /// <summary> /// Finish writing the raw tar archive data to a stream. The stream will be closed on completion. /// </summary> /// <param name="s">Stream to which to write the data</param> /// <returns></returns> public void Close() { // Write two consecutive 0 blocks to end the archive byte[] finalZeroPadding = new byte[1024]; lock (m_bw) { m_bw.Write(finalZeroPadding); m_bw.Flush(); m_bw.Close(); } } public static byte[] ConvertDecimalToPaddedOctalBytes(int d, int padding) { string oString = ""; while (d > 0) { oString = Convert.ToString((byte)'0' + d & 7) + oString; d >>= 3; } while (oString.Length < padding) { oString = "0" + oString; } byte[] oBytes = Encoding.ASCII.GetBytes(oString); return oBytes; } /// <summary> /// Write a particular entry /// </summary> /// <param name="filePath"></param> /// <param name="data"></param> /// <param name="fileType"></param> protected void WriteEntry(string filePath, byte[] data, char fileType) { byte[] header = new byte[512]; // file path field (100) byte[] nameBytes = Encoding.ASCII.GetBytes(filePath); int nameSize = (nameBytes.Length >= 100) ? 100 : nameBytes.Length; Array.Copy(nameBytes, header, nameSize); // file mode (8) byte[] modeBytes = Encoding.ASCII.GetBytes("0000777"); Array.Copy(modeBytes, 0, header, 100, 7); // owner user id (8) byte[] ownerIdBytes = Encoding.ASCII.GetBytes("0000764"); Array.Copy(ownerIdBytes, 0, header, 108, 7); // group user id (8) byte[] groupIdBytes = Encoding.ASCII.GetBytes("0000764"); Array.Copy(groupIdBytes, 0, header, 116, 7); // file size in bytes (12) int fileSize = data.Length; byte[] fileSizeBytes = ConvertDecimalToPaddedOctalBytes(fileSize, 11); Array.Copy(fileSizeBytes, 0, header, 124, 11); // last modification time (12) byte[] lastModTimeBytes = Encoding.ASCII.GetBytes("11017037332"); Array.Copy(lastModTimeBytes, 0, header, 136, 11); // entry type indicator (1) header[156] = Encoding.ASCII.GetBytes(new char[] { fileType })[0]; Array.Copy(Encoding.ASCII.GetBytes("0000000"), 0, header, 329, 7); Array.Copy(Encoding.ASCII.GetBytes("0000000"), 0, header, 337, 7); // check sum for header block (8) [calculated last] Array.Copy(Encoding.ASCII.GetBytes(" "), 0, header, 148, 8); int checksum = 0; foreach (byte b in header) { checksum += b; } byte[] checkSumBytes = ConvertDecimalToPaddedOctalBytes(checksum, 6); Array.Copy(checkSumBytes, 0, header, 148, 6); header[154] = 0; lock (m_bw) { // Write out header m_bw.Write(header); // Write out data // An IOException occurs if we try to write out an empty array in Mono 2.6 if (data.Length > 0) m_bw.Write(data); if (data.Length % 512 != 0) { int paddingRequired = 512 - (data.Length % 512); byte[] padding = new byte[paddingRequired]; m_bw.Write(padding); } } } } }
34.232558
106
0.554076
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Framework/Serialization/TarArchiveWriter.cs
7,360
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 inspector-2016-02-16.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.Inspector.Model { /// <summary> /// Contains information about an Amazon Inspector agent. This data type is used as a /// response element in the <a>ListAssessmentRunAgents</a> action. /// </summary> public partial class AssessmentRunAgent { private AgentHealth _agentHealth; private AgentHealthCode _agentHealthCode; private string _agentHealthDetails; private string _agentId; private string _assessmentRunArn; private string _autoScalingGroup; private List<TelemetryMetadata> _telemetryMetadata = new List<TelemetryMetadata>(); /// <summary> /// Gets and sets the property AgentHealth. /// <para> /// The current health state of the agent. /// </para> /// </summary> [AWSProperty(Required=true)] public AgentHealth AgentHealth { get { return this._agentHealth; } set { this._agentHealth = value; } } // Check to see if AgentHealth property is set internal bool IsSetAgentHealth() { return this._agentHealth != null; } /// <summary> /// Gets and sets the property AgentHealthCode. /// <para> /// The detailed health state of the agent. /// </para> /// </summary> [AWSProperty(Required=true)] public AgentHealthCode AgentHealthCode { get { return this._agentHealthCode; } set { this._agentHealthCode = value; } } // Check to see if AgentHealthCode property is set internal bool IsSetAgentHealthCode() { return this._agentHealthCode != null; } /// <summary> /// Gets and sets the property AgentHealthDetails. /// <para> /// The description for the agent health code. /// </para> /// </summary> [AWSProperty(Min=0, Max=1000)] public string AgentHealthDetails { get { return this._agentHealthDetails; } set { this._agentHealthDetails = value; } } // Check to see if AgentHealthDetails property is set internal bool IsSetAgentHealthDetails() { return this._agentHealthDetails != null; } /// <summary> /// Gets and sets the property AgentId. /// <para> /// The AWS account of the EC2 instance where the agent is installed. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string AgentId { get { return this._agentId; } set { this._agentId = value; } } // Check to see if AgentId property is set internal bool IsSetAgentId() { return this._agentId != null; } /// <summary> /// Gets and sets the property AssessmentRunArn. /// <para> /// The ARN of the assessment run that is associated with the agent. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=300)] public string AssessmentRunArn { get { return this._assessmentRunArn; } set { this._assessmentRunArn = value; } } // Check to see if AssessmentRunArn property is set internal bool IsSetAssessmentRunArn() { return this._assessmentRunArn != null; } /// <summary> /// Gets and sets the property AutoScalingGroup. /// <para> /// The Auto Scaling group of the EC2 instance that is specified by the agent ID. /// </para> /// </summary> [AWSProperty(Min=1, Max=256)] public string AutoScalingGroup { get { return this._autoScalingGroup; } set { this._autoScalingGroup = value; } } // Check to see if AutoScalingGroup property is set internal bool IsSetAutoScalingGroup() { return this._autoScalingGroup != null; } /// <summary> /// Gets and sets the property TelemetryMetadata. /// <para> /// The Amazon Inspector application data metrics that are collected by the agent. /// </para> /// </summary> [AWSProperty(Required=true, Min=0, Max=5000)] public List<TelemetryMetadata> TelemetryMetadata { get { return this._telemetryMetadata; } set { this._telemetryMetadata = value; } } // Check to see if TelemetryMetadata property is set internal bool IsSetTelemetryMetadata() { return this._telemetryMetadata != null && this._telemetryMetadata.Count > 0; } } }
31.843575
107
0.591404
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Inspector/Generated/Model/AssessmentRunAgent.cs
5,700
C#
using Microsoft.PowerBI.Api; using Newtonsoft.Json; using System.Management.Automation; using Models = Microsoft.PowerBI.Api.Models; namespace PsPowerBi { [Cmdlet(VerbsCommon.Get, "Datasource")] [OutputType(typeof(Models.Datasource))] public class GetDatasourceCommand : PSCmdlet { [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty()] public PowerBIClient Connection { get; set; } = ConnectServiceCommand.SessionConnection; [Parameter( Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByDataset")] [ValidateNotNullOrEmpty()] public Models.Dataset Dataset { get; set; } [Parameter( Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByGateway")] [ValidateNotNullOrEmpty()] public Models.Gateway Gateway { get; set; } protected override void ProcessRecord() { base.ProcessRecord(); if (Connection == null) throw new PSArgumentNullException(nameof(Connection), $"run Connect-PowerBiService"); switch (this.ParameterSetName) { case "ByDataset": { WriteVerbose($"Request datasources with filter on dataset { Dataset.Id }."); var datasources = Connection.Datasets.GetDatasources(Dataset.Id).Value; WriteVerbose($"{ datasources.Count } datasources received with filter on dataset { Dataset.Id }."); foreach (var datasource in datasources) { var result = new PSObject(datasource); result.Properties.Add(new PSNoteProperty("DatasetId", Dataset.Id)); WriteObject(result); } break; } case "ByGateway": { WriteVerbose($"Request datasources with filter on gateway { Gateway.Id }."); var datasources = Connection.Gateways.GetDatasources(Gateway.Id).Value; WriteVerbose($"{ datasources.Count } datasources received with filter on gateway { Gateway.Id }."); foreach (var datasource in datasources) { var result = new PSObject(datasource); result.Properties.Add(new PSNoteProperty("GatewayId", Gateway.Id)); dynamic dynamicObject = JsonConvert.DeserializeObject(datasource.ConnectionDetails); result.Properties.Add(new PSNoteProperty("Server", dynamicObject?.server.Value)); result.Properties.Add(new PSNoteProperty("Database", dynamicObject?.database.Value)); WriteObject(result); } break; } default: throw new System.NotImplementedException(this.ParameterSetName); } } } }
41.614458
124
0.528373
[ "MIT" ]
abbgrade/PsPowerBi
src/PsPowerBi/GetDatasourceCommand.cs
3,456
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using BuildXL.Cache.ContentStore.Interfaces.Logging; using BuildXL.Cache.ContentStore.Interfaces.Tracing; using BuildXL.Cache.ContentStore.Tracing; using BuildXL.Cache.ContentStore.Utils; using BuildXL.Cache.ContentStore.Vsts; using BuildXL.Cache.MemoizationStore.VstsInterfaces; using Microsoft.VisualStudio.Services.Content.Common; namespace BuildXL.Cache.MemoizationStore.Vsts.Http { /// <summary> /// Factory class for creating HTTP clients that can communicate with a VSTS Build Cache service. /// </summary> public class BuildCacheHttpClientFactory : IBuildCacheHttpClientFactory { private static readonly Tracer _tracer = new Tracer(nameof(BuildCacheHttpClientFactory)); private readonly Uri _buildCacheBaseUri; private readonly VssCredentialsFactory _vssCredentialsFactory; private readonly TimeSpan _httpSendTimeout; private readonly bool _useAad; /// <summary> /// Initializes a new instance of the <see cref="BuildCacheHttpClientFactory"/> class. /// </summary> public BuildCacheHttpClientFactory(Uri buildCacheBaseUri, VssCredentialsFactory vssCredentialsFactory, TimeSpan httpSendTimeout, bool useAad = true) { _buildCacheBaseUri = buildCacheBaseUri; _vssCredentialsFactory = vssCredentialsFactory; _httpSendTimeout = httpSendTimeout; _useAad = useAad; } /// <summary> /// Creates an http client that can communicate with a VSTS Build Cache Service. /// </summary> public async Task<IBuildCacheHttpClient> CreateBuildCacheHttpClientAsync(Context context) { IRetryPolicy retryPolicy = RetryPolicyFactory.GetExponentialPolicy(AuthorizationErrorDetectionStrategy.IsTransient); var creds = await retryPolicy.ExecuteAsync( () => _vssCredentialsFactory.CreateVssCredentialsAsync(_buildCacheBaseUri, _useAad), CancellationToken.None).ConfigureAwait(false); var httpClientFactory = new ArtifactHttpClientFactory( creds, _httpSendTimeout, tracer: new AppTraceSourceContextAdapter(context, "BuildCacheHttpClientFactory", SourceLevels.All), verifyConnectionCancellationToken: CancellationToken.None); // TODO: Pipe down cancellation support (bug 1365340) IBuildCacheHttpClient client = httpClientFactory.CreateVssHttpClient<IArtifactBuildCacheHttpClient, ItemBuildCacheHttpClient>(_buildCacheBaseUri); await ArtifactHttpClientErrorDetectionStrategy.ExecuteAsync( context, "VerifyBuildCacheHttpClientConnection", () => httpClientFactory.VerifyConnectionAsync(client as IArtifactHttpClient), CancellationToken.None).ConfigureAwait(false); _tracer.Debug(context, $"Verified connection to {_buildCacheBaseUri} with SessionId=[{httpClientFactory.ClientSettings.SessionId}]"); return client; } /// <summary> /// Creates an http client that can communicate with a VSTS Build Cache Service. /// </summary> public async Task<IBlobBuildCacheHttpClient> CreateBlobBuildCacheHttpClientAsync(Context context) { IRetryPolicy authRetryPolicy = RetryPolicyFactory.GetExponentialPolicy(AuthorizationErrorDetectionStrategy.IsTransient); var creds = await authRetryPolicy.ExecuteAsync( () => _vssCredentialsFactory.CreateVssCredentialsAsync(_buildCacheBaseUri, _useAad), CancellationToken.None).ConfigureAwait(false); var httpClientFactory = new ArtifactHttpClientFactory( creds, _httpSendTimeout, tracer: new AppTraceSourceContextAdapter(context, "BuildCacheHttpClientFactory", SourceLevels.All), verifyConnectionCancellationToken: CancellationToken.None); // TODO: Pipe down cancellation support (bug 1365340) IBlobBuildCacheHttpClient client = httpClientFactory.CreateVssHttpClient<IArtifactBlobBuildCacheHttpClient, BlobBuildCacheHttpClient>(_buildCacheBaseUri); await ArtifactHttpClientErrorDetectionStrategy.ExecuteAsync( context, "VerifyBlobBuildCacheHttpClientConnection", () => httpClientFactory.VerifyConnectionAsync(client as IArtifactHttpClient), CancellationToken.None).ConfigureAwait(false); _tracer.Debug(context, "Verified connection to {_buildCacheBaseUri} with SessionId=[{httpClientFactory.ClientSettings.SessionId}]"); return client; } } }
53.623656
157
0.69621
[ "MIT" ]
shivanshu3/BuildXL
Public/Src/Cache/MemoizationStore/Vsts/Http/BuildCacheHttpClientFactory.cs
4,987
C#
using System; using System.Collections.Generic; using System.Text; using TangleChainIXI.Classes; namespace TangleChainIXI.Interfaces { public interface IDownloadable { string NodeAddress { get; set; } string SendTo { get; set; } string Hash { get; set; } bool IsFinalized { get; } IDownloadable GenerateHash(); } }
18.6
40
0.650538
[ "MIT" ]
AskMeAgain/TangleChain
TangleChainIXI/Interfaces/IDownloadable.cs
374
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace BuildAnApp { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
39.318182
100
0.610405
[ "MIT" ]
JianGuoWan/third-edition
VS2013/Chapter_2/BuildAnApp/BuildAnApp/App.xaml.cs
4,327
C#
/* * Copyright (C) 2021 - 2021, SanteSuite Inc. and the SanteSuite Contributors (See NOTICE.md for full copyright notices) * Copyright (C) 2019 - 2021, Fyfe Software Inc. and the SanteSuite Contributors * Portions Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology * * 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. * * User: fyfej * Date: 2021-8-5 */ using Hl7.Fhir.Model; using SanteDB.Core.Model; using SanteDB.Core.Model.Constants; using SanteDB.Core.Model.DataTypes; using SanteDB.Core.Model.Entities; using SanteDB.Core.Services; using SanteDB.Messaging.FHIR.Util; using System; using System.Collections.Generic; using System.Linq; using static Hl7.Fhir.Model.CapabilityStatement; using Organization = Hl7.Fhir.Model.Organization; namespace SanteDB.Messaging.FHIR.Handlers { /// <summary> /// Represents a medication resource handler /// </summary> public class MedicationResourceHandler : RepositoryResourceHandlerBase<Medication, ManufacturedMaterial> { /// <summary> /// Initializes a new instance of the <see cref="MedicationResourceHandler"/> class. /// </summary> /// <param name="repositoryService">The repository service.</param> /// <param name="localizationService">The localization service.</param> public MedicationResourceHandler(IRepositoryService<ManufacturedMaterial> repositoryService, ILocalizationService localizationService) : base(repositoryService, localizationService) { } /// <summary> /// Get included resources /// </summary> protected override IEnumerable<Resource> GetIncludes(ManufacturedMaterial resource, IEnumerable<IncludeInstruction> includePaths) { throw new NotImplementedException(this.m_localizationService.GetString("error.type.NotImplementedException")); } /// <summary> /// Get interactions /// </summary> protected override IEnumerable<ResourceInteractionComponent> GetInteractions() { return new[] { TypeRestfulInteraction.Create, TypeRestfulInteraction.Update, TypeRestfulInteraction.HistoryInstance, TypeRestfulInteraction.Read, TypeRestfulInteraction.SearchType, TypeRestfulInteraction.Vread, TypeRestfulInteraction.Delete }.Select(o => new ResourceInteractionComponent {Code = o}); } /// <summary> /// Get reverse included resources /// </summary> protected override IEnumerable<Resource> GetReverseIncludes(ManufacturedMaterial resource, IEnumerable<IncludeInstruction> reverseIncludePaths) { throw new NotImplementedException(this.m_localizationService.GetString("error.type.NotImplementedException")); } /// <summary> /// Maps a <see cref="ManufacturedMaterial"/> instance to a FHIR <see cref="Medication"/> instance. /// </summary> /// <param name="model">The instance to map.</param> /// <returns>Returns the mapped instance.</returns> protected override Medication MapToFhir(ManufacturedMaterial model) { var retVal = DataTypeConverter.CreateResource<Medication>(model); // Code of medication code retVal.Code = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty<Concept>(nameof(Entity.TypeConcept)), "http://snomed.info/sct"); retVal.Identifier = model.LoadCollection<EntityIdentifier>(nameof(Entity.Identifiers)).Select(DataTypeConverter.ToFhirIdentifier).ToList(); switch (model.StatusConceptKey.ToString().ToUpper()) { case StatusKeyStrings.Active: case StatusKeyStrings.New: retVal.Status = Medication.MedicationStatusCodes.Active; break; case StatusKeyStrings.Obsolete: retVal.Status = Medication.MedicationStatusCodes.Inactive; break; case StatusKeyStrings.Nullified: retVal.Status = Medication.MedicationStatusCodes.EnteredInError; break; } // Is brand? var manufacturer = model.LoadCollection<EntityRelationship>("Relationships").FirstOrDefault(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.ManufacturedProduct); if (manufacturer != null) { retVal.Manufacturer = DataTypeConverter.CreateVersionedReference<Organization>(manufacturer.LoadProperty<Entity>(nameof(EntityRelationship.TargetEntity))); } // Form retVal.Form = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty<Concept>("FormConcept"), "http://hl7.org/fhir/ValueSet/medication-form-codes"); retVal.Batch = new Medication.BatchComponent { LotNumber = model.LotNumber, ExpirationDateElement = DataTypeConverter.ToFhirDateTime(model.ExpiryDate) }; return retVal; } /// <summary> /// Maps a FHIR <see cref="Medication"/> to a <see cref="ManufacturedMaterial"/> instance. /// </summary> /// <param name="resource">The model resource to be mapped</param> /// <returns>Returns the mapped <see cref="ManufacturedMaterial"/> instance.</returns> protected override ManufacturedMaterial MapToModel(Medication resource) { ManufacturedMaterial manufacturedMaterial; if (Guid.TryParse(resource.Id, out var key)) { manufacturedMaterial = this.m_repository.Get(key) ?? new ManufacturedMaterial { Key = key }; } else { manufacturedMaterial = new ManufacturedMaterial { Key = Guid.NewGuid() }; } manufacturedMaterial.Identifiers = resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier).ToList(); manufacturedMaterial.TypeConcept = DataTypeConverter.ToConcept(resource.Code?.Coding?.FirstOrDefault(), "http://snomed.info/sct"); switch (resource.Status) { case Medication.MedicationStatusCodes.Active: manufacturedMaterial.StatusConceptKey = StatusKeys.Active; break; case Medication.MedicationStatusCodes.Inactive: manufacturedMaterial.StatusConceptKey = StatusKeys.Obsolete; break; case Medication.MedicationStatusCodes.EnteredInError: manufacturedMaterial.StatusConceptKey = StatusKeys.Nullified; break; } manufacturedMaterial.LotNumber = resource.Batch?.LotNumber; manufacturedMaterial.ExpiryDate = DataTypeConverter.ToDateTimeOffset(resource.Batch?.ExpirationDateElement)?.DateTime; if (resource.Manufacturer != null) { manufacturedMaterial.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.ManufacturedProduct, DataTypeConverter.ResolveEntity<Core.Model.Entities.Organization>(resource.Manufacturer, resource))); } return manufacturedMaterial; } } }
43.693989
227
0.648699
[ "Apache-2.0" ]
santedb/santedb-fhir
SanteDB.Messaging.FHIR/Handlers/MedicationResourceHandler.cs
7,998
C#
using System.ComponentModel.DataAnnotations; using Abp.Auditing; using Abp.Authorization.Users; using Abp.AutoMapper; using Abp.Runtime.Validation; using SMS.ALL.Authorization.Users; namespace SMS.ALL.Users.Dto { [AutoMapTo(typeof(User))] public class CreateUserDto : IShouldNormalize { [Required] [StringLength(AbpUserBase.MaxUserNameLength)] public string UserName { get; set; } [Required] [StringLength(AbpUserBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpUserBase.MaxSurnameLength)] public string Surname { get; set; } [Required] [EmailAddress] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string EmailAddress { get; set; } public bool IsActive { get; set; } public string[] RoleNames { get; set; } [Required] [StringLength(AbpUserBase.MaxPlainPasswordLength)] [DisableAuditing] public string Password { get; set; } public void Normalize() { if (RoleNames == null) { RoleNames = new string[0]; } } } }
25.125
58
0.613599
[ "MIT" ]
UtpalMaiti/SMS.ALL.ANGULAR
src/SMS.ALL.Application/Users/Dto/CreateUserDto.cs
1,206
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CoreWiki.Core.Configuration { public class EmailNotifications { public string SendGridApiKey { get; set; } public string FromEmailAddress { get; set; } public string FromName { get; set; } } }
20.8
47
0.717949
[ "MIT" ]
ChaplinMarchais/CoreWiki
CoreWiki.Core/Configuration/EmailNotifications.cs
300
C#
namespace DSInternals.DataStore { using System; using System.IO; using Microsoft.Database.Isam; using Microsoft.Isam.Esent.Interop; public class DirectoryContext : IDisposable { private const string JetInstanceName = "DSInternals"; private IsamInstance instance; private IsamSession session; private IsamDatabase database; private string attachedDatabasePath; /// <summary> /// Creates a new Active Directory database context. /// </summary> /// <param name="dbPath">dbFilePath must point to the DIT file on the local computer.</param> /// <param name="logPath">The path should point to a writeable folder on the local computer, where ESE log files will be created. If not specified, then temp folder will be used.</param> public DirectoryContext(string dbFilePath, bool readOnly, string logDirectoryPath = null) { if (!File.Exists(dbFilePath)) { // TODO: Extract as resource throw new FileNotFoundException("The specified database file does not exist.", dbFilePath); } ValidateDatabaseState(dbFilePath); string dbDirectoryPath = Path.GetDirectoryName(dbFilePath); string checkpointDirectoryPath = dbDirectoryPath; string tempDirectoryPath = dbDirectoryPath; if (logDirectoryPath != null) { if (!Directory.Exists(logDirectoryPath)) { // TODO: Extract as resource throw new FileNotFoundException("The specified log directory does not exist.", logDirectoryPath); } } else { logDirectoryPath = dbDirectoryPath; } // TODO: Exception handling? // HACK: IsamInstance constructor throws AccessDenied Exception when the path does not end with a backslash. this.instance = new IsamInstance(AddPathSeparator(checkpointDirectoryPath), AddPathSeparator(logDirectoryPath), AddPathSeparator(tempDirectoryPath), ADConstants.EseBaseName, JetInstanceName, readOnly, ADConstants.PageSize); try { var isamParameters = this.instance.IsamSystemParameters; // TODO: Add param explanations isamParameters.LogFileSize = ADConstants.EseLogFileSize; isamParameters.DeleteOutOfRangeLogs = true; isamParameters.EnableIndexChecking = 1; isamParameters.EnableIndexCleanup = true; isamParameters.CircularLog = true; // TODO: Configure additional ISAM parameters // this.instance.IsamSystemParameters.EnableOnlineDefrag = false; // JET_paramDeleteOldLogs = 1 this.session = this.instance.CreateSession(); this.session.AttachDatabase(dbFilePath); this.attachedDatabasePath = dbFilePath; this.database = this.session.OpenDatabase(dbFilePath); this.Schema = new DirectorySchema(this.database); this.SecurityDescriptorRersolver = new SecurityDescriptorRersolver(this.database); this.DistinguishedNameResolver = new DistinguishedNameResolver(this.database, this.Schema); this.LinkResolver = new LinkResolver(this.database, this.Schema); this.DomainController = new DomainController(this); } catch (EsentUnicodeTranslationFailException unicodeException) { // This typically happens while opening a Windows Server 2003 DIT on a newer system. this.Dispose(); throw new InvalidDatabaseStateException("There was a problem reading the database, which probably comes from a legacy system. Try defragmenting it first by running the 'esentutl /d ntds.dit' command.", dbFilePath, unicodeException); } catch { // Free resources if anything failed this.Dispose(); throw; } } public DirectorySchema Schema { get; private set; } public LinkResolver LinkResolver { get; private set; } public DomainController DomainController { get; private set; } public DistinguishedNameResolver DistinguishedNameResolver { get; private set; } public SecurityDescriptorRersolver SecurityDescriptorRersolver { get; private set; } public Cursor OpenDataTable() { return this.database.OpenCursor(ADConstants.DataTableName); } public Cursor OpenLinkTable() { return this.database.OpenCursor(ADConstants.LinkTableName); } public Cursor OpenSystemTable() { return this.database.OpenCursor(ADConstants.SystemTableName); } public IsamTransaction BeginTransaction() { return new IsamTransaction(this.session); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing) { // Do nothing return; } if(this.LinkResolver != null) { this.LinkResolver.Dispose(); this.LinkResolver = null; } if (this.SecurityDescriptorRersolver != null) { this.SecurityDescriptorRersolver.Dispose(); this.SecurityDescriptorRersolver = null; } if (this.DistinguishedNameResolver != null) { this.DistinguishedNameResolver.Dispose(); this.DistinguishedNameResolver = null; } if (this.DomainController != null) { this.DomainController.Dispose(); this.DomainController = null; } if (this.database != null) { this.database.Dispose(); this.database = null; } if (this.session != null) { if (this.attachedDatabasePath != null) { this.session.DetachDatabase(this.attachedDatabasePath); this.attachedDatabasePath = null; } this.session.Dispose(); this.session = null; } if (this.instance != null) { this.instance.Dispose(); this.instance = null; } } private static string AddPathSeparator(string path) { // TODO: Newer version of ISAM should implemet this if (string.IsNullOrEmpty(path) || path.EndsWith(Path.DirectorySeparatorChar.ToString())) { // No need to add path separator return path; } else { return path + Path.DirectorySeparatorChar; } } private static void ValidateDatabaseState(string dbFilePath) { // Retrieve info about the DB (Win Version, Page Size, State,...) JET_DBINFOMISC dbInfo; Api.JetGetDatabaseFileInfo(dbFilePath, out dbInfo, JET_DbInfo.Misc); if (dbInfo.dbstate != JET_dbstate.CleanShutdown) { // Database might be inconsistent // TODO: Extract message as a recource throw new InvalidDatabaseStateException("The database is not in a clean state. Try to recover it first by running the 'esentutl /r edb /d' command.", dbFilePath); } } } }
37.041096
248
0.56287
[ "MIT" ]
Alvimar/DSInternals
Src/DSInternals.DataStore/DirectoryContext.cs
8,114
C#
/* * Copyright (c) 2019 ETH Zürich, Educational Development and Technology (LET) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.IO; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using SafeExamBrowser.Configuration.DataCompression; using SafeExamBrowser.Logging.Contracts; namespace SafeExamBrowser.Configuration.UnitTests.DataCompression { [TestClass] public class GZipCompressorTests { private const int ID1 = 0x1F; private const int ID2 = 0x8B; private const int CM = 8; private const int FOOTER_LENGTH = 8; private const int HEADER_LENGTH = 10; private Mock<ILogger> logger; private GZipCompressor sut; [TestInitialize] public void Initialize() { logger = new Mock<ILogger>(); sut = new GZipCompressor(logger.Object); } [TestMethod] public void MustCorrectlyDetectGZipStream() { var randomBytes = new byte[123]; new Random().NextBytes(randomBytes); Assert.IsFalse(sut.IsCompressed(null)); Assert.IsFalse(sut.IsCompressed(new MemoryStream())); Assert.IsFalse(sut.IsCompressed(new MemoryStream(randomBytes))); Assert.IsTrue(sut.IsCompressed(new MemoryStream(new byte[] { ID1, ID2, CM }.Concat(randomBytes).ToArray()))); } [TestMethod] public void MustPerformCorrectly() { var data = Encoding.UTF8.GetBytes(String.Join(" ", Enumerable.Repeat("A comparatively easy text to compress.", 100))); var compressed = sut.Compress(new MemoryStream(data)); compressed.Seek(0, SeekOrigin.Begin); Assert.AreEqual(ID1, compressed.ReadByte()); Assert.AreEqual(ID2, compressed.ReadByte()); Assert.AreEqual(CM, compressed.ReadByte()); Assert.IsTrue(compressed.Length < data.Length); var decompressed = sut.Decompress(compressed); decompressed.Seek(0, SeekOrigin.Begin); foreach (var item in data) { Assert.AreEqual(item, decompressed.ReadByte()); } Assert.IsTrue(decompressed.Length == data.Length); } [TestMethod] public void MustPreviewDataCorrectly() { var data = Encoding.UTF8.GetBytes("A comparatively easy text to compress."); var compressed = sut.Compress(new MemoryStream(data)); var preview = sut.Peek(compressed, 5); try { var position = compressed.Position; var length = compressed.Length; } catch (ObjectDisposedException) { Assert.Fail("Source stream was disposed after previewing data!"); } Assert.AreEqual(5, preview.Length); Assert.IsTrue(Encoding.UTF8.GetBytes("A com").SequenceEqual(preview)); } } }
27.029703
121
0.721978
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
junbaor/seb-win-refactoring
SafeExamBrowser.Configuration.UnitTests/DataCompression/GZipCompressorTests.cs
2,733
C#
using Microsoft.Xna.Framework; using Nez.UI; #if DEBUG namespace Nez { public class ColorInspector : Inspector { TextField _textFieldR, _textFieldG, _textFieldB, _textFieldA; public override void initialize( Table table, Skin skin, float leftCellWidth ) { var value = getValue<Color>(); var label = createNameLabel( table, skin, leftCellWidth ); var labelR = new Label( "r", skin ); _textFieldR = new TextField( value.R.ToString(), skin ); _textFieldR.setMaxLength( 3 ); _textFieldR.setTextFieldFilter( new DigitsOnlyFilter() ).setPreferredWidth( 28 ); _textFieldR.onTextChanged += ( field, str ) => { int newR; if( int.TryParse( str, out newR ) ) { var newValue = getValue<Color>(); newValue.R = (byte)newR; setValue( newValue ); } }; var labelG = new Label( "g", skin ); _textFieldG = new TextField( value.G.ToString(), skin ); _textFieldG.setMaxLength( 3 ); _textFieldG.setTextFieldFilter( new DigitsOnlyFilter() ).setPreferredWidth( 28 ); _textFieldG.onTextChanged += ( field, str ) => { int newG; if( int.TryParse( str, out newG ) ) { var newValue = getValue<Color>(); newValue.G = (byte)newG; setValue( newValue ); } }; var labelB = new Label( "b", skin ); _textFieldB = new TextField( value.B.ToString(), skin ); _textFieldB.setMaxLength( 3 ); _textFieldB.setTextFieldFilter( new DigitsOnlyFilter() ).setPreferredWidth( 28 ); _textFieldB.onTextChanged += ( field, str ) => { int newB; if( int.TryParse( str, out newB ) ) { var newValue = getValue<Color>(); newValue.B = (byte)newB; setValue( newValue ); } }; var labelA = new Label( "a", skin ); _textFieldA = new TextField( value.A.ToString(), skin ); _textFieldA.setMaxLength( 3 ); _textFieldA.setTextFieldFilter( new DigitsOnlyFilter() ).setPreferredWidth( 28 ); _textFieldA.onTextChanged += ( field, str ) => { int newA; if( int.TryParse( str, out newA ) ) { var newValue = getValue<Color>(); newValue.A = (byte)newA; setValue( newValue ); } }; var hBox = new HorizontalGroup( 2 ); hBox.addElement( labelR ); hBox.addElement( _textFieldR ); hBox.addElement( labelG ); hBox.addElement( _textFieldG ); hBox.addElement( labelB ); hBox.addElement( _textFieldB ); hBox.addElement( labelA ); hBox.addElement( _textFieldA ); table.add( label ); table.add( hBox ); } public override void update() { var value = getValue<Color>(); _textFieldR.setText( value.R.ToString() ); _textFieldG.setText( value.G.ToString() ); } } } #endif
26.156863
84
0.640555
[ "MIT" ]
Blucky87/Nez
Nez.Portable/Debugger/Inspector/Inspectors/ColorInspector.cs
2,670
C#
using System; using System.Collections.Generic; using System.Linq; namespace pelazem.util { public class ValidationResult { private List<Validation> _validations = null; public virtual IList<Validation> Validations { get { if (_validations == null) _validations = new List<Validation>(); return _validations; } } public bool IsValid { get { return (_validations == null || this.Validations.Count == 0 | this.Validations.Where(r => !r.IsValid).Count() == 0); } } } public class Validation { public bool IsValid { get; set; } = false; public string Message { get; set; } = string.Empty; } }
17.236842
120
0.654962
[ "MIT" ]
plzm/pelazem.util
pelazem.util/ValidationResult.cs
657
C#
using System; using System.Collections.Generic; namespace CurrieTechnologies.Razor.WebAuthn { public class PublicKeyCredentialCreationOptions { public PublicKeyCredentialRpEntity Rp { get; set; } public PublicKeyCredentialUserEntity User { get; set; } #pragma warning disable CA1819 // Properties should not return arrays public byte[] Challenge { get; set; } #pragma warning restore CA1819 // Properties should not return arrays public IEnumerable<PublicKeyCredentialParameters> PubKeyCredParams { get; set; } public ulong? Timeout { get; set; } public IEnumerable<PublicKeyCredentialDescriptor>? ExcludeCredentials { get; set; } = Array.Empty<PublicKeyCredentialDescriptor>(); public AuthenticatorSelectionCriteria? AuthenticatorSelection { get; set; } public AttestationConveyancePreference? Attestation { get; set; } = AttestationConveyancePreference.None; public AuthenticationExtensionsClientInputs? Extensions { get; set; } } }
44.478261
139
0.744868
[ "MIT" ]
Basaingeal/Razor.WebAuthn
Dictionaries/PublicKeyCredentialCreationOptions.cs
1,025
C#
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System.Text.Json.Serialization; using System.Runtime.Serialization; #pragma warning disable 1591 namespace Plotly.Blazor.Traces.ScatterGlLib.MarkerLib.ColorBarLib { /// <summary> /// Determines where tick labels are drawn relative to the ticks. Left and right /// options are used when <c>orientation</c> is <c>h</c>, top and bottom when /// <c>orientation</c> is <c>v</c>. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [JsonConverter(typeof(EnumConverter))] public enum TickLabelPositionEnum { [EnumMember(Value=@"outside")] Outside = 0, [EnumMember(Value=@"inside")] Inside, [EnumMember(Value=@"outside top")] OutsideTop, [EnumMember(Value=@"inside top")] InsideTop, [EnumMember(Value=@"outside left")] OutsideLeft, [EnumMember(Value=@"inside left")] InsideLeft, [EnumMember(Value=@"outside right")] OutsideRight, [EnumMember(Value=@"inside right")] InsideRight, [EnumMember(Value=@"outside bottom")] OutsideBottom, [EnumMember(Value=@"inside bottom")] InsideBottom } }
31.658537
88
0.624807
[ "MIT" ]
ScriptBox99/Plotly.Blazor
Plotly.Blazor/Traces/ScatterGlLib/MarkerLib/ColorBarLib/TickLabelPositionEnum.cs
1,298
C#
/* Sourced from Nord: * https://github.com/arcticicestudio/nord * https://www.nordtheme.com/docs/colors-and-palettes */ namespace ScottPlot.Drawing.Colorsets { public class Snowstorm : HexColorset, IPalette { public override string[] hexColors => new string[] { "#D8DEE9", "#E5E9F0", "#ECEFF4" }; } }
23.533333
58
0.617564
[ "MIT" ]
BambOoxX/ScottPlot
src/ScottPlot/Palettes/Snowstorm.cs
355
C#
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DotNetNuke.Modules.Groups { public partial class View { /// <summary> /// plhContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder plhContent; } }
32.37931
101
0.517572
[ "MIT" ]
Acidburn0zzz/Dnn.Platform
DNN Platform/Modules/Groups/View.ascx.designer.cs
941
C#
using System; using System.Windows.Forms; namespace APNGBuilder { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
22.45
66
0.547884
[ "MIT" ]
murrple-1/APNGManagement
APNGBuilder/Program.cs
451
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BarLauncher.BaseConverter.Lib.Service; namespace BarLauncher.BaseConverter.Test.Mock.Service { public class SystemInformationsMock : ISystemInformations { public string ApplicationName { get; set; } public string Version { get; set; } public string HomepageUrl { get; set; } } }
22.1
61
0.726244
[ "MIT" ]
gissehel/BarLauncher-BaseConverter
BarLauncher.BaseConverter.Test.Mock/Service/SystemInformations.cs
444
C#
namespace Peep.Wings.Domain.Services; public interface IOAuthService<T> where T : class { Task<T> RetrieveLoggedUserInformation(string token); }
19
56
0.769737
[ "MIT" ]
guilhermedjr/clone-twitter
source/Peep.Wings/Peep.Wings.Domain/Services/IOAuthService.cs
154
C#
/************************************************************************************* Extended WPF Toolkit Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://xceed.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ internal static class _XceedVersionInfoCommon { [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields" )] public const string Build = ".*"; }
35.173913
111
0.598269
[ "MIT" ]
0xflotus/Materia
wpftoolkit-master/wpftoolkit-master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.AvalonDock.Themes.Aero/AssemblyVersionInfoCommon.cs
811
C#
using System; namespace rock_paper_scissor { public class Program { static void Main(string[] args) { Console.WriteLine("Hello there put your input- Rock, Scissor or Paper"); string input = Console.ReadLine(); // Console.WriteLine(input); int sum = 0; string[] myArray = { "rock", "paper", "scissors" }; string player2 = "rock"; if (input.ToLower() == player2) { Console.WriteLine("You Won"); sum += 1; Console.WriteLine($"you won {sum} times."); } else if (input.ToLower() == null || input == "") { Console.WriteLine("Please enter- either rock or paper or sissor"); string input2 = Console.ReadLine(); youWon(input2); Console.WriteLine($"you won {sum} times."); } else { Console.WriteLine("You lost, better luck next time"); } void youWon(string a) { if (a.ToLower() == "rock") { Console.WriteLine("You Won"); sum++; } else { Console.WriteLine("You lost, better luck next time"); } } } } }
28.041667
84
0.451709
[ "MIT" ]
2011-nov02-net/dhurba-code
rock-paper-scissor/Program.cs
1,348
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SnapOnTop.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources () { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SnapOnTop.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
33.722222
160
0.688633
[ "MIT" ]
Fragatta/SnapOnMatt
Properties/Resources.Designer.cs
2,430
C#
/*********************************************************************** * Project: CoreCms * ProjectName: 核心内容管理系统 * Web: https://www.corecms.net * Author: 大灰灰 * Email: jianweie@163.com * CreateTime: 2021/1/31 21:45:10 * Description: 暂无 ***********************************************************************/ using System; using System.Collections.Generic; using System.Threading.Tasks; using CoreCms.Net.Caching.Manual; using CoreCms.Net.Configuration; using CoreCms.Net.Model.Entities; using CoreCms.Net.Model.ViewModels.Basics; using CoreCms.Net.IRepository; using CoreCms.Net.IRepository.UnitOfWork; using CoreCms.Net.Model.Entities.Entities; using CoreCms.Net.Model.ViewModels.UI; using SqlSugar; namespace CoreCms.Net.Repository { /// <summary> /// 商品分类 接口实现 /// </summary> public class CoreCmsGoodsCategoryRepository : BaseRepository<CoreCmsGoodsCategory>, ICoreCmsGoodsCategoryRepository { public CoreCmsGoodsCategoryRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } #region 实现重写增删改查操作========================================================== /// <summary> /// 重写异步插入方法 /// </summary> /// <param name="entity">实体数据</param> /// <returns></returns> public new async Task<AdminUiCallBack> InsertAsync(CoreCmsGoodsCategory entity) { var jm = new AdminUiCallBack(); var bl = await DbClient.Insertable(entity).ExecuteReturnIdentityAsync() > 0; jm.code = bl ? 0 : 1; jm.msg = bl ? GlobalConstVars.CreateSuccess : GlobalConstVars.CreateFailure; if (bl) { await UpdateCaChe(); } return jm; } /// <summary> /// 重写异步更新方法 /// </summary> /// <param name="entity"></param> /// <returns></returns> public new async Task<AdminUiCallBack> UpdateAsync(CoreCmsGoodsCategory entity) { var jm = new AdminUiCallBack(); //事物处理过程结束 var bl = await DbClient.Updateable(entity).ExecuteCommandHasChangeAsync(); jm.code = bl ? 0 : 1; jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure; if (bl) { await UpdateCaChe(); } return jm; } /// <summary> /// 重写异步更新方法方法 /// </summary> /// <param name="entity"></param> /// <returns></returns> public new async Task<AdminUiCallBack> UpdateAsync(List<CoreCmsGoodsCategory> entity) { var jm = new AdminUiCallBack(); var bl = await DbClient.Updateable(entity).ExecuteCommandHasChangeAsync(); jm.code = bl ? 0 : 1; jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure; if (bl) { await UpdateCaChe(); } return jm; } /// <summary> /// 重写删除指定ID的数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public new async Task<AdminUiCallBack> DeleteByIdAsync(object id) { var jm = new AdminUiCallBack(); var bl = await DbClient.Deleteable<CoreCmsGoodsCategory>(id).ExecuteCommandHasChangeAsync(); jm.code = bl ? 0 : 1; jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure; if (bl) { await UpdateCaChe(); } return jm; } /// <summary> /// 重写删除指定ID集合的数据(批量删除) /// </summary> /// <param name="ids"></param> /// <returns></returns> public new async Task<AdminUiCallBack> DeleteByIdsAsync(int[] ids) { var jm = new AdminUiCallBack(); var bl = await DbClient.Deleteable<CoreCmsGoodsCategory>().In(ids).ExecuteCommandHasChangeAsync(); jm.code = bl ? 0 : 1; jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure; if (bl) { await UpdateCaChe(); } return jm; } #endregion #region 获取缓存的所有数据========================================================== /// <summary> /// 获取缓存的所有数据 /// </summary> /// <returns></returns> public async Task<List<CoreCmsGoodsCategory>> GetCaChe() { var cache = ManualDataCache.Instance.Get<List<CoreCmsGoodsCategory>>(GlobalConstVars.CacheCoreCmsGoodsCategory); if (cache != null) { return cache; } return await UpdateCaChe(); } /// <summary> /// 更新cache /// </summary> private async Task<List<CoreCmsGoodsCategory>> UpdateCaChe() { var list = await DbClient.Queryable<CoreCmsGoodsCategory>().With(SqlWith.NoLock).ToListAsync(); ManualDataCache.Instance.Set(GlobalConstVars.CacheCoreCmsGoodsCategory, list); return list; } #endregion } }
31.934911
124
0.511025
[ "Apache-2.0" ]
XRJ1230663/CoreShop
CoreCms.Net.Repository/Good/CoreCmsGoodsCategoryRepository.cs
5,623
C#
using System; namespace BattleLogic.BattleResources { public interface IResource { event Action<int> Changed; BattleResourceType Type { get; } int Value { get; } void Add(int value); void Remove(int value); } }
16.533333
37
0.645161
[ "MIT" ]
NeoremFf/Wizard-Fighter
WizardFighter/Assets/Scripts/BattleLogic/BattleResources/IResource.cs
250
C#
using System; namespace Entitas.CodeGenerator { [AttributeUsage(AttributeTargets.Class)] public class CustomPrefixAttribute : Attribute { public string prefix; public CustomPrefixAttribute(string prefix) { this.prefix = prefix; } } }
21.923077
53
0.663158
[ "MIT" ]
MrMonotone/SimpleFight
Assets/ThirdParty/Entitas-Unity/Entitas.CodeGenerator/Attributes/CustomPrefixAttribute.cs
287
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20191201.Inputs { /// <summary> /// Specifies the peering configuration. /// </summary> public sealed class ExpressRouteCircuitPeeringConfigArgs : Pulumi.ResourceArgs { [Input("advertisedCommunities")] private InputList<string>? _advertisedCommunities; /// <summary> /// The communities of bgp peering. Specified for microsoft peering. /// </summary> public InputList<string> AdvertisedCommunities { get => _advertisedCommunities ?? (_advertisedCommunities = new InputList<string>()); set => _advertisedCommunities = value; } [Input("advertisedPublicPrefixes")] private InputList<string>? _advertisedPublicPrefixes; /// <summary> /// The reference to AdvertisedPublicPrefixes. /// </summary> public InputList<string> AdvertisedPublicPrefixes { get => _advertisedPublicPrefixes ?? (_advertisedPublicPrefixes = new InputList<string>()); set => _advertisedPublicPrefixes = value; } /// <summary> /// The CustomerASN of the peering. /// </summary> [Input("customerASN")] public Input<int>? CustomerASN { get; set; } /// <summary> /// The legacy mode of the peering. /// </summary> [Input("legacyMode")] public Input<int>? LegacyMode { get; set; } /// <summary> /// The RoutingRegistryName of the configuration. /// </summary> [Input("routingRegistryName")] public Input<string>? RoutingRegistryName { get; set; } public ExpressRouteCircuitPeeringConfigArgs() { } } }
31.569231
102
0.621345
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20191201/Inputs/ExpressRouteCircuitPeeringConfigArgs.cs
2,052
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace dnsimple_dotnet.Data { public class User { [JsonProperty("email")] public string Email { get; set; } [JsonProperty("id")] public long Id { get; set; } } }
17.764706
41
0.625828
[ "MIT" ]
kfrancis/dnsimple-dotnet
src/dnsimple-dotnet/Data/User.cs
304
C#
using System.ComponentModel.DataAnnotations; namespace App.Infrastructure.Data { public class Tag { public int Id { get; set; } [Required] public string Name { get; set; } public string Description { get; set; } // Navigation public virtual ICollection<Post> Posts { get; set; } = new List<Post>(); public virtual ICollection<TagPost> TagPosts { get; set; } = new List<TagPost>(); } }
24.105263
89
0.60917
[ "MIT" ]
alpyesil/.Net-6-Twitter-Clone
App.Infrastructure/Data/Tag.cs
460
C#
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using Sasinosoft.SampMapEditor.Pedestrians; namespace Sasinosoft.SampMapEditor.IDE { /// <summary> /// Represents a "peds" IDE element. /// </summary> /// <see cref="https://gtamods.com/wiki/PEDS"/> public class PedsIDEElement : IDEElement { public UInt32 Id; public string ModelName; public string TextureDictionaryName; public PedestrianType Type; public string Behavior; public string AnimationGroup; public string CarsCanDrive; public UInt32 Flags; public string AnimationFile; public UInt32 Radio1; public UInt32 Radio2; public string VoiceArchive; public string Voice1; public string Voice2; } }
30.30303
71
0.634
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SaSiNO97/scene-editor
Sasinosoft.SampMapEditor/IDE/PedsIDEElement.cs
1,000
C#
namespace ET { [ObjectSystem] public class SessionIdleCheckerComponentAwakeSystem: AwakeSystem<SessionIdleCheckerComponent, int> { public override void Awake(SessionIdleCheckerComponent self, int checkInteral) { self.RepeatedTimer = TimerComponent.Instance.NewRepeatedTimer(checkInteral, self.Check); } } [ObjectSystem] public class SessionIdleCheckerComponentDestroySystem: DestroySystem<SessionIdleCheckerComponent> { public override void Destroy(SessionIdleCheckerComponent self) { TimerComponent.Instance.Remove(ref self.RepeatedTimer); } } public static class SessionIdleCheckerComponentSystem { public static void Check(this SessionIdleCheckerComponent self) { Session session = self.GetParent<Session>(); long timeNow = TimeHelper.ClientNow(); if (timeNow - session.LastRecvTime < 30 * 1000 && timeNow - session.LastSendTime < 30 * 1000) { return; } Log.Info($"session timeout: {session.Id} {timeNow} {session.LastRecvTime} {session.LastSendTime} {timeNow - session.LastRecvTime} {timeNow - session.LastSendTime}"); session.Error = ErrorCode.ERR_SessionSendOrRecvTimeout; session.Dispose(); } } }
35.487179
177
0.648121
[ "MIT" ]
1090504117/ET
Unity/Assets/Hotfix/Module/Message/SessionIdleCheckerComponentSystem.cs
1,384
C#
// // System.Runtime.InteropServices.RegistrationConnectionType // // Author: // Kazuki Oikawa (kazuki@panicode.com) // #if NET_2_0 using System; namespace System.Runtime.InteropServices { [Flags] public enum RegistrationConnectionType { MultipleUse = 1, MultiSeparate = 2, SingleUse = 0, Suspended = 4, Surrogate = 8 } } #endif
14.92
61
0.664879
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/corlib/System.Runtime.InteropServices/RegistrationConnectionType.cs
373
C#
using Sitecore.Foundation.Alerts.Models; namespace Sitecore.Foundation.Alerts { public class Constants { public const string InfoMessageView = "~/Views/Alerts/InfoMessage.cshtml"; } }
22.555556
79
0.729064
[ "Apache-2.0" ]
26384sunilrana/Habitat
src/Foundation/Alerts/code/Constants.cs
205
C#
using UnityEngine; using System.Collections; using UnityStandardAssets.CrossPlatformInput; public class HashIDsDragons : MonoBehaviour { [HideInInspector] public static int verticalHash = Animator.StringToHash("Vertical"); [HideInInspector] public static int horizontalHash = Animator.StringToHash("Horizontal"); [HideInInspector] public static int updownHash = Animator.StringToHash("UpDown"); [HideInInspector] public static int standHash = Animator.StringToHash("Stand"); [HideInInspector] public static int jumpHash = Animator.StringToHash("Jump"); [HideInInspector] public static int flyHash = Animator.StringToHash("Fly"); [HideInInspector] public static int dodgeHash = Animator.StringToHash("Dodge") ; [HideInInspector] public static int fallHash = Animator.StringToHash("Fall"); [HideInInspector] public static int groundedHash = Animator.StringToHash("Grounded"); [HideInInspector] public static int shiftHash = Animator.StringToHash("Shift"); [HideInInspector] public static int flySpeedHash = Animator.StringToHash("FlySpeed"); [HideInInspector] public static int attack1Hash = Animator.StringToHash("Attack1"); [HideInInspector] public static int attack2Hash = Animator.StringToHash("Attack2"); [HideInInspector] public static int deathHash = Animator.StringToHash("Death"); [HideInInspector] public static int injuredHash = Animator.StringToHash("Damaged"); [HideInInspector] public static int stunnedHash = Animator.StringToHash("Stunned"); [HideInInspector] public static int intDragonHash = Animator.StringToHash("DragoInt"); [HideInInspector] public static int floatDragonHash = Animator.StringToHash("DragoFloat"); [HideInInspector] public static int swimHash = Animator.StringToHash("Swim"); [HideInInspector] public static int underWaterHash = Animator.StringToHash("Underwater"); }
52.972973
97
0.745918
[ "MIT" ]
Shirai-Laboratory-2016-Kinect-EXPIXEL/Dragon_by_Kinect-EXPIXEL
Assets/Asset_Stores/Little Dragons/Common/Scripts/HashIDsDragons.cs
1,962
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace EmptyRecycleBin { class Program { enum RecycleFlags : uint { SHRB_NOCONFIRMATION = 0x00000001, SHRB_NOPROGRESSUI = 0x00000002, SHRB_NOSOUND = 0x00000004 } [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); static void Main(string[] args) { uint IsSuccess = SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlags.SHRB_NOCONFIRMATION); } } }
26.785714
101
0.64
[ "MIT" ]
DanielBence/Optimiser
EmptyRecycleBin/EmptyRecycleBin/Program.cs
752
C#
using System; using Chromium; using Neutronium.Core.WebBrowserEngine.Control; using Neutronium.Core.WebBrowserEngine.JavascriptObject; using Neutronium.Core.WebBrowserEngine.Window; using Neutronium.WPF.Internal; using Tests.Infra.WebBrowserEngineTesterHelper.Window; namespace Tests.ChromiumFX.Infra { internal class ChromiumFXHTMLWindowProvider : IWebBrowserWindowProvider { private readonly IWebView _Webview; private readonly CfxClient _CfxClient; public IDispatcher UiDispatcher => new WPFUIDispatcher(WpfThread.GetWpfThread().Dispatcher); public IWebBrowserWindow HtmlWindow { get; } event EventHandler<DebugEventArgs> IWebBrowserWindowProvider.DebugToolOpened { add { } remove { } } public event EventHandler OnDisposed; public ChromiumFXHTMLWindowProvider(CfxClient cfxClient, IWebView webview, Uri url) { _Webview = webview; _CfxClient = cfxClient; HtmlWindow = new FakeHTMLWindow(cfxClient, webview, url); } public void Show() { } public void Hide() { } public void Dispose() { OnDisposed?.Invoke(this, EventArgs.Empty); } public bool OnDebugToolsRequest() => false; public void CloseDebugTools() { } } }
28.914894
107
0.670346
[ "MIT" ]
simonbuehler/Neutronium
Tests/WebBrowserEngines/ChromiumFX/Tests.ChromiumFX.Infra/ChromiumFXHTMLWindowProvider.cs
1,361
C#
namespace ConfigWorker.Interfaces { public interface IStore { string Get(string name); void Set(string name, string value); } }
17.444444
44
0.630573
[ "MIT" ]
jbzorg/ConfigWorker
ConfigWorker/Interfaces/IStore.cs
159
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using UnityEngine.EventSystems; using System.Collections.Generic; using HoloToolkit.Unity.InputModule; namespace HoloToolkit.Unity.Receivers { /// <summary> /// An interaction receiver is simply a component that attached to a list of interactable objects and does something /// based on events from those interactable objects. This is the base abstract class to extend from. /// </summary> public abstract class InteractionReceiver : MonoBehaviour, IInputHandler, IHoldHandler, IInputClickHandler, IManipulationHandler { #region Public Members /// <summary> /// List of linked interactable objects to receive events for /// </summary> [Tooltip("Target interactable Object to receive events for")] public List<GameObject> interactables = new List<GameObject>(); /// <summary> /// List of linked targets that the receiver affects /// </summary> [Tooltip("Targets for the receiver to ")] public List<GameObject> Targets = new List<GameObject>(); /// <summary> /// Flag for locking focus while selected /// </summary> public bool LockFocus { get { return lockFocus; } set { lockFocus = value; CheckLockFocus(_selectingFocuser); } } #endregion #region Private and Protected Members [Tooltip("If true, this object will remain the prime focus while select is held")] [SerializeField] private bool lockFocus = false; /// <summary> /// Protected focuser for the current selecting focuser /// </summary> protected IPointingSource _selectingFocuser; #endregion /// <summary> /// On start subscribe to all interaction events on elements in the interactables list. /// </summary> public virtual void OnEnable() { InputManager.Instance.AddGlobalListener(gameObject); FocusManager.Instance.PointerSpecificFocusChanged += OnPointerSpecificFocusChanged; } /// <summary> /// On disable remove all linked interactables from the delegate functions /// </summary> public virtual void OnDisable() { if (InputManager.IsInitialized) { InputManager.Instance.RemoveGlobalListener(gameObject); } if (FocusManager.IsInitialized) { FocusManager.Instance.PointerSpecificFocusChanged -= OnPointerSpecificFocusChanged; } } /// <summary> /// Register an interactable with this receiver. /// </summary> /// <param name="interactable">takes a GameObject as the interactable to register.</param> public virtual void Registerinteractable(GameObject interactable) { if (interactable == null || interactables.Contains(interactable)) { return; } interactables.Add(interactable); } #if UNITY_EDITOR /// <summary> /// When selected draw lines to all linked interactables /// </summary> protected virtual void OnDrawGizmosSelected() { if (this.interactables.Count > 0) { GameObject[] bioList = this.interactables.ToArray(); for (int i = 0; i < bioList.Length; i++) { if (bioList[i] != null) { Gizmos.color = Color.green; Gizmos.DrawLine(this.transform.position, bioList[i].transform.position); } } } if (this.Targets.Count > 0) { GameObject[] targetList = this.Targets.ToArray(); for (int i = 0; i < targetList.Length; i++) { if (targetList[i] != null) { Gizmos.color = Color.red; Gizmos.DrawLine(this.transform.position, targetList[i].transform.position); } } } } #endif /// <summary> /// Function to remove an interactable from the linked list. /// </summary> /// <param name="interactable"></param> public virtual void Removeinteractable(GameObject interactable) { if (interactable != null && interactables.Contains(interactable)) { interactables.Remove(interactable); } } /// <summary> /// Clear the interactables list and unregister them /// </summary> public virtual void Clearinteractables() { GameObject[] _intList = interactables.ToArray(); for (int i = 0; i < _intList.Length; i++) { this.Removeinteractable(_intList[i]); } } /// <summary> /// Is the game object interactable in our list of interactables /// </summary> /// <param name="interactable"></param> /// <returns></returns> protected bool Isinteractable(GameObject interactable) { return (interactables != null && interactables.Contains(interactable)); } private void CheckLockFocus(IPointingSource focuser) { // If our previous selecting focuser isn't the same if (_selectingFocuser != null && _selectingFocuser != focuser) { // If our focus is currently locked, unlock it before moving on if (LockFocus) { _selectingFocuser.FocusLocked = false; } } // Set to the new focuser _selectingFocuser = focuser; if (_selectingFocuser != null) { _selectingFocuser.FocusLocked = LockFocus; } } private void LockFocuser(IPointingSource focuser) { if (focuser != null) { ReleaseFocuser(); _selectingFocuser = focuser; _selectingFocuser.FocusLocked = true; } } private void ReleaseFocuser() { if (_selectingFocuser != null) { _selectingFocuser.FocusLocked = false; _selectingFocuser = null; } } /// <summary> /// Handle the pointer specific changes to fire focus enter and exit events /// </summary> /// <param name="pointer">The pointer associated with this focus change.</param> /// <param name="oldFocusedObject">Object that was previously being focused.</param> /// <param name="newFocusedObject">New object being focused.</param> private void OnPointerSpecificFocusChanged(IPointingSource pointer, GameObject oldFocusedObject, GameObject newFocusedObject) { PointerSpecificEventData eventData = new PointerSpecificEventData(EventSystem.current); eventData.Initialize(pointer); if (newFocusedObject != null && Isinteractable(newFocusedObject)) { FocusEnter(newFocusedObject, eventData); } if (oldFocusedObject != null && Isinteractable(oldFocusedObject)) { FocusExit(oldFocusedObject, eventData); } CheckLockFocus(pointer); } #region Global Listener Callbacks public void OnInputDown(InputEventData eventData) { if (Isinteractable(eventData.selectedObject)) { InputDown(eventData.selectedObject, eventData); } } public void OnInputUp(InputEventData eventData) { if (Isinteractable(eventData.selectedObject)) { InputUp(eventData.selectedObject, eventData); } } public void OnInputClicked(InputClickedEventData eventData) { if (Isinteractable(eventData.selectedObject)) { InputClicked(eventData.selectedObject, eventData); } } public void OnHoldStarted(HoldEventData eventData) { if (Isinteractable(eventData.selectedObject)) { HoldStarted(eventData.selectedObject, eventData); } } public void OnHoldCompleted(HoldEventData eventData) { if (Isinteractable(eventData.selectedObject)) { HoldCompleted(eventData.selectedObject, eventData); } } public void OnHoldCanceled(HoldEventData eventData) { if (Isinteractable(eventData.selectedObject)) { HoldCanceled(eventData.selectedObject, eventData); } } public void OnManipulationStarted(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationStarted(eventData.selectedObject, eventData); } } public void OnManipulationUpdated(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationUpdated(eventData.selectedObject, eventData); } } public void OnManipulationCompleted(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationCompleted(eventData.selectedObject, eventData); } } public void OnManipulationCanceled(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationCanceled(eventData.selectedObject, eventData); } } public void OnNavigationStarted(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationStarted(eventData.selectedObject, eventData); } } public void OnNavigationUpdated(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationUpdated(eventData.selectedObject, eventData); } } public void OnNavigationCompleted(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationCompleted(eventData.selectedObject, eventData); } } public void OnNavigationCanceled(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationCanceled(eventData.selectedObject, eventData); } } #endregion #region Protected Virtual Callback Functions protected virtual void FocusEnter(GameObject obj, PointerSpecificEventData eventData) { } protected virtual void FocusExit(GameObject obj, PointerSpecificEventData eventData) { } protected virtual void InputDown(GameObject obj, InputEventData eventData) { } protected virtual void InputUp(GameObject obj, InputEventData eventData) { } protected virtual void InputClicked(GameObject obj, InputClickedEventData eventData) { } protected virtual void HoldStarted(GameObject obj, HoldEventData eventData) { } protected virtual void HoldCompleted(GameObject obj, HoldEventData eventData) { } protected virtual void HoldCanceled(GameObject obj, HoldEventData eventData) { } protected virtual void ManipulationStarted(GameObject obj, ManipulationEventData eventData) { } protected virtual void ManipulationUpdated(GameObject obj, ManipulationEventData eventData) { } protected virtual void ManipulationCompleted(GameObject obj, ManipulationEventData eventData) { } protected virtual void ManipulationCanceled(GameObject obj, ManipulationEventData eventData) { } protected virtual void NavigationStarted(GameObject obj, NavigationEventData eventData) { } protected virtual void NavigationUpdated(GameObject obj, NavigationEventData eventData) { } protected virtual void NavigationCompleted(GameObject obj, NavigationEventData eventData) { } protected virtual void NavigationCanceled(GameObject obj, NavigationEventData eventData) { } #endregion } }
36.008086
134
0.569429
[ "MIT" ]
Chalghouma/holocare
Assets/HoloToolkit/UX/Scripts/Receivers/InteractionReceiver.cs
13,359
C#
namespace ClassLib082 { public class Class092 { public static string Property => "ClassLib082"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib082/Class092.cs
120
C#
// <copyright file="GreyscaleBt601.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageProcessorCore.Filters { using System.Numerics; /// <summary> /// Converts the colors of the image to greyscale applying the formula as specified by /// ITU-R Recommendation BT.601 <see href="https://en.wikipedia.org/wiki/Luma_%28video%29#Rec._601_luma_versus_Rec._709_luma_coefficients"/>. /// </summary> public class GreyscaleBt601 : ColorMatrixFilter { /// <inheritdoc/> public override Matrix4x4 Matrix => new Matrix4x4() { M11 = .299f, M12 = .299f, M13 = .299f, M21 = .587f, M22 = .587f, M23 = .587f, M31 = .114f, M32 = .114f, M33 = .114f }; } }
30.064516
145
0.585837
[ "Apache-2.0" ]
SeanKilleen/ImageProcessor
src/ImageProcessorCore/Filters/ColorMatrix/GreyscaleBt601.cs
934
C#
using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace KyoshinEewViewer.Series.Radar { public partial class RadarView : UserControl { public RadarView() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
15
45
0.729825
[ "MIT" ]
ingen084/KyoshinEewViewerIngen
src/KyoshinEewViewer/Series/Radar/RadarView.axaml.cs
285
C#
using System.Collections.Generic; using BlogModule.Domain.Common; namespace BlogModule.Domain.Entities { public class Category : AuditableBaseEntity { public Category() { SubCategories = new HashSet<Category>(); } public string Name { get; set; } public string Description { get; set; } public int? ParentId { get; set; } public Category Parent { get; set; } public virtual ICollection<Category> SubCategories { get; set; } } }
25.95
72
0.622351
[ "MIT" ]
mrgrayhat/CleanMicroserviceArchitecture
src/MicroServices/Blog/Core/BlogModule.Domain/Entities/Category.cs
521
C#
using ApiApproverTests.Examples; using Xunit; namespace ApiApproverTests { public class Method_modifiers : ApiGeneratorTestsBase { [Fact] public void Should_output_static_modifier() { AssertPublicApi<ClassWithStaticMethod>( @"namespace ApiApproverTests.Examples { public class ClassWithStaticMethod { public ClassWithStaticMethod() { } public static void DoSomething() { } } }"); } [Fact] public void Should_output_abstract_modifier() { AssertPublicApi<ClassWithAbstractMethod>( @"namespace ApiApproverTests.Examples { public abstract class ClassWithAbstractMethod { protected ClassWithAbstractMethod() { } public abstract void DoSomething(); } }"); } [Fact] public void Should_output_virtual_modifier() { AssertPublicApi<ClassWithVirtualMethod>( @"namespace ApiApproverTests.Examples { public class ClassWithVirtualMethod { public ClassWithVirtualMethod() { } public virtual void DoSomething() { } } }"); } [Fact] public void Should_output_override_modifier() { AssertPublicApi<ClassWithOverridingMethod>( @"namespace ApiApproverTests.Examples { public class ClassWithOverridingMethod : ApiApproverTests.Examples.ClassWithVirtualMethod { public ClassWithOverridingMethod() { } public override void DoSomething() { } } }"); } [Fact] public void Should_allow_overriding_object_methods() { AssertPublicApi<ClassWithMethodOverridingObjectMethod>( @"namespace ApiApproverTests.Examples { public class ClassWithMethodOverridingObjectMethod { public ClassWithMethodOverridingObjectMethod() { } public override string ToString() { } } }"); } [Fact] public void Should_output_new_modifier() { AssertPublicApi<ClassWithMethodHiding>( @"namespace ApiApproverTests.Examples { public class ClassWithMethodHiding : ApiApproverTests.Examples.ClassWithSimpleMethod { public ClassWithMethodHiding() { } public new void Method() { } } }"); } } // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMemberHiearchy.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable RedundantOverridenMember // ReSharper disable ClassWithVirtualMembersNeverInherited.Global namespace Examples { public class ClassWithStaticMethod { public static void DoSomething() { } } public class ClassWithSimpleMethod { public void Method() { } } public class ClassWithMethodHiding : ClassWithSimpleMethod { public new void Method() { } } public abstract class ClassWithAbstractMethod { public abstract void DoSomething(); } public class ClassWithVirtualMethod { public virtual void DoSomething() { } } public class ClassWithOverridingMethod : ClassWithVirtualMethod { public override void DoSomething() { base.DoSomething(); } } public class ClassWithMethodOverridingObjectMethod { public override string ToString() { return base.ToString(); } } } // ReSharper restore ClassWithVirtualMembersNeverInherited.Global // ReSharper restore RedundantOverridenMember // ReSharper restore MemberCanBeProtected.Global // ReSharper restore UnusedMemberHiearchy.Global // ReSharper restore UnusedMember.Global // ReSharper restore ClassNeverInstantiated.Global }
25.884615
93
0.625557
[ "MIT" ]
heynickc/ApiApprover
src/ApiApproverTests/Method_modifiers.cs
4,040
C#
using System; namespace UnityEngine.PostProcessing { [Serializable] public class GrainModel : PostProcessingModel { [Serializable] public struct Settings { [Tooltip("Enable the use of colored grain.")] public bool colored; [Range(0f, 1f), Tooltip("Grain strength. Higher means more visible grain.")] public float intensity; [Range(0.3f, 3f), Tooltip("Grain particle size.")] public float size; [Range(0f, 1f), Tooltip("Controls the noisiness response curve based on scene luminance. Lower values mean less noise in dark areas.")] public float luminanceContribution; public static Settings defaultSettings { get { return new Settings { colored = true, intensity = 0.5f, size = 1f, luminanceContribution = 0.8f }; } } } [SerializeField] Settings m_Settings = Settings.defaultSettings; public Settings settings { get { return m_Settings; } set { m_Settings = value; } } public override void Reset() { m_Settings = Settings.defaultSettings; } } }
28.557692
148
0.484175
[ "Apache-2.0" ]
Aasish-Virjala/StressLessFinal
PostProcessing/Runtime/Models/GrainModel.cs
1,485
C#
using IBank.Dtos.Transaction; using IBank.Exceptions; using IBank.Services.Token; using IBank.Services.Transaction; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace IBank.Controllers { [Authorize] [ApiController] [Route("api/v1/transactions")] public class TransactionController : ControllerBase { private readonly ITokenService _tokenService; private readonly ITransactionService _transactionService; public TransactionController( ITokenService tokenService, ITransactionService transactionService ) { _tokenService = tokenService; _transactionService = transactionService; } [HttpGet] public async Task<ActionResult<IEnumerable<ReturnListTransactionDto>>> List([FromQuery] ListTransactionDto range) { var id = long.Parse(_tokenService.GetIdFromToken(User)); var list = await _transactionService.List(id, range); return Ok(list); } [AllowAnonymous] [HttpPost] [Route("deposit")] public async Task<ActionResult<ReturnTransactionDto>> Deposit(DepositTransactionDto deposit) { try { var transaction = await _transactionService.Deposit(deposit); return CreatedAtAction("List", transaction); } catch (AccountNotFoundException e) { return NotFound(new { e.Message }); } } [HttpPost] [Route("withdraw")] public async Task<ActionResult<ReturnTransactionDto>> Withdraw(WithdrawTransactionDto withdraw) { try { var id = long.Parse(_tokenService.GetIdFromToken(User)); var transaction = await _transactionService.Withdraw(id, withdraw); return CreatedAtAction("List", transaction); } catch (InsufficientBalanceException e) { return StatusCode(StatusCodes.Status403Forbidden, new { e.Message }); } } [HttpPost] [Route("transfer")] public async Task<ActionResult<ReturnTransactionDto>> Transfer(TransferTransactionDto transfer) { try { var id = long.Parse(_tokenService.GetIdFromToken(User)); var transaction = await _transactionService.Transfer(id, transfer); return CreatedAtAction("List", transaction); } catch (AccountNotFoundException e) { return NotFound(new { e.Message }); } catch (InvalidOperationException e) { return BadRequest(new { e.Message }); } catch (InsufficientBalanceException e) { return StatusCode(StatusCodes.Status403Forbidden, new { e.Message }); } } } }
32.635417
121
0.595276
[ "MIT" ]
9Rain/donus-code-challenge
IBank/Controllers/TransactionController.cs
3,135
C#
// // ExtensionTree.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // 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.Collections; using System.Reflection; using System.Xml; using Mono.Addins.Description; using System.Collections.Generic; namespace Mono.Addins { internal class ExtensionTree: TreeNode { int internalId; internal const string AutoIdPrefix = "__nid_"; ExtensionContext context; public ExtensionTree (AddinEngine addinEngine, ExtensionContext context): base (addinEngine, "") { this.context = context; } public override ExtensionContext Context { get { return context; } } public void LoadExtension (string addin, Extension extension, ArrayList addedNodes) { TreeNode tnode = GetNode (extension.Path); if (tnode == null) { addinEngine.ReportError ("Can't load extensions for path '" + extension.Path + "'. Extension point not defined.", addin, null, false); return; } int curPos = -1; LoadExtensionElement (tnode, addin, extension.ExtensionNodes, (ModuleDescription) extension.Parent, ref curPos, tnode.Condition, false, addedNodes); } void LoadExtensionElement (TreeNode tnode, string addin, ExtensionNodeDescriptionCollection extension, ModuleDescription module, ref int curPos, BaseCondition parentCondition, bool inComplextCondition, ArrayList addedNodes) { foreach (ExtensionNodeDescription elem in extension) { if (inComplextCondition) { parentCondition = ReadComplexCondition (elem, parentCondition); inComplextCondition = false; continue; } if (elem.NodeName == "ComplexCondition") { LoadExtensionElement (tnode, addin, elem.ChildNodes, module, ref curPos, parentCondition, true, addedNodes); continue; } if (elem.NodeName == "Condition") { Condition cond = new Condition (AddinEngine, elem, parentCondition); LoadExtensionElement (tnode, addin, elem.ChildNodes, module, ref curPos, cond, false, addedNodes); continue; } var pnode = tnode; ExtensionPoint extensionPoint = null; while (pnode != null && (extensionPoint = pnode.ExtensionPoint) == null) pnode = pnode.Parent; string after = elem.GetAttribute ("insertafter"); if (after.Length == 0 && extensionPoint != null && curPos == -1) after = extensionPoint.DefaultInsertAfter; if (after.Length > 0) { int i = tnode.Children.IndexOfNode (after); if (i != -1) curPos = i+1; } string before = elem.GetAttribute ("insertbefore"); if (before.Length == 0 && extensionPoint != null && curPos == -1) before = extensionPoint.DefaultInsertBefore; if (before.Length > 0) { int i = tnode.Children.IndexOfNode (before); if (i != -1) curPos = i; } // If node position is not explicitly set, add the node at the end if (curPos == -1) curPos = tnode.Children.Count; // Find the type of the node in this extension ExtensionNodeType ntype = addinEngine.FindType (tnode.ExtensionNodeSet, elem.NodeName, addin); if (ntype == null) { addinEngine.ReportError ("Node '" + elem.NodeName + "' not allowed in extension: " + tnode.GetPath (), addin, null, false); continue; } string id = elem.GetAttribute ("id"); if (id.Length == 0) id = AutoIdPrefix + (++internalId); TreeNode cnode = new TreeNode (addinEngine, id); ExtensionNode enode = ReadNode (cnode, addin, ntype, elem, module); if (enode == null) continue; cnode.Condition = parentCondition; cnode.ExtensionNodeSet = ntype; tnode.InsertChildNode (curPos, cnode); addedNodes.Add (cnode); if (cnode.Condition != null) Context.RegisterNodeCondition (cnode, cnode.Condition); // Load children if (elem.ChildNodes.Count > 0) { int cp = 0; LoadExtensionElement (cnode, addin, elem.ChildNodes, module, ref cp, parentCondition, false, addedNodes); } curPos++; } if (Context.FireEvents) tnode.NotifyChildrenChanged (); } BaseCondition ReadComplexCondition (ExtensionNodeDescription elem, BaseCondition parentCondition) { if (elem.NodeName == "Or" || elem.NodeName == "And" || elem.NodeName == "Not") { ArrayList conds = new ArrayList (); foreach (ExtensionNodeDescription celem in elem.ChildNodes) { conds.Add (ReadComplexCondition (celem, null)); } if (elem.NodeName == "Or") return new OrCondition ((BaseCondition[]) conds.ToArray (typeof(BaseCondition)), parentCondition); else if (elem.NodeName == "And") return new AndCondition ((BaseCondition[]) conds.ToArray (typeof(BaseCondition)), parentCondition); else { if (conds.Count != 1) { addinEngine.ReportError ("Invalid complex condition element '" + elem.NodeName + "'. 'Not' condition can only have one parameter.", null, null, false); return new NullCondition (); } return new NotCondition ((BaseCondition) conds [0], parentCondition); } } if (elem.NodeName == "Condition") { return new Condition (AddinEngine, elem, parentCondition); } addinEngine.ReportError ("Invalid complex condition element '" + elem.NodeName + "'.", null, null, false); return new NullCondition (); } public ExtensionNode ReadNode (TreeNode tnode, string addin, ExtensionNodeType ntype, ExtensionNodeDescription elem, ModuleDescription module) { try { if (ntype.Type == null) { if (!InitializeNodeType (ntype)) return null; } ExtensionNode node; node = Activator.CreateInstance (ntype.Type) as ExtensionNode; if (node == null) { addinEngine.ReportError ("Extension node type '" + ntype.Type + "' must be a subclass of ExtensionNode", addin, null, false); return null; } tnode.AttachExtensionNode (node); node.SetData (addinEngine, addin, ntype, module); node.Read (elem); return node; } catch (Exception ex) { addinEngine.ReportError ("Could not read extension node of type '" + ntype.Type + "' from extension path '" + tnode.GetPath() + "'", addin, ex, false); return null; } } bool InitializeNodeType (ExtensionNodeType ntype) { RuntimeAddin p = addinEngine.GetAddin (ntype.AddinId); if (p == null) { if (!addinEngine.IsAddinLoaded (ntype.AddinId)) { if (!addinEngine.LoadAddin (null, ntype.AddinId, false)) return false; p = addinEngine.GetAddin (ntype.AddinId); if (p == null) { addinEngine.ReportError ("Add-in not found", ntype.AddinId, null, false); return false; } } } // If no type name is provided, use TypeExtensionNode by default if (ntype.TypeName == null || ntype.TypeName.Length == 0 || ntype.TypeName == typeof(TypeExtensionNode).FullName) { // If it has a custom attribute, use the generic version of TypeExtensionNode if (ntype.ExtensionAttributeTypeName.Length > 0) { Type attType = p.GetType (ntype.ExtensionAttributeTypeName, false); if (attType == null) { addinEngine.ReportError ("Custom attribute type '" + ntype.ExtensionAttributeTypeName + "' not found.", ntype.AddinId, null, false); return false; } if (ntype.ObjectTypeName.Length > 0 || ntype.TypeName == typeof(TypeExtensionNode).FullName) ntype.Type = typeof(TypeExtensionNode<>).MakeGenericType (attType); else ntype.Type = typeof(ExtensionNode<>).MakeGenericType (attType); } else { ntype.Type = typeof(TypeExtensionNode); return true; } } else { ntype.Type = p.GetType (ntype.TypeName, false); if (ntype.Type == null) { addinEngine.ReportError ("Extension node type '" + ntype.TypeName + "' not found.", ntype.AddinId, null, false); return false; } } // Check if the type has NodeAttribute attributes applied to fields. ExtensionNodeType.FieldData boundAttributeType = null; Dictionary<string,ExtensionNodeType.FieldData> fields = GetMembersMap (ntype.Type, out boundAttributeType); ntype.CustomAttributeMember = boundAttributeType; if (fields.Count > 0) ntype.Fields = fields; // If the node type is bound to a custom attribute and there is a member bound to that attribute, // get the member map for the attribute. if (boundAttributeType != null) { if (ntype.ExtensionAttributeTypeName.Length == 0) throw new InvalidOperationException ("Extension node not bound to a custom attribute."); if (ntype.ExtensionAttributeTypeName != boundAttributeType.MemberType.FullName) throw new InvalidOperationException ("Incorrect custom attribute type declaration in " + ntype.Type + ". Expected '" + ntype.ExtensionAttributeTypeName + "' found '" + boundAttributeType.MemberType.FullName + "'"); fields = GetMembersMap (boundAttributeType.MemberType, out boundAttributeType); if (fields.Count > 0) ntype.CustomAttributeFields = fields; } return true; } Dictionary<string,ExtensionNodeType.FieldData> GetMembersMap (Type type, out ExtensionNodeType.FieldData boundAttributeType) { string fname; Dictionary<string,ExtensionNodeType.FieldData> fields = new Dictionary<string, ExtensionNodeType.FieldData> (); boundAttributeType = null; while (type != typeof(object) && type != null) { foreach (FieldInfo field in type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { NodeAttributeAttribute at = (NodeAttributeAttribute) Attribute.GetCustomAttribute (field, typeof(NodeAttributeAttribute), true); if (at != null) { ExtensionNodeType.FieldData fd = CreateFieldData (field, at, out fname, ref boundAttributeType); if (fd != null) fields [fname] = fd; } } foreach (PropertyInfo prop in type.GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { NodeAttributeAttribute at = (NodeAttributeAttribute) Attribute.GetCustomAttribute (prop, typeof(NodeAttributeAttribute), true); if (at != null) { ExtensionNodeType.FieldData fd = CreateFieldData (prop, at, out fname, ref boundAttributeType); if (fd != null) fields [fname] = fd; } } type = type.BaseType; } return fields; } ExtensionNodeType.FieldData CreateFieldData (MemberInfo member, NodeAttributeAttribute at, out string name, ref ExtensionNodeType.FieldData boundAttributeType) { ExtensionNodeType.FieldData fdata = new ExtensionNodeType.FieldData (); fdata.Member = member; fdata.Required = at.Required; fdata.Localizable = at.Localizable; if (at.Name != null && at.Name.Length > 0) name = at.Name; else name = member.Name; if (typeof(CustomExtensionAttribute).IsAssignableFrom (fdata.MemberType)) { if (boundAttributeType != null) throw new InvalidOperationException ("Type '" + member.DeclaringType + "' has two members bound to a custom attribute. There can be only one."); boundAttributeType = fdata; return null; } return fdata; } } }
38.134375
225
0.692371
[ "MIT" ]
doc22940/mono-addins
Mono.Addins/Mono.Addins/ExtensionTree.cs
12,203
C#
using System; using System.ComponentModel.DataAnnotations; namespace UpsMo.Common.DTO.Request.Organization { public class ManagerCreateRequest : BaseManager { /// <summary> /// will be manager user email or username /// </summary> [Required] public string Identifier { get; set; } } }
25
52
0.62
[ "Unlicense" ]
halilkocaoz/upmo-server
UpsMo.Common/DTO/Request/Organization/ManagerCreateRequest.cs
350
C#
using Microsoft.Extensions.Configuration; using pote.Config.Shared; namespace pote.Config.Middleware; public static class ExtensionMethods { public static async Task<IConfigurationBuilder> AddConfigurationFromApi(this IConfigurationBuilder builder, BuilderConfiguration configuration, string inputJson, Action<string, Exception> errorOutput = null!) { var parsedJsonFile = Path.Combine(configuration.WorkingDirectory, $"appsettings.{configuration.Environment}.Parsed.json"); try { var apiCommunication = new ApiCommunication(configuration.ApiUri); var response = await apiCommunication.GetConfiguration(new ParseRequest(configuration.Application, configuration.Environment, inputJson)); if (response == null) throw new InvalidDataException("Reponse from API was empty."); var json = response.GetJson(); await File.WriteAllTextAsync(parsedJsonFile, json); return builder.AddJsonFile(parsedJsonFile, false, false); } catch (Exception ex) { errorOutput("Error getting configuration from API. Loading previously parsed configuration.", ex); return builder.AddPreviouslyParsedConfiguration(parsedJsonFile); } } private static IConfigurationBuilder AddPreviouslyParsedConfiguration(this IConfigurationBuilder builder, string file) { if (!File.Exists(file)) throw new FileNotFoundException($"An old parsed configuration not found, file: {file}"); return builder.AddJsonFile(file, false, true); } }
48.545455
212
0.71598
[ "MIT" ]
poteb/ConfigurationService
src/Config.Middleware/Config.Middleware.NetStandard20/ExtensionMethods.cs
1,602
C#
// Copyright (c) 2017 Jan Pluskal // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Castle.MicroKernel.Registration; using Netfox.AppIdent; using Netfox.NetfoxFrameworkAPI.Tests; using Netfox.NetfoxFrameworkAPI.Tests.Properties; using NUnit.Framework; namespace Spid.Tests { /// <summary> An application recognizer spid tests.</summary> [TestFixture] public class ApplicationRecognizerSPIDTests : FrameworkBaseTests { /// <summary> The test start Date/Time.</summary> private static DateTime _testStart; [OneTimeSetUp] public void SetUp() { base.SetUpInMemory(); this.WindsorContainer.Register(Component.For<ApplicationRecognizerSpid>()); } [Test][Ignore("Debugging test")] public void DumpTestSpid() { var csv = new StringBuilder(); this.FrameworkController.ProcessCapture(this.PrepareCaptureForProcessing(SnoopersPcaps.Default.pcap_mix_root_cz_cap)); var conversations = this.L7Conversations.ToArray(); csv.AppendLine(string.Format(this.PmCaptures.First().FileInfo.FullName) + "\n\n"); var spid = this.WindsorContainer.Resolve<ApplicationRecognizerSpid>(); foreach(var conv in conversations) { spid.UpdateModelForProtocol(conv); } this.FrameworkController.ProcessCapture(this.PrepareCaptureForProcessing(Pcaps.Default.pcap_mix_root_cz_cap)); conversations = this.L7Conversations.ToArray(); csv.AppendLine(string.Format(this.PmCaptures.First().FileInfo.FullName) + "\n\n"); var measure = new Dictionary<string, Array>(); var unknown = 0; foreach(var conv in conversations) { var appTag = conv.AppTag; if(appTag == null) { continue; } var tmpRet = spid.RecognizeConversation2(conv); if(tmpRet == null) { unknown++; continue; } var line = string.Format(conv.SourceEndPoint + " " + conv.DestinationEndPoint + ";" + appTag + ";" + tmpRet); Console.WriteLine(line); csv.AppendLine(line); if(!measure.ContainsKey(tmpRet)) { measure.Add(tmpRet, new[] { 0, 0, 0 }); } if(!measure.ContainsKey(appTag)) { measure.Add(appTag, new[] { 0, 0, 0 }); } if(appTag == tmpRet) { //TP measure[tmpRet].SetValue((int) measure[tmpRet].GetValue(0) + 1, 0); } else if(appTag != tmpRet) { //FP measure[tmpRet].SetValue((int) measure[tmpRet].GetValue(2) + 1, 2); //FN measure[appTag].SetValue((int) measure[appTag].GetValue(1) + 1, 1); } } var unk = string.Format("\n" + "Unknown " + unknown); csv.AppendLine(unk); Console.WriteLine(unk); foreach(var tag in measure) { var line = string.Format("\n" + tag.Key + " TP: " + tag.Value.GetValue(0) + " FP: " + tag.Value.GetValue(2) + " FN: " + tag.Value.GetValue(1)); Console.WriteLine(line); csv.AppendLine(line); line = string.Format("Precision: " + Utilities.Precission((int) tag.Value.GetValue(0), (int) tag.Value.GetValue(2))); Console.WriteLine(line); csv.AppendLine(line); line = string.Format("Recall: " + Utilities.Recall((int) tag.Value.GetValue(0), (int) tag.Value.GetValue(0) + (int) tag.Value.GetValue(1))); Console.WriteLine(line); csv.AppendLine(line); line = string.Format("F-Measure: " + Utilities.F_Measure((int) tag.Value.GetValue(0), (int) tag.Value.GetValue(2), (int) tag.Value.GetValue(0) + (int) tag.Value.GetValue(1))); Console.WriteLine(line); csv.AppendLine(line); //Console.WriteLine("\n" + tag.Key + " TP: " + tag.Value.GetValue(0) + " FP: " + tag.Value.GetValue(2) + " FN: " + tag.Value.GetValue(1)); //Console.WriteLine("Precision: " + this.Precission((int)tag.Value.GetValue(0), (int)tag.Value.GetValue(2))); //Console.WriteLine("Recall: " + this.Recall((int)tag.Value.GetValue(0), (int)tag.Value.GetValue(0) + (int)tag.Value.GetValue(1))); //Console.WriteLine("F-Measure: " + this.F_Measure((int)tag.Value.GetValue(0), (int)tag.Value.GetValue(2), (int)tag.Value.GetValue(0) + (int)tag.Value.GetValue(1))); } //File.AppendAllText("X:\\DPtest\\SPID.csv", csv.ToString()); } /// <summary> Tests application recognizer spid.</summary> //[SetUp] //public void ApplicationRecognizerSPIDTest() { this.recognizer = new ApplicationRecognizerSpid(); } // <summary> Tests recognize conversation fast.</summary> //[Test] //public void RecognizeConversationFastTest() //{ //TestStart(); //var path = Pcaps.Default.pcap_mix_imap_smtp_collector_pcap; //@"..\..\..\TestingData\pcap_mix\http.cap"; // //var captureProcessor = new Capture(path); //captureProcessor.TrackConversations(); //Console.WriteLine("Conversations> " + captureProcessor.GetConversations().Count()); //var captureProcessorSPID = new Capture(path); //captureProcessorSPID.TrackConversations(this.recognizer); //var convsSPID = captureProcessorSPID.GetConversations(); ////Debug.Assert(convsSPID != null, "convs != null"); //var ctConversationValues = convsSPID as CsConversationValue[] ?? convsSPID.ToArray(); //var HTTP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.http)); //var ICQ = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.icq)); //var YMSG = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.ymsg)); //var MSN = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.msn)); //var XMPP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.xmpp)); //var POP3 = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.pop3)); //var IMAP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.imap)); //var SMTP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.smtp)); //var DNS = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.dns)); //var portAppTags = (from conv in captureProcessor.GetConversations() // select conv).GroupBy(conv => conv.ApplicationTags); //var SPIDAppTags = (from conv in convsSPID // select conv).GroupBy(conv => conv.ApplicationTags); //var appTags = portAppTags as IGrouping<string, CsConversationValue>[] ?? portAppTags.ToArray(); //var spidAppTags = SPIDAppTags as IGrouping<string, CsConversationValue>[] ?? SPIDAppTags.ToArray(); //foreach (var appstag in (appTags.Concat(spidAppTags)).GroupBy(i=>i.Key)) //{ // var port = appTags.Where(i => i.Key == appstag.Key); // var spid = spidAppTags.Where(i => i.Key == appstag.Key); // int ports =0; // int spids=0; // if (port.Any()) // ports = port.First().Count(); // if (spid.Any()) // spids = spid.First().Count(); // Console.WriteLine("{0}, port> {1}, SPID> {2}", appstag.Key, ports, spids); //} //TestStop(); //Assert.IsTrue(HTTP == 0 && ICQ == 0 && YMSG == 0 && MSN == 0 && XMPP == 0 && POP3 == 0 && IMAP == 7 && SMTP == 22 && DNS == 11); //} //[Test] //[Category("LongRunning")] //public void RecognizeConversationTest() //{ // TestStart(); // var path = Pcaps.Default.pcap_mix_mix_pcap; // var captureProcessor = new Capture(path); // captureProcessor.TrackConversations(); // Console.WriteLine("Conversations> " + captureProcessor.GetConversations().Count()); // var captureProcessorSPID = new Capture(path); // captureProcessorSPID.TrackConversations(this.recognizer); // var convsSPID = captureProcessorSPID.GetConversations(); // Debug.Assert(convsSPID != null, "convs != null"); // var ctConversationValues = convsSPID as CsConversationValue[] ?? convsSPID.ToArray(); // var HTTP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.http)); // var ICQ = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.icq)); // var YMSG = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.ymsg)); // var MSN = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.msn)); // var XMPP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.xmpp)); // var POP3 = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.pop3)); // var IMAP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.imap)); // var SMTP = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.smtp)); // var DNS = ctConversationValues.Count(c => c.isXYProtocolConversation(NBARprotocols.Default.dns)); // //var portAppTags = (from conv in captureProcessor.GetConversations() // // select conv).GroupBy(conv => conv.ApplicationTags); // //var SPIDAppTags = (from conv in convsSPID // // select conv).GroupBy(conv => conv.ApplicationTags); // //var appTags = portAppTags as IGrouping<string, CsConversationValue>[] ?? portAppTags.ToArray(); // //var spidAppTags = SPIDAppTags as IGrouping<string, CsConversationValue>[] ?? SPIDAppTags.ToArray(); // //foreach (var appstag in (appTags.Concat(spidAppTags)).GroupBy(i => i.Key)) // //{ // // var port = appTags.Where(i => i.Key == appstag.Key); // // var spid = spidAppTags.Where(i => i.Key == appstag.Key); // // int ports = 0; // // int spids = 0; // // if (port.Any()) // // ports = port.First().Count(); // // if (spid.Any()) // // spids = spid.First().Count(); // // Console.WriteLine("{0}, port> {1}, SPID> {2}", appstag.Key, ports, spids); // //} // TestStop(); // Assert.IsTrue(HTTP == 3176 && ICQ == 0 && YMSG == 0 && MSN == 3 && XMPP == 0 && POP3 == 0 && IMAP == 21 && SMTP == 23 && DNS == 2852); //} /// <summary> Tests recognize conversation.</summary> /// <summary> Tests start.</summary> private static void TestStart() { _testStart = DateTime.Now; } /// <summary> Tests stop.</summary> private static void TestStop() { var testStop = DateTime.Now; var duration = testStop - _testStart; Console.WriteLine("Timeduration: " + duration.Hours + ":" + duration.Minutes + ":" + duration.Seconds + "." + duration.Milliseconds); } } }
46.569343
181
0.576646
[ "Apache-2.0" ]
mvondracek/NetfoxDetective
Framework/ApplicationRecognizers/Spid.Tests/ApplicationRecognizerSPIDTests.cs
12,762
C#
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.CosmosDB.BulkExecutor.Graph.Element; using Octogami.SixDegreesOfNetflix.Application.Infrastructure.Configuration; using Octogami.SixDegreesOfNetflix.Application.Infrastructure.Data; namespace Octogami.SixDegreesOfNetflix.Application.Feature.LoadRecords { public interface IActorInserter { Task InsertActorsAsync(IEnumerable<MovieAndActorRecord> records); } public class ActorInserter : IActorInserter { private readonly IBulkLoader _bulkLoader; private readonly GraphConfiguration _graphConfiguration; public ActorInserter(IBulkLoader bulkLoader, GraphConfiguration graphConfiguration) { _bulkLoader = bulkLoader; _graphConfiguration = graphConfiguration; } public async Task InsertActorsAsync(IEnumerable<MovieAndActorRecord> records) { var distinctActors = records .GroupBy(x => new { x.NameId, x.Actor, }).Select(group => group.First()); await _bulkLoader.BulkInsertAsync(distinctActors.Select(x => { var vertex = new GremlinVertex(x.NameId, "Actor"); vertex.AddProperty(_graphConfiguration.PartitionKey, x.Actor); vertex.AddProperty("Name", x.Actor); return vertex; }), CancellationToken.None); } } }
34.622222
91
0.657895
[ "MIT" ]
nelsonwellswku/SixDegreesOfNetflix
Application/Feature/LoadRecords/ActorInserter.cs
1,558
C#
 namespace EPI.Searching { /// <summary> /// Design an algorithm that checks whether a number appears in a 2D sorted array or not. /// A 2D array is considered sorted if all rows and columns are sorted. /// </summary> public static class Search2DSortedArray { public static bool Search(int[,] array, int valueToSearch) { int row = array.GetLength(0) - 1; int column = 0; while (row >= 0 && column < array.GetLength(1)) { if (array[row, column] == valueToSearch) { return true; } else if (array[row, column] < valueToSearch) { // value is not present in current column, increment column column++; } else { // value might be in current column, decrement row row--; } } return false; } } }
22.314286
90
0.619718
[ "MIT" ]
dipakboyed/epibook.github.io.Puzzles
EPIProblems/Searching/Search2DSortedArray.cs
783
C#
// // System.Runtime.InteropServices.ErrorWrapper.cs // // Author: // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // 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; namespace System.Runtime.InteropServices { #if NET_2_0 [Serializable] [ComVisible (true)] #endif public sealed class ErrorWrapper { int errorCode; public ErrorWrapper (Exception e) { this.errorCode = Marshal.GetHRForException (e); } public ErrorWrapper (int errorCode) { this.errorCode = errorCode; } public ErrorWrapper (object errorCode) { if (errorCode.GetType() != typeof(int)) throw new ArgumentException ("errorCode has to be an int type"); this.errorCode = (int)errorCode; } public int ErrorCode { get { return errorCode; } } } }
28.8
73
0.731838
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/corlib/System.Runtime.InteropServices/ErrorWrapper.cs
1,872
C#
using Beer.DaAPI.BlazorApp.Dialogs; using Microsoft.AspNetCore.Components; using MudBlazor; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static Beer.DaAPI.Shared.Responses.DHCPv6InterfaceResponses.V1; namespace Beer.DaAPI.BlazorApp.Pages.DHCPv6Interfaces { public partial class DeleteDHCPv6InterfaceDialog : DaAPIDialogBase { private Boolean _sendingInProgress = false; private Boolean _hasErrors = false; [Parameter] public ActiveDHCPv6InterfaceEntry Entry { get; set; } private async Task DeleteListener() { _sendingInProgress = true; _hasErrors = false; Boolean result = await _service.SendDeleteDHCPv6InterfaceRequest(Entry.SystemId); _sendingInProgress = false; if (result == true) { MudDialog.Close(DialogResult.Ok<Boolean>(result)); } else { _hasErrors = true; } } } }
27.684211
93
0.643536
[ "MIT" ]
just-the-benno/Beer
src/DaAPI/App/Beer.DaAPI.BlazorApp/Pages/DHCPv6Interfaces/DeleteDHCPv6InterfaceDialog.razor.cs
1,054
C#
using System.Web.Mvc; using System.Web.Routing; namespace _47Example { public static class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
26.263158
99
0.553106
[ "MIT" ]
getyoti/yoti-dotnet-sdk
src/Examples/Profile/47Example/App_Start/RouteConfig.cs
501
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 System; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; namespace osu.Game.Rulesets.Mods { public abstract class ModNoFail : ModBlockFail { public override string Name => "No Fail"; public override string Acronym => "NF"; public override IconUsage Icon => OsuIcon.ModNofail; public override ModType Type => ModType.DifficultyReduction; public override string Description => "You can't fail, no matter what."; public override double ScoreMultiplier => 0.5; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModRelax), typeof(ModSuddenDeath), typeof(ModAutoplay) }; } }
40.090909
124
0.68254
[ "MIT" ]
123tris/osu
osu.Game/Rulesets/Mods/ModNoFail.cs
861
C#
using System.Collections.Generic; using System.Linq; using NServiceBus.DeliveryConstraints; namespace NServiceBus.Extensions.DispatchRetries.AcceptanceTests.Transport.Helpers { internal static class DeliveryConstraintsExtensions { internal static bool TryGet<T>(this List<DeliveryConstraint> list, out T constraint) where T : DeliveryConstraint { constraint = list.OfType<T>().FirstOrDefault(); return constraint != null; } } }
30.625
121
0.716327
[ "Apache-2.0" ]
mauroservienti/NServiceBus.Extensions.DispatchRetries
src/NServiceBus.Extensions.DispatchRetries.AcceptanceTests/Transport/Helpers/DeliveryConstraintsExtensions.cs
492
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft 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.Reflection; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Common; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; namespace Microsoft.Azure.Commands.Batch.Test.ScenarioTests { public class CertificateTests : WindowsAzure.Commands.Test.Utilities.Common.RMTestBase { public CertificateTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); } [Fact] [Trait(Category.AcceptanceType, Category.Flaky)] public void TestCertificateCrudOperations() { BatchController.NewInstance.RunPsTest("Test-CertificateCrudOperations"); } [Fact] [Trait(Category.AcceptanceType, Category.Flaky)] public void TestCancelCertificateDelete() { BatchController controller = BatchController.NewInstance; BatchAccountContext context = null; string thumbprint = null; string poolId = "certPool"; controller.RunPsTestWorkflow( () => { return new string[] { string.Format("Test-TestCancelCertificateDelete '{0}' '{1}'", BatchTestHelpers.TestCertificateAlgorithm, thumbprint) }; }, () => { context = new ScenarioTestContext(); thumbprint = ScenarioTestHelpers.AddTestCertificate(controller, context, BatchTestHelpers.TestCertificateFileName); CertificateReference certRef = new CertificateReference(); certRef.StoreLocation = CertStoreLocation.CurrentUser; certRef.StoreName = "My"; certRef.ThumbprintAlgorithm = BatchTestHelpers.TestCertificateAlgorithm; certRef.Thumbprint = thumbprint; certRef.Visibility = CertificateVisibility.Task; ScenarioTestHelpers.CreateTestPool(controller, context, poolId, targetDedicated: 0, targetLowPriority: 0, certReference: certRef); ScenarioTestHelpers.DeleteTestCertificate(controller, context, BatchTestHelpers.TestCertificateAlgorithm, thumbprint); ScenarioTestHelpers.WaitForCertificateToFailDeletion(controller, context, BatchTestHelpers.TestCertificateAlgorithm, thumbprint); }, () => { ScenarioTestHelpers.DeletePool(controller, context, poolId); ScenarioTestHelpers.DeleteTestCertificate(controller, context, BatchTestHelpers.TestCertificateAlgorithm, thumbprint); }, MethodBase.GetCurrentMethod().ReflectedType?.ToString(), MethodBase.GetCurrentMethod().Name); } } }
52
169
0.632178
[ "MIT" ]
Philippe-Morin/azure-powershell
src/ResourceManager/AzureBatch/Commands.Batch.Test/ScenarioTests/CertificateTests.cs
3,624
C#
using System; using System.Drawing; using Grasshopper; using Grasshopper.Kernel; namespace DragonCurve { public class DragonCurveInfo : GH_AssemblyInfo { public override string Name { get { return "DragonCurve"; } } public override Bitmap Icon { get { //Return a 24x24 pixel bitmap to represent this GHA library. return null; } } public override string Description { get { //Return a short string describing the purpose of this GHA library. return ""; } } public override Guid Id { get { return new Guid("c2dda7f0-223e-49e8-bc51-6dc4d31224d9"); } } public override string AuthorName { get { //Return a string identifying you or your company. return "masayaTKT"; } } public override string AuthorContact { get { //Return a string representing your preferred contact details. return ""; } } } public class MeenaxyCategoryIcon : GH_AssemblyPriority { public override GH_LoadingInstruction PriorityLoad() { Instances.ComponentServer.AddCategoryIcon("Meenaxy", Properties.Resources.meenaxyLogo); Instances.ComponentServer.AddCategorySymbolName("Meenaxy", 'M'); return GH_LoadingInstruction.Proceed; } } }
24.753623
99
0.503513
[ "MIT" ]
masayaTAKATA/GH_DragonCurve
DragonCurve/DragonCurveInfo.cs
1,710
C#
namespace EnvironmentAssessment.Common.VimApi { public class HostHardwareStatusInfo : DynamicData { protected HostHardwareElementInfo[] _memoryStatusInfo; protected HostHardwareElementInfo[] _cpuStatusInfo; protected HostStorageElementInfo[] _storageStatusInfo; public HostHardwareElementInfo[] MemoryStatusInfo { get { return this._memoryStatusInfo; } set { this._memoryStatusInfo = value; } } public HostHardwareElementInfo[] CpuStatusInfo { get { return this._cpuStatusInfo; } set { this._cpuStatusInfo = value; } } public HostStorageElementInfo[] StorageStatusInfo { get { return this._storageStatusInfo; } set { this._storageStatusInfo = value; } } } }
17.744186
56
0.70118
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/H/HostHardwareStatusInfo.cs
763
C#
using System; using System.Security.Cryptography; using System.Text; namespace Investec.OpenBanking.RestClient.Extensions { public static class CryptographyExtensions { private static Encoding _defaultEncoding => Encoding.UTF8; public static Guid ToMd5Guid(this string value) => new Guid(GetMd5Hash(value)); public static byte[] GetMd5Hash(string input) { using (var md5 = MD5.Create()) { var inputBytes = _defaultEncoding.GetBytes(input); return md5.ComputeHash(inputBytes); } } } }
27.545455
87
0.633663
[ "MIT" ]
dalion619/investec-openbanking-dotnet
src/Investec.OpenBanking.RestClient/Extensions/CryptographyExtensions.cs
606
C#
using Nethereum.LogProcessing.Dynamic.Handling.Handlers; using System.Threading.Tasks; namespace Nethereum.LogProcessing.Dynamic.Configuration { public class EventContractQueryConfigurationRepository: IEventContractQueryConfigurationRepository { public EventContractQueryConfigurationRepository( IContractQueryRepository queryRepo, ISubscriberContractRepository contractRepo, IContractQueryParameterRepository parameterRepo) { QueryRepo = queryRepo; ContractRepo = contractRepo; ParameterRepo = parameterRepo; } public IContractQueryRepository QueryRepo { get; } public ISubscriberContractRepository ContractRepo { get; } public IContractQueryParameterRepository ParameterRepo { get; } public async Task<ContractQueryConfiguration> GetAsync(long subscriberId, long eventHandlerId) { return await QueryRepo.LoadContractQueryConfiguration( subscriberId, eventHandlerId, ContractRepo, ParameterRepo).ConfigureAwait(false); } } }
38.448276
102
0.721973
[ "MIT" ]
Dave-Whiffin/Nethereum.BlockchainProcessing
src/Nethereum.LogProcessing.Dynamic/Configuration/EventContractQueryConfigurationRepository.cs
1,117
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Divergent.Frontend { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); //some IT/Ops code to allow all modules to configure routes: IRegisterRoutes } } }
26
99
0.60355
[ "Apache-2.0" ]
zpbappi/Workshop.Microservices
demos/CompositeUI-MVC/Divergent.Frontend/App_Start/RouteConfig.cs
678
C#
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using TheArtOfDev.HtmlRenderer.Core.Dom; using TheArtOfDev.HtmlRenderer.Core.Utils; namespace TheArtOfDev.HtmlRenderer.Core.Parse { /// <summary> /// /// </summary> internal static class HtmlParser { /// <summary> /// Parses the source html to css boxes tree structure. /// </summary> /// <param name="source">the html source to parse</param> public static CssBox ParseDocument(string source) { var root = CssBox.CreateBlock(); var curBox = root; int endIdx = 0; int startIdx = 0; while (startIdx >= 0) { var tagIdx = source.IndexOf('<', startIdx); if (tagIdx >= 0 && tagIdx < source.Length) { // add the html text as anon css box to the structure AddTextBox(source, startIdx, tagIdx, ref curBox); if (source[tagIdx + 1] == '!') { if (source[tagIdx + 2] == '-') { // skip the html comment elements (<!-- bla -->) startIdx = source.IndexOf("-->", tagIdx + 2); endIdx = startIdx > 0 ? startIdx + 3 : tagIdx + 2; } else { // skip the html crap elements (<!crap bla>) startIdx = source.IndexOf(">", tagIdx + 2); endIdx = startIdx > 0 ? startIdx + 1 : tagIdx + 2; } } else { // parse element tag to css box structure endIdx = ParseHtmlTag(source, tagIdx, ref curBox) + 1; if (curBox.HtmlTag != null && curBox.HtmlTag.Name.Equals(HtmlConstants.Style, StringComparison.OrdinalIgnoreCase)) { var endIdxS = endIdx; endIdx = source.IndexOf("</style>", endIdx, StringComparison.OrdinalIgnoreCase); if (endIdx > -1) AddTextBox(source, endIdxS, endIdx, ref curBox); } } } startIdx = tagIdx > -1 && endIdx > 0 ? endIdx : -1; } // handle pieces of html without proper structure if (endIdx > -1 && endIdx < source.Length) { // there is text after the end of last element var endText = new SubString(source, endIdx, source.Length - endIdx); if (!endText.IsEmptyOrWhitespace()) { var abox = CssBox.CreateBox(root); abox.Text = endText; } } return root; } #region Private methods /// <summary> /// Add html text anon box to the current box, this box will have the rendered text<br/> /// Adding box also for text that contains only whitespaces because we don't know yet if /// the box is preformatted. At later stage they will be removed if not relevant. /// </summary> /// <param name="source">the html source to parse</param> /// <param name="startIdx">the start of the html part</param> /// <param name="tagIdx">the index of the next html tag</param> /// <param name="curBox">the current box in html tree parsing</param> private static void AddTextBox(string source, int startIdx, int tagIdx, ref CssBox curBox) { var text = tagIdx > startIdx ? new SubString(source, startIdx, tagIdx - startIdx) : null; if (text != null) { var abox = CssBox.CreateBox(curBox); abox.Text = text; } } /// <summary> /// Parse the html part, the part from prev parsing index to the beginning of the next html tag.<br/> /// </summary> /// <param name="source">the html source to parse</param> /// <param name="tagIdx">the index of the next html tag</param> /// <param name="curBox">the current box in html tree parsing</param> /// <returns>the end of the parsed part, the new start index</returns> private static int ParseHtmlTag(string source, int tagIdx, ref CssBox curBox) { var endIdx = source.IndexOf('>', tagIdx + 1); if (endIdx > 0) { string tagName; Dictionary<string, string> tagAttributes; var length = endIdx - tagIdx + 1 - (source[endIdx - 1] == '/' ? 1 : 0); if (ParseHtmlTag(source, tagIdx, length, out tagName, out tagAttributes)) { if (!HtmlUtils.IsSingleTag(tagName) && curBox.ParentBox != null) { // need to find the parent tag to go one level up curBox = DomUtils.FindParent(curBox.ParentBox, tagName, curBox); } } else if (!string.IsNullOrEmpty(tagName)) { //new SubString(source, lastEnd + 1, tagmatch.Index - lastEnd - 1) var isSingle = HtmlUtils.IsSingleTag(tagName) || source[endIdx - 1] == '/'; var tag = new HtmlTag(tagName, isSingle, tagAttributes); if (isSingle) { // the current box is not changed CssBox.CreateBox(tag, curBox); } else { // go one level down, make the new box the current box curBox = CssBox.CreateBox(tag, curBox); } } else { endIdx = tagIdx + 1; } } return endIdx; } /// <summary> /// Parse raw html tag source to <seealso cref="HtmlTag"/> object.<br/> /// Extract attributes found on the tag. /// </summary> /// <param name="source">the html source to parse</param> /// <param name="idx">the start index of the tag in the source</param> /// <param name="length">the length of the tag from the start index in the source</param> /// <param name="name">return the name of the html tag</param> /// <param name="attributes">return the dictionary of tag attributes</param> /// <returns>true - the tag is closing tag, false - otherwise</returns> private static bool ParseHtmlTag(string source, int idx, int length, out string name, out Dictionary<string, string> attributes) { idx++; length = length - (source[idx + length - 3] == '/' ? 3 : 2); // Check if is end tag var isClosing = false; if (source[idx] == '/') { idx++; length--; isClosing = true; } int spaceIdx = idx; while (spaceIdx < idx + length && !char.IsWhiteSpace(source, spaceIdx)) spaceIdx++; // Get the name of the tag name = source.Substring(idx, spaceIdx - idx).ToLower(); attributes = null; if (!isClosing && idx + length > spaceIdx) { ExtractAttributes(source, spaceIdx, length - (spaceIdx - idx), out attributes); } return isClosing; } /// <summary> /// Extract html tag attributes from the given sub-string. /// </summary> /// <param name="source">the html source to parse</param> /// <param name="idx">the start index of the tag attributes in the source</param> /// <param name="length">the length of the tag attributes from the start index in the source</param> /// <param name="attributes">return the dictionary of tag attributes</param> private static void ExtractAttributes(string source, int idx, int length, out Dictionary<string, string> attributes) { attributes = null; int startIdx = idx; while (startIdx < idx + length) { while (startIdx < idx + length && char.IsWhiteSpace(source, startIdx)) startIdx++; var endIdx = startIdx + 1; while (endIdx < idx + length && !char.IsWhiteSpace(source, endIdx) && source[endIdx] != '=') endIdx++; if (startIdx < idx + length) { var key = source.Substring(startIdx, endIdx - startIdx); var value = ""; startIdx = endIdx + 1; while (startIdx < idx + length && (char.IsWhiteSpace(source, startIdx) || source[startIdx] == '=')) startIdx++; bool hasPChar = false; if (startIdx < idx + length) { char pChar = source[startIdx]; if (pChar == '"' || pChar == '\'') { hasPChar = true; startIdx++; } endIdx = startIdx + (hasPChar ? 0 : 1); while (endIdx < idx + length && (hasPChar ? source[endIdx] != pChar : !char.IsWhiteSpace(source, endIdx))) endIdx++; value = source.Substring(startIdx, endIdx - startIdx); value = HtmlUtils.DecodeHtml(value); } if (key.Length != 0) { if (attributes == null) attributes = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); attributes[key.ToLower()] = value; } startIdx = endIdx + (hasPChar ? 2 : 1); } } } #endregion } }
40.673004
138
0.478078
[ "BSD-3-Clause" ]
AndGutierrez/HTML-Renderer
Source/HtmlRenderer/Core/Parse/HtmlParser.cs
10,699
C#
namespace Octokit.GraphQL.Model { using System; using System.Collections.Generic; using System.Linq.Expressions; using Octokit.GraphQL.Core; using Octokit.GraphQL.Core.Builders; /// <summary> /// An edge in a connection. /// </summary> public class OrganizationInvitationEdge : QueryableValue<OrganizationInvitationEdge> { internal OrganizationInvitationEdge(Expression expression) : base(expression) { } /// <summary> /// A cursor for use in pagination. /// </summary> public string Cursor { get; } /// <summary> /// The item at the end of the edge. /// </summary> public OrganizationInvitation Node => this.CreateProperty(x => x.Node, Octokit.GraphQL.Model.OrganizationInvitation.Create); internal static OrganizationInvitationEdge Create(Expression expression) { return new OrganizationInvitationEdge(expression); } } }
30.121212
132
0.641851
[ "MIT" ]
0xced/octokit.graphql.net
Octokit.GraphQL/Model/OrganizationInvitationEdge.cs
994
C#
// Generated class v2.50.0.0, don't modify using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace NHtmlUnit.Javascript.Host.Performance { public partial class PerformanceTiming : NHtmlUnit.Javascript.SimpleScriptable { static PerformanceTiming() { ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.performance.PerformanceTiming o) => new PerformanceTiming(o)); } public PerformanceTiming(com.gargoylesoftware.htmlunit.javascript.host.performance.PerformanceTiming wrappedObject) : base(wrappedObject) {} public new com.gargoylesoftware.htmlunit.javascript.host.performance.PerformanceTiming WObj { get { return (com.gargoylesoftware.htmlunit.javascript.host.performance.PerformanceTiming)WrappedObject; } } public PerformanceTiming() : this(new com.gargoylesoftware.htmlunit.javascript.host.performance.PerformanceTiming()) {} public System.Int64 DomainLookupStart { get { return WObj.getDomainLookupStart(); } } public System.Int64 DomainLookupEnd { get { return WObj.getDomainLookupEnd(); } } public System.Int64 ConnectStart { get { return WObj.getConnectStart(); } } public System.Int64 ConnectEnd { get { return WObj.getConnectEnd(); } } public System.Int64 ResponseStart { get { return WObj.getResponseStart(); } } public System.Int64 ResponseEnd { get { return WObj.getResponseEnd(); } } public System.Int64 SecureConnectionStart { get { return WObj.getSecureConnectionStart(); } } public System.Int64 UnloadEventStart { get { return WObj.getUnloadEventStart(); } } public System.Int64 UnloadEventEnd { get { return WObj.getUnloadEventEnd(); } } public System.Int64 RedirectStart { get { return WObj.getRedirectStart(); } } public System.Int64 RedirectEnd { get { return WObj.getRedirectEnd(); } } public System.Int64 DomContentLoadedEventStart { get { return WObj.getDomContentLoadedEventStart(); } } public System.Int64 DomLoading { get { return WObj.getDomLoading(); } } public System.Int64 DomInteractive { get { return WObj.getDomInteractive(); } } public System.Int64 DomContentLoadedEventEnd { get { return WObj.getDomContentLoadedEventEnd(); } } public System.Int64 DomComplete { get { return WObj.getDomComplete(); } } public System.Int64 LoadEventStart { get { return WObj.getLoadEventStart(); } } public System.Int64 LoadEventEnd { get { return WObj.getLoadEventEnd(); } } public System.Int64 NavigationStart { get { return WObj.getNavigationStart(); } } public System.Int64 FetchStart { get { return WObj.getFetchStart(); } } } }
19.989637
147
0.525402
[ "Apache-2.0" ]
HtmlUnit/NHtmlUnit
app/NHtmlUnit/Generated/Javascript/Host/Performance/PerformanceTiming.cs
3,858
C#
using System; using System.Collections.Generic; namespace EF7.Bencher.Model { public partial class BusinessEntityContact { public int BusinessEntityID { get; set; } public int PersonID { get; set; } public int ContactTypeID { get; set; } public DateTime ModifiedDate { get; set; } public Guid rowguid { get; set; } public virtual BusinessEntity BusinessEntity { get; set; } public virtual ContactType ContactType { get; set; } public virtual Person Person { get; set; } } }
29.052632
66
0.650362
[ "MIT" ]
sanekpr/RawDataAccessBencher
EF7.Bencher.Model/BusinessEntityContact.cs
552
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.Cognito.Outputs { [OutputType] public sealed class IdentityPoolCognitoIdentityProvider { public readonly string? ClientId; public readonly string? ProviderName; public readonly bool? ServerSideTokenCheck; [OutputConstructor] private IdentityPoolCognitoIdentityProvider( string? clientId, string? providerName, bool? serverSideTokenCheck) { ClientId = clientId; ProviderName = providerName; ServerSideTokenCheck = serverSideTokenCheck; } } }
26.911765
81
0.67541
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/Cognito/Outputs/IdentityPoolCognitoIdentityProvider.cs
915
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; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Alidns.Transform; using Aliyun.Acs.Alidns.Transform.V20150109; using System.Collections.Generic; namespace Aliyun.Acs.Alidns.Model.V20150109 { public class SetDomainRecordStatusRequest : RpcAcsRequest<SetDomainRecordStatusResponse> { public SetDomainRecordStatusRequest() : base("Alidns", "2015-01-09", "SetDomainRecordStatus") { } private string lang; private string userClientIp; private string recordId; private string status; public string Lang { get { return lang; } set { lang = value; DictionaryUtil.Add(QueryParameters, "Lang", value); } } public string UserClientIp { get { return userClientIp; } set { userClientIp = value; DictionaryUtil.Add(QueryParameters, "UserClientIp", value); } } public string RecordId { get { return recordId; } set { recordId = value; DictionaryUtil.Add(QueryParameters, "RecordId", value); } } public string Status { get { return status; } set { status = value; DictionaryUtil.Add(QueryParameters, "Status", value); } } public override SetDomainRecordStatusResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return SetDomainRecordStatusResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
23.871287
121
0.676898
[ "Apache-2.0" ]
DMIAOCHEN/AliyunService
Depends/aliyun-net-sdk-alidns/Alidns/Model/V20150109/SetDomainRecordStatusRequest.cs
2,411
C#
using Content.Server.Botany.Components; using Content.Shared.Botany; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.Reagent; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Chemistry.ReagentEffects.PlantMetabolism { [UsedImplicitly] [DataDefinition] public class RobustHarvest : ReagentEffect { public override void Metabolize(EntityUid plantHolder, EntityUid organEntity, Solution.ReagentQuantity reagent, IEntityManager entityManager) { if (!entityManager.TryGetComponent(plantHolder, out PlantHolderComponent? plantHolderComp) || plantHolderComp.Seed == null || plantHolderComp.Dead || plantHolderComp.Seed.Immutable) return; var random = IoCManager.Resolve<IRobustRandom>(); var chance = MathHelper.Lerp(15f, 150f, plantHolderComp.Seed.Potency) * 3.5f; if (random.Prob(chance)) { plantHolderComp.CheckForDivergence(true); plantHolderComp.Seed.Potency++; } chance = MathHelper.Lerp(6f, 2f, plantHolderComp.Seed.Yield) * 0.15f; if (random.Prob(chance)) { plantHolderComp.CheckForDivergence(true); plantHolderComp.Seed.Yield--; } } } }
34.666667
149
0.646795
[ "MIT" ]
virgildotcodes/space-station-14
Content.Server/Chemistry/ReagentEffects/PlantMetabolism/RobustHarvest.cs
1,562
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Acai.NewsStatistics.Models { [Serializable] public class ListContentsModel { public int Id { get; set; } public string PublishTime { get; set; } public string Title { get; set; } public string Keywords { get; set; } public string LinkUrl { get; set; } public string Tags { get; set; } } }
24.944444
47
0.632517
[ "BSD-3-Clause" ]
charles0525/orchard
src/Orchard.Web/Modules/Acai.NewsStatistics/Models/ListContentsModel.cs
451
C#