content
stringlengths
23
1.05M
/********************************************************************************************************************** FocusOPEN Digital Asset Manager (TM) (c) Daydream Interactive Limited 1995-2011, All Rights Reserved The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders. Please refer to licences/focusopen.txt or http://www.digitalassetmanager.com for licensing information about this software. **********************************************************************************************************************/ using System; using System.Web.UI.WebControls; using FocusOPEN.Data; using FocusOPEN.Shared; using FocusOPEN.Website.Components; namespace FocusOPEN.Website.Controls { public class BrandMetadataLabel : Label { #region Public Accessors /// <summary> /// Gets or sets the field name /// </summary> public string FieldName { get; set; } /// <summary> /// Gets or sets the brand control ID /// If not set, the current brand is used /// (based on the logged in user or URL) /// </summary> public string BrandDropDownListId { get; set; } #endregion #region Private Accessors /// <summary> /// Gets the brand to be used for setting this label text /// </summary> private Brand Brand { get { // Get the current brand Brand brand = WebsiteBrandManager.GetBrand(); // Check for a brand control ID // If specified, then get the brand based on that if (!string.IsNullOrEmpty(BrandDropDownListId)) { ListControl dropdown = SiteUtils.FindControlRecursiveUp(this, BrandDropDownListId) as ListControl; if (dropdown != null) { int selectedId = NumericUtils.ParseInt32(dropdown.SelectedValue, Int32.MinValue); if (selectedId != Int32.MinValue) { Brand b = BrandCache.Instance.GetById(selectedId); if (!b.IsNull) brand = b; } } } return brand; } } #endregion #region Overrides protected override void OnPreRender(EventArgs e) { BrandMetadataSetting setting = Brand.GetMetadataSetting(FieldName); if (setting.IsNull) setting = WebsiteBrandManager.GetMasterBrand().GetMetadataSetting(FieldName); if (setting.IsNull || StringUtils.IsBlank(setting.FieldName)) { Text = GeneralUtils.SplitIntoSentence(FieldName); return; } Text = setting.FieldName; } #endregion } }
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; /// Dummy router to connect to when moving onto the next room. When hacked into, switches the scene. public class DummyRouter : HackableObject { void Update() { if (active) { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } } public override string ToString() { return uid + " (Router)"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SharpGL.SceneGraph.Core; namespace SharpGL.SceneGraph.Raytracing { /// <summary> /// A Ray. /// </summary> public class Ray { /// <summary> /// The light. /// </summary> public GLColor light = new GLColor(0, 0, 0, 0); /// <summary> /// The origin. /// </summary> public System.Numerics.Vector3 origin = new System.Numerics.Vector3(); /// <summary> /// The direction. /// </summary> public System.Numerics.Vector3 direction = new System.Numerics.Vector3(); } }
using Xerris.DotNet.Core.TestSupport; namespace Xerris.DotNet.Core.Test { public class AddMe : IAddMe { } }
using System.IO; namespace DuplicateClass { public class Program { private static readonly string RootDirectory = Path.GetFullPath(@"..\..\..\NetCoreRepro"); public static void Main(string[] args) { using (var fileWriter = File.CreateText(Path.Combine(RootDirectory, "IClassN.cs"))) { fileWriter.WriteLine($"public class Base {{ public virtual void DoSomething() {{ }} }}"); for (int i = 1; i <= 1000; ++i) { fileWriter.WriteLine($"public class Derived{i} : Base {{ }}"); } } } } }
using System.Collections.Immutable; using System.Reflection; using System.Runtime.Loader; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; namespace Analyzers.Tests.Helpers; public record GenerationTestResults( CSharpCompilation InputCompilation, ImmutableArray<Diagnostic> InputDiagnostics, ImmutableArray<SyntaxTree> InputSyntaxTrees, ImmutableDictionary<Type, GenerationTestResult> Results, ImmutableArray<Diagnostic> ResultDiagnostics ) { public static implicit operator CSharpCompilation(GenerationTestResults results) { return results.ToFinalCompilation(); } public bool TryGetResult(Type type, [NotNullWhen(true)] out GenerationTestResult? result) { return Results.TryGetValue(type, out result); } public bool TryGetResult<T>([NotNullWhen(true)] out GenerationTestResult? result) where T : new() { return Results.TryGetValue(typeof(T), out result); } public void EnsureDiagnosticSeverity(DiagnosticSeverity severity = DiagnosticSeverity.Warning) { Assert.Empty(InputDiagnostics.Where(x => x.Severity >= severity)); foreach (var result in Results.Values) { result.EnsureDiagnostics(severity); } } public void AssertGeneratedAsExpected<T>(string expectedValue, params string[] expectedValues) where T : new() { if (!TryGetResult<T>(out var result)) { Assert.NotNull(result); return; } result.AssertGeneratedAsExpected(expectedValue); } public void AssertCompilationWasSuccessful() { Assert.Empty( InputDiagnostics .Where(z => !z.GetMessage().Contains("does not contain a definition for")) .Where(z => !z.GetMessage().Contains("Assuming assembly reference")) .Where(x => x.Severity >= DiagnosticSeverity.Warning) ); foreach (var result in Results.Values) { result.EnsureDiagnosticSeverity(); } } public void AssertGenerationWasSuccessful() { foreach (var item in Results.Values) { Assert.NotNull(item.Compilation); item.EnsureDiagnosticSeverity(); } } public CSharpCompilation ToFinalCompilation() { return Results.Values.Aggregate(InputCompilation, (current, item) => current.AddSyntaxTrees(item.SyntaxTrees)); } }
namespace RegexParser.Nodes { /// <summary> /// RegexNode representing a single character "a". /// </summary> public class CharacterNode : RegexNode { public char Character { get; } public CharacterNode(char ch) { Character = ch; } public override string ToString() { return $"{Prefix}{Character}"; } protected override RegexNode CopyInstance() { return new CharacterNode(Character); } } }
using System; using NUnit.Framework; class Membership_is_active : BaseTest { [Test] public void Should_tell_if_period_is_active() { var dateTimeNow = DateTime.Now; var dateTimeEnd = DateTime.Now.AddMonths(6); var membership = new Membership { PeriodStart = dateTimeNow, PeriodEnd = dateTimeEnd }; Assert.That(membership.IsActive(dateTimeNow)); Assert.That(membership.IsActive(dateTimeEnd)); } }
// *** 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.Datadog.Outputs { [OutputType] public sealed class DashboardWidgetQueryTableDefinitionRequestFormulaConditionalFormat { public readonly string Comparator; public readonly string? CustomBgColor; public readonly string? CustomFgColor; public readonly bool? HideValue; public readonly string? ImageUrl; public readonly string? Metric; public readonly string Palette; public readonly string? Timeframe; public readonly double Value; [OutputConstructor] private DashboardWidgetQueryTableDefinitionRequestFormulaConditionalFormat( string comparator, string? customBgColor, string? customFgColor, bool? hideValue, string? imageUrl, string? metric, string palette, string? timeframe, double value) { Comparator = comparator; CustomBgColor = customBgColor; CustomFgColor = customFgColor; HideValue = hideValue; ImageUrl = imageUrl; Metric = metric; Palette = palette; Timeframe = timeframe; Value = value; } } }
using UnityEngine; namespace Leyoutech.Utility { public static class GizmosUtility { public static void DrawBounds(Bounds bounds) { Gizmos.DrawCube(bounds.center, bounds.size); } public static void DrawBounds(Bounds bounds, Color color) { Gizmos.color = color; DrawBounds(bounds); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(AudioSource))] public class PlayVoiceoverCommand : CommandToExecute { public AudioClip audio; public MuteButtonAction muteButton; AudioSource source; // Use this for initialization override public void Start () { source = GetComponent<AudioSource>(); base.Start(); } // Update is called once per frame void Update () { } override protected Action Command() { return delegate { if(!(muteButton == null) && !muteButton.IsMuted()) source.PlayOneShot(audio, 2.0f); }; } }
using OpenTK; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OpenWorld.Engine { /// <summary> /// Provides a view matrix. /// </summary> public interface IViewMatrixSource { /// <summary> /// Gets the view matrix. /// </summary> /// <returns></returns> Matrix4 GetViewMatrix(Camera camera); } /// <summary> /// Provides a projection matrix. /// </summary> public interface IProjectionMatrixSource { /// <summary> /// Gets the projection matrix. /// </summary> /// <returns></returns> Matrix4 GetProjectionMatrix(Camera camera); } }
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.471/blob/master/LICENSE * */ #endregion namespace Common { public enum SupportedHashAlgorithims { MESSAGEDIGEST5 = 0, SECUREHASHALGORITHIM1 = 1, SECUREHASHALGORITHIM256 = 2, SECUREHASHALGORITHIM384 = 3, SECUREHASHALGORITHIM512 = 4, RACEINTEGRITYPRIMITIVESEVALUATIONMESSAGEDIGEST = 5 } /// <summary> /// The icon type. /// </summary> public enum IconType { /// <summary> /// The warning /// </summary> WARNING = 101, /// <summary> /// The help /// </summary> HELP = 102, /// <summary> /// The error /// </summary> ERROR = 103, /// <summary> /// The information /// </summary> INFO = 104, /// <summary> /// The shield /// </summary> SHIELD = 106 } public enum DevelopmentState { PREALPHA, ALPHA, BETA, RTM, CURRENT, EOL } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Text; using System.Threading.Tasks; using AnZw.NavCodeEditor.Extensions.Reflection; namespace AnZw.NavCodeEditor.Extensions.LanguageService { public class TypeInfoManager : ReflectionWrapper { public TypeInfoManager(object source) : base(source) { } public IEnumerable<SignatureInfo> GetSignatures(string methodName) { IEnumerable sourceSignatureList = CallMethod<IEnumerable>("GetSignatures", methodName); if (sourceSignatureList == null) return null; List<SignatureInfo> signatures = new List<SignatureInfo>(); foreach (object sourceSignature in sourceSignatureList) { signatures.Add(new SignatureInfo(sourceSignature)); } return signatures; } public IEnumerable<FieldInfo> GetFields(string owner) { IEnumerable sourceFieldList = CallMethod<IEnumerable>("GetFields", owner); if (sourceFieldList == null) return null; List<FieldInfo> fields = new List<FieldInfo>(); foreach (object sourceField in sourceFieldList) { fields.Add(new FieldInfo(sourceField)); } return fields; } } }
using ConsoleTableExt; using MovieManager.Core.DataTransferObjects; using Newtonsoft.Json.Linq; using RestSharp; using System; using System.Collections.Generic; using System.Linq; namespace MovieManager.ConsoleClient { class Program { private const string ServerNameWithPort = "localhost:57745"; static void Main(string[] args) { //RetrieveCategories(); RetrieveMoviesForCategoryId(3); } private static void RetrieveMoviesForCategoryId(int id) { var client = new RestClient($"http://{ServerNameWithPort}"); var request = new RestRequest($"api/categories/{id}/movies", DataFormat.Json); var response = client.Get(request); JArray moviesAsJson = JArray.Parse(response.Content); List<MovieDto> movies = moviesAsJson .Select(m => m.ToObject<MovieDto>()) .OrderBy(m => m.Title) .ToList(); ConsoleTableBuilder .From(movies) .ExportAndWriteLine(); } public static void RetrieveCategories() { var client = new RestClient($"http://{ServerNameWithPort}"); var request = new RestRequest("api/categories", DataFormat.Json); var response = client.Get(request); JArray categories = JArray.Parse(response.Content); foreach (var category in categories) { Console.WriteLine(category); } Console.ReadKey(); } } }
using NetPrints.Core; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace NetPrints.Core { [Serializable] [DataContract] public class PropertySpecifier { [DataMember] public string Name { get; private set; } [DataMember] public TypeSpecifier DeclaringType { get; private set; } [DataMember] public TypeSpecifier Type { get; private set; } [DataMember] public bool HasPublicGetter { get; private set; } [DataMember] public bool HasPublicSetter { get; private set; } public PropertySpecifier(string name, TypeSpecifier type, bool hasPublicGetter, bool hasPublicSetter, TypeSpecifier declaringType) { Name = name; Type = type; HasPublicGetter = hasPublicGetter; HasPublicSetter = HasPublicSetter; DeclaringType = declaringType; } public static implicit operator PropertySpecifier(PropertyInfo propertyInfo) { MethodInfo[] publicAccessors = propertyInfo.GetAccessors(); bool hasPublicGetter = publicAccessors.Any(a => a.ReturnType != typeof(void)); bool hasPublicSetter = publicAccessors.Any(a => a.ReturnType == typeof(void)); return new PropertySpecifier( propertyInfo.Name, propertyInfo.PropertyType, hasPublicGetter, hasPublicSetter, propertyInfo.DeclaringType); } } }
using Contega; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest.Contega.core { [TestClass] public class ContagaGameTests { [TestMethod] [ExpectedException(typeof(GridToSmallException))] public void New_ToNarrow_GridToSmallException() { new ContegaGame(9, 22); } [TestMethod] [ExpectedException(typeof(GridToSmallException))] public void New_ToShort_GridToSmallException() { new ContegaGame(10, 21); } [TestMethod] public void New_10_22_GridSizeCheck() { var game = new ContegaGame(10, 22); Assert.AreEqual(10, game.Grid.Width); Assert.AreEqual(22, game.Grid.Height); } [TestMethod] public void ActiveBlock_NotNull() { var game = new ContegaGame(10, 22); var block = game.ActiveBlock; Assert.IsNotNull(block); } // test if tetromino drops on tick // test if first 7 blocks contain 7 different values // test is second block is there // test if first block is there // test if tetromino stops dropping at bottom // test if tetromino stop dropping when hitting other // test if move left works // test if move right works // test if move left stops after hitting wall // test if move right stops after hitting wall // test if rotate left/right works // test if rotated block still hits walls and other blocks // test if a full line is detected // test if 4 fulle lines are detected // test if full lines get removed // test if ghost image is correct // test if hard drop works // test if game over is detected // test if reset game works // test if block ID's are correctly copied to the grid // test if score increases in all situations // test if level rises after 10 lines. // test if level stops rising after reaching max // test is next block moves to active block } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Galaxy.Azure.ServiceBus.Extensions.Retry { public interface IServiceBusRetryHandler { Task Handle(ServiceBusRetryWrapper serviceBusRetryWrapper); } }
// DigitalRune Engine - Copyright (C) DigitalRune GmbH // This file is subject to the terms and conditions defined in // file 'LICENSE.TXT', which is part of this source code package. using System; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using DigitalRune.Mathematics; using Image = System.Windows.Controls.Image; namespace DigitalRune.Windows.Controls { /// <summary> /// Represents a context menu for selecting the mode and scale of an <see cref="ExplorerView"/>. /// </summary> [TemplatePart(Name = "PART_ViewSlider", Type = typeof(Slider))] public class ExplorerViewMenu : ContextMenu { //-------------------------------------------------------------- #region Constants //-------------------------------------------------------------- // The scales that correspond to the individual view modes. internal const double ScaleExtraLarge = 16; internal const double ScaleLarge = 6; internal const double ScaleMedium = 3; internal const double ScaleSmall = 1; internal const double ScaleList = 1; internal const double ScaleDetails = 1; internal const double ScaleTiles = 1; // The slider positions that correspond to the view modes. private const double SliderPositionExtraLarge = 222; private const double SliderPositionLarge = 178; private const double SliderPositionMedium = 148; private const double SliderPositionSmall = 108; private const double SliderPositionList = 72; private const double SliderPositionDetails = 36; private const double SliderPositionTiles = 0; #endregion //-------------------------------------------------------------- #region Fields //-------------------------------------------------------------- private bool _initialized; private bool _updating; private Slider _slider; private Thumb _sliderThumb; #endregion //-------------------------------------------------------------- #region Properties //-------------------------------------------------------------- #endregion //-------------------------------------------------------------- #region Dependency Properties //-------------------------------------------------------------- #region ----- Customization ----- /// <summary> /// Identifies the <see cref="ImageSourceExtraLargeIcons"/> dependency property. /// </summary> public static readonly DependencyProperty ImageSourceExtraLargeIconsProperty = DependencyProperty.Register( "ImageSourceExtraLargeIcons", typeof(object), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets the <see cref="ImageSource"/> or <see cref="MultiColorGlyph"/> that is /// shown in the "Extra Large Icons" menu item. This is a dependency property. /// </summary> /// <remarks> /// The default display size is 16 x 16 device-independent pixels. /// </remarks> [Description("Gets or sets the image that represents the 'Extra Large Icons' mode.")] [Category(Categories.Appearance)] public object ImageSourceExtraLargeIcons { get { return GetValue(ImageSourceExtraLargeIconsProperty); } set { SetValue(ImageSourceExtraLargeIconsProperty, value); } } /// <summary> /// Identifies the <see cref="ImageSourceLargeIcons"/> dependency property. /// </summary> public static readonly DependencyProperty ImageSourceLargeIconsProperty = DependencyProperty.Register( "ImageSourceLargeIcons", typeof(object), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="ImageSource"/> or <see cref="MultiColorGlyph"/> that is shown in /// the "Large Icons" menu item. This is a dependency property. /// </summary> /// <remarks> /// The default display size is 16 x 16 device-independent pixels. /// </remarks> [Description("Gets or sets the image that represents the 'Large Icons' mode.")] [Category(Categories.Appearance)] public object ImageSourceLargeIcons { get { return GetValue(ImageSourceLargeIconsProperty); } set { SetValue(ImageSourceLargeIconsProperty, value); } } /// <summary> /// Identifies the <see cref="ImageSourceMediumIcons"/> dependency property. /// </summary> public static readonly DependencyProperty ImageSourceMediumIconsProperty = DependencyProperty.Register( "ImageSourceMediumIcons", typeof(object), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="ImageSource"/> or <see cref="MultiColorGlyph"/> that is shown in /// the "Medium Icons" menu item. This is a dependency property. /// </summary> /// <remarks> /// The default display size is 16 x 16 device-independent pixels. /// </remarks> [Description("Gets or sets the image that represents the 'Medium Icons' mode.")] [Category(Categories.Appearance)] public object ImageSourceMediumIcons { get { return GetValue(ImageSourceMediumIconsProperty); } set { SetValue(ImageSourceMediumIconsProperty, value); } } /// <summary> /// Identifies the <see cref="ImageSourceSmallIcons"/> dependency property. /// </summary> public static readonly DependencyProperty ImageSourceSmallIconsProperty = DependencyProperty.Register( "ImageSourceSmallIcons", typeof(object), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="ImageSource"/> or <see cref="MultiColorGlyph"/> that is shown in /// the "Small Icons" menu item. This is a dependency property. /// </summary> /// <remarks> /// The default display size is 16 x 16 device-independent pixels. /// </remarks> [Description("Gets or sets the image that represents the 'Small Icons' mode.")] [Category(Categories.Appearance)] public object ImageSourceSmallIcons { get { return GetValue(ImageSourceSmallIconsProperty); } set { SetValue(ImageSourceSmallIconsProperty, value); } } /// <summary> /// Identifies the <see cref="ImageSourceList"/> dependency property. /// </summary> public static readonly DependencyProperty ImageSourceListProperty = DependencyProperty.Register( "ImageSourceList", typeof(object), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="ImageSource"/> or <see cref="MultiColorGlyph"/> that is shown in /// the "List" menu item. This is a dependency property. /// </summary> /// <remarks> /// The default display size is 16 x 16 device-independent pixels. /// </remarks> [Description("Gets or sets the image that represents the 'List' mode.")] [Category(Categories.Appearance)] public object ImageSourceList { get { return GetValue(ImageSourceListProperty); } set { SetValue(ImageSourceListProperty, value); } } /// <summary> /// Identifies the <see cref="ImageSourceDetails"/> dependency property. /// </summary> public static readonly DependencyProperty ImageSourceDetailsProperty = DependencyProperty.Register( "ImageSourceDetails", typeof(object), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="ImageSource"/> or <see cref="MultiColorGlyph"/> that is shown in /// the "Details" menu item. This is a dependency property. /// </summary> /// <remarks> /// The default display size is 16 x 16 device-independent pixels. /// </remarks> [Description("Gets or sets the image that represents the 'Details' mode.")] [Category(Categories.Appearance)] public object ImageSourceDetails { get { return GetValue(ImageSourceDetailsProperty); } set { SetValue(ImageSourceDetailsProperty, value); } } /// <summary> /// Identifies the <see cref="ImageSourceTiles"/> dependency property. /// </summary> public static readonly DependencyProperty ImageSourceTilesProperty = DependencyProperty.Register( "ImageSourceTiles", typeof(object), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="ImageSource"/> or <see cref="MultiColorGlyph"/> that is shown in /// the "Tiles" menu item. This is a dependency property. /// </summary> /// <remarks> /// The default display size is 16 x 16 device-independent pixels. /// </remarks> [Description("Gets or sets the image that represents the 'Tiles' mode.")] [Category(Categories.Appearance)] public object ImageSourceTiles { get { return GetValue(ImageSourceTilesProperty); } set { SetValue(ImageSourceTilesProperty, value); } } /// <summary> /// Identifies the <see cref="StringExtraLargeIcons"/> dependency property. /// </summary> public static readonly DependencyProperty StringExtraLargeIconsProperty = DependencyProperty.Register( "StringExtraLargeIcons", typeof(string), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="string"/> that is shown in the "Extra Large Icons" menu item. /// This is a dependency property. /// </summary> [Description("Gets or sets the name of the 'Extra Large Icons' mode.")] [Category(Categories.Default)] public string StringExtraLargeIcons { get { return (string)GetValue(StringExtraLargeIconsProperty); } set { SetValue(StringExtraLargeIconsProperty, value); } } /// <summary> /// Identifies the <see cref="StringLargeIcons"/> dependency property. /// </summary> public static readonly DependencyProperty StringLargeIconsProperty = DependencyProperty.Register( "StringLargeIcons", typeof(string), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="string"/> that is shown in the "Large Icons" menu item. /// This is a dependency property. /// </summary> [Description("Gets or sets the name of the 'Large Icons' mode.")] [Category(Categories.Default)] public string StringLargeIcons { get { return (string)GetValue(StringLargeIconsProperty); } set { SetValue(StringLargeIconsProperty, value); } } /// <summary> /// Identifies the <see cref="StringMediumIcons"/> dependency property. /// </summary> public static readonly DependencyProperty StringMediumIconsProperty = DependencyProperty.Register( "StringMediumIcons", typeof(string), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="string"/> that is shown in the "Medium Icons" menu item. /// This is a dependency property. /// </summary> [Description("Gets or sets the name of the 'Medium Icons' mode.")] [Category(Categories.Default)] public string StringMediumIcons { get { return (string)GetValue(StringMediumIconsProperty); } set { SetValue(StringMediumIconsProperty, value); } } /// <summary> /// Identifies the <see cref="StringSmallIcons"/> dependency property. /// </summary> public static readonly DependencyProperty StringSmallIconsProperty = DependencyProperty.Register( "StringSmallIcons", typeof(string), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="string"/> that is shown in the "Small Icons" menu item. /// This is a dependency property. /// </summary> [Description("Gets or sets the name of the 'Small Icons' mode.")] [Category(Categories.Default)] public string StringSmallIcons { get { return (string)GetValue(StringSmallIconsProperty); } set { SetValue(StringSmallIconsProperty, value); } } /// <summary> /// Identifies the <see cref="StringDetails"/> dependency property. /// </summary> public static readonly DependencyProperty StringDetailsProperty = DependencyProperty.Register( "StringDetails", typeof(string), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="string"/> that is shown in the "Details" menu item. /// This is a dependency property. /// </summary> [Description("Gets or sets the name of the 'Details' mode.")] [Category(Categories.Default)] public string StringDetails { get { return (string)GetValue(StringDetailsProperty); } set { SetValue(StringDetailsProperty, value); } } /// <summary> /// Identifies the <see cref="StringList"/> dependency property. /// </summary> public static readonly DependencyProperty StringListProperty = DependencyProperty.Register( "StringList", typeof(string), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="string"/> that is shown in the "List" menu item. /// This is a dependency property. /// </summary> [Description("Gets or sets the name of the 'List' mode.")] [Category(Categories.Default)] public string StringList { get { return (string)GetValue(StringListProperty); } set { SetValue(StringListProperty, value); } } /// <summary> /// Identifies the <see cref="StringTiles"/> dependency property. /// </summary> public static readonly DependencyProperty StringTilesProperty = DependencyProperty.Register( "StringTiles", typeof(string), typeof(ExplorerViewMenu)); /// <summary> /// Gets or sets <see cref="string"/> that is shown in the "Tiles" menu item. /// This is a dependency property. /// </summary> [Description("Gets or sets the name of the 'Tiles' mode.")] [Category(Categories.Default)] public string StringTiles { get { return (string)GetValue(StringTilesProperty); } set { SetValue(StringTilesProperty, value); } } #endregion private static readonly DependencyPropertyKey IconPropertyKey = DependencyProperty.RegisterReadOnly( "Icon", typeof(object), typeof(ExplorerViewMenu), new FrameworkPropertyMetadata(null)); /// <summary> /// Identifies the <see cref="Icon"/> dependency property. /// </summary> public static readonly DependencyProperty IconProperty = IconPropertyKey.DependencyProperty; /// <summary> /// Gets the icon (<see cref="ImageSource"/> or <see cref="MultiColorGlyph"/>) representing /// the current view mode. This is a dependency property. /// </summary> [Description("Gets the image that represents the current view mode.")] [Category(Categories.Appearance)] public object Icon { get { return GetValue(IconProperty); } private set { SetValue(IconPropertyKey, value); } } /// <summary> /// Identifies the <see cref="Mode"/> dependency property. /// </summary> public static readonly DependencyProperty ModeProperty = ExplorerView.ModeProperty.AddOwner( typeof(ExplorerViewMenu), new FrameworkPropertyMetadata(ExplorerViewMode.Details, FrameworkPropertyMetadataOptions.None, OnModeChanged)); /// <summary> /// Gets or sets the mode of the <see cref="ExplorerView"/>. /// This is a dependency property. /// </summary> /// <value> /// The current <see cref="ExplorerViewMode"/>. The default value is /// <see cref="ExplorerViewMode.Details"/>. /// </value> [Description("Gets or sets current view mode.")] [Category(Categories.Default)] public ExplorerViewMode Mode { get { return (ExplorerViewMode)GetValue(ModeProperty); } set { SetValue(ModeProperty, value); } } /// <summary> /// Identifies the <see cref="Scale"/> dependency property. /// </summary> public static readonly DependencyProperty ScaleProperty = ExplorerView.ScaleProperty.AddOwner( typeof(ExplorerViewMenu), new FrameworkPropertyMetadata(ScaleDetails, FrameworkPropertyMetadataOptions.None, OnScaleChanged)); /// <summary> /// Gets or sets the scale used to display the icons in the <see cref="ExplorerView"/>. /// This is a dependency property. /// </summary> /// <value>A value in the range [1, 16]. The default value is 1.</value> /// <remarks> /// <para> /// This property is only relevant when the <see cref="Mode"/> is set to /// <see cref="ExplorerViewMode.SmallIcons"/>, <see cref="ExplorerViewMode.MediumIcons"/>, /// <see cref="ExplorerViewMode.LargeIcons"/>, or <see cref="ExplorerViewMode.ExtraLargeIcons"/>. /// </para> /// <para> /// When <see cref="Scale"/> is set to a value greater than 1 the property <see cref="Mode"/> is /// automatically set to the appropriate mode (as listed in the previous paragraph). /// </para> /// </remarks> [Description("Gets or sets the scale of the current view [1, 16].")] [Category(Categories.Default)] public double Scale { get { return (double)GetValue(ScaleProperty); } set { SetValue(ScaleProperty, value); } } /// <summary> /// Identifies the <see cref="SliderPosition"/> dependency property. /// </summary> public static readonly DependencyProperty SliderPositionProperty = DependencyProperty.Register( "SliderPosition", typeof(double), typeof(ExplorerViewMenu), new FrameworkPropertyMetadata(SliderPositionMedium, FrameworkPropertyMetadataOptions.None, OnSliderPositionChanged)); /// <summary> /// Gets or sets the position of the slider. /// This is a dependency property. /// </summary> /// <value> /// A value in the range [0, 222]. The default value is 148. /// (0 = Tiles, 36 = Details, 72 = List, 108 = Small Icons, /// 148 = Medium Icons, 178 = Large Icons, 222 = Extra Large Icons) /// </value> [Description("Gets or sets the position of the slider.")] [Category(Categories.Default)] public double SliderPosition { get { return (double)GetValue(SliderPositionProperty); } set { SetValue(SliderPositionProperty, value); } } #endregion //-------------------------------------------------------------- #region Creation and Cleanup //-------------------------------------------------------------- /// <summary> /// Initializes static members of the <see cref="ExplorerViewMenu"/> class. /// </summary> static ExplorerViewMenu() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ExplorerViewMenu), new FrameworkPropertyMetadata(typeof(ExplorerViewMenu))); EventManager.RegisterClassHandler(typeof(ExplorerViewMenu), MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClicked)); } #endregion //-------------------------------------------------------------- #region Methods //-------------------------------------------------------------- /// <summary> /// Raises the <see cref="FrameworkElement.Initialized"/> event. This method is invoked whenever /// <see cref="FrameworkElement.IsInitialized"/> is set to <see langword="true"/> internally. /// </summary> /// <param name="e"> /// The <see cref="RoutedEventArgs"/> that contains the event data. /// </param> protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); var extraLargeIconsMenuItem = new MenuItem { Height = 24, Margin = new Thickness(0, 3, 0, 20), DataContext = ExplorerViewMode.ExtraLargeIcons }; var largeIconsMenuItem = new MenuItem { Height = 24, Margin = new Thickness(0, 0, 0, 6), DataContext = ExplorerViewMode.LargeIcons }; var mediumIconsMenuItem = new MenuItem { Height = 24, Margin = new Thickness(0, 0, 0, 16), DataContext = ExplorerViewMode.MediumIcons }; var smallIconsMenuItem = new MenuItem { Height = 24, Margin = new Thickness(0, 0, 0, 0), DataContext = ExplorerViewMode.SmallIcons }; var listMenuItem = new MenuItem { Height = 24, DataContext = ExplorerViewMode.List }; var detailsMenuItem = new MenuItem { Height = 24, DataContext = ExplorerViewMode.Details }; var tilesMenuItem = new MenuItem { Height = 24, Margin = new Thickness(0, 0, 0, 3), DataContext = ExplorerViewMode.Tiles }; // Bind menu icons to the ImageSource provided by this control. BindMenuIcon(extraLargeIconsMenuItem, ImageSourceExtraLargeIconsProperty); BindMenuIcon(largeIconsMenuItem, ImageSourceLargeIconsProperty); BindMenuIcon(mediumIconsMenuItem, ImageSourceMediumIconsProperty); BindMenuIcon(smallIconsMenuItem, ImageSourceSmallIconsProperty); BindMenuIcon(listMenuItem, ImageSourceListProperty); BindMenuIcon(detailsMenuItem, ImageSourceDetailsProperty); BindMenuIcon(tilesMenuItem, ImageSourceTilesProperty); // Bind menu text to the strings provided by this control. BindMenuText(extraLargeIconsMenuItem, StringExtraLargeIconsProperty); BindMenuText(largeIconsMenuItem, StringLargeIconsProperty); BindMenuText(mediumIconsMenuItem, StringMediumIconsProperty); BindMenuText(smallIconsMenuItem, StringSmallIconsProperty); BindMenuText(listMenuItem, StringListProperty); BindMenuText(detailsMenuItem, StringDetailsProperty); BindMenuText(tilesMenuItem, StringTilesProperty); ItemsSource = new FrameworkElement[] { extraLargeIconsMenuItem, largeIconsMenuItem, mediumIconsMenuItem, smallIconsMenuItem, new Separator { Height = 1, Margin = new Thickness(-30, 6, 0, 5) }, listMenuItem, new Separator { Height = 1, Margin = new Thickness(-30, 6, 0, 5) }, detailsMenuItem, new Separator { Height = 1, Margin = new Thickness(-30, 6, 0, 5) }, tilesMenuItem }; } private void BindMenuIcon(MenuItem menuItem, DependencyProperty property) { var image = new Image { Width = 16, Height = 16 }; var binding = new Binding { Source = this, Path = new PropertyPath(property) }; image.SetBinding(Image.SourceProperty, binding); menuItem.Icon = image; } private void BindMenuText(MenuItem menuItem, DependencyProperty property) { var binding = new Binding { Source = this, Path = new PropertyPath(property) }; menuItem.SetBinding(HeaderedItemsControl.HeaderProperty, binding); } /// <summary> /// When overridden in a derived class, is invoked whenever application code or internal /// processes call <see cref="FrameworkElement.ApplyTemplate"/>. /// </summary> public override void OnApplyTemplate() { DetachFromVisualTree(); AttachToVisualTree(); base.OnApplyTemplate(); } private void AttachToVisualTree() { _slider = GetTemplateChild("PART_ViewSlider") as Slider; if (_slider != null) { _sliderThumb = _slider.GetVisualDescendants(false).OfType<Thumb>().FirstOrDefault(); if (_sliderThumb != null) { _sliderThumb.MouseEnter += CaptureMouseToThumb; _sliderThumb.LostMouseCapture += OnThumbLostMouseCapture; } } } private void DetachFromVisualTree() { if (_sliderThumb != null) { _sliderThumb.MouseEnter -= CaptureMouseToThumb; _sliderThumb.LostMouseCapture -= OnThumbLostMouseCapture; } } /// <summary> /// Captures the mouse to the thumb if the track is clicked somewhere other than the thumb. /// </summary> /// <param name="sender">The sender.</param> /// <param name="eventArgs"> /// The <see cref="MouseEventArgs"/> instance containing the event data. /// </param> private static void CaptureMouseToThumb(object sender, MouseEventArgs eventArgs) { // When the left mouse button is pressed on the thumb, the thumb automatically captures // the mouse. // But when the left mouse button is pressed somewhere else on the slider, the mouse is // not captured by default. But we want the mouse to be captured. Therefore, we have set // up this event handler for Thumb.MouseEnter. The user presses the left mouse button, // the thumbs snaps to this position and Thumb.MouseEnter event is raised. var thumb = sender as Thumb; if (eventArgs.LeftButton == MouseButtonState.Pressed && thumb != null && eventArgs.MouseDevice.Captured != thumb) { // The left mouse button is pressed and the thumb does not have the mouse captured. // --> Generate a MouseLeftButtonDown event. The thumb will then capture the mouse. var args = new MouseButtonEventArgs(eventArgs.MouseDevice, eventArgs.Timestamp, MouseButton.Left); args.RoutedEvent = MouseLeftButtonDownEvent; thumb.RaiseEvent(args); } } /// <summary> /// Called when the thumb of the slider releases/loses the mouse capture. /// </summary> /// <param name="sender">The sender.</param> /// <param name="eventArgs"> /// The <see cref="MouseEventArgs"/> instance containing the event data. /// </param> private void OnThumbLostMouseCapture(object sender, MouseEventArgs eventArgs) { // Close the context menu when the thumb loses the mouse capture. IsOpen = false; } /// <summary> /// Called when the property <see cref="ItemsControl.Items"/> has changed. /// </summary> /// <param name="e"> /// The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data. /// </param> protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { if (!_initialized) { UpdateFromMode(Mode); _initialized = true; } base.OnItemsChanged(e); } /// <summary> /// Called when the property <see cref="Scale"/> has changed. /// </summary> /// <param name="dependencyObject">The dependency object.</param> /// <param name="eventArgs"> /// The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data. /// </param> private static void OnScaleChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs) { var explorerViewMenu = (ExplorerViewMenu)dependencyObject; explorerViewMenu.UpdateFromScale((double)eventArgs.NewValue); } /// <summary> /// Called when property <see cref="SliderPosition"/> has changed. /// </summary> /// <param name="dependencyObject">The dependency object.</param> /// <param name="eventArgs"> /// The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data. /// </param> private static void OnSliderPositionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs) { var explorerViewMenu = (ExplorerViewMenu)dependencyObject; explorerViewMenu.UpdateFromSlider((double)eventArgs.NewValue); } /// <summary> /// Called when the property <see cref="Mode"/> has changed. /// </summary> /// <param name="dependencyObject">The dependency object.</param> /// <param name="eventArgs"> /// The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data. /// </param> private static void OnModeChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs) { var explorerViewMenu = (ExplorerViewMenu)dependencyObject; explorerViewMenu.UpdateFromMode((ExplorerViewMode)eventArgs.NewValue); } /// <summary> /// Raises the <see cref="ContextMenu.Opened"/> event. /// </summary> /// <param name="e"> /// The <see cref="RoutedEventArgs"/> instance containing the event data. /// </param> protected override void OnOpened(RoutedEventArgs e) { if (_sliderThumb != null) { Point centerOfThumb = new Point(_sliderThumb.DesiredSize.Width / 2, _sliderThumb.DesiredSize.Height / 2); Point offsetToThumb = _sliderThumb.TranslatePoint(centerOfThumb, this); Placement = PlacementMode.MousePoint; HorizontalOffset = -offsetToThumb.X; VerticalOffset = -offsetToThumb.Y; } base.OnOpened(e); } /// <summary> /// Called when a menu item is clicked. /// </summary> /// <param name="sender">The sender.</param> /// <param name="eventArgs"> /// The <see cref="RoutedEventArgs"/> instance containing the event data. /// </param> private static void OnMenuItemClicked(object sender, RoutedEventArgs eventArgs) { var explorerViewMenu = (ExplorerViewMenu)sender; if (explorerViewMenu != null) { var menuItem = eventArgs.OriginalSource as MenuItem; if (menuItem?.DataContext is ExplorerViewMode) { explorerViewMenu.Mode = (ExplorerViewMode)menuItem.DataContext; eventArgs.Handled = true; } } } private void UpdateFromScale(double scale) { // Avoid re-entrance. if (_updating) return; _updating = true; try { SetSliderPosition(scale); SetMode(SliderPosition); SetIcon(Mode); } finally { _updating = false; } } private void UpdateFromSlider(double sliderPosition) { // Avoid re-entrance. if (_updating) return; _updating = true; try { SetScale(sliderPosition); SetMode(sliderPosition); SetIcon(Mode); } finally { _updating = false; } } private void UpdateFromMode(ExplorerViewMode mode) { // Avoid re-entrance. if (_updating) return; _updating = true; try { SetScale(mode); SetSliderPosition(mode); SetIcon(mode); } finally { _updating = false; } } private void SetIcon(ExplorerViewMode mode) { switch (mode) { case ExplorerViewMode.ExtraLargeIcons: Icon = ImageSourceExtraLargeIcons; break; case ExplorerViewMode.LargeIcons: Icon = ImageSourceLargeIcons; break; case ExplorerViewMode.MediumIcons: Icon = ImageSourceMediumIcons; break; case ExplorerViewMode.SmallIcons: Icon = ImageSourceSmallIcons; break; case ExplorerViewMode.List: Icon = ImageSourceList; break; case ExplorerViewMode.Details: Icon = ImageSourceDetails; break; default: Icon = ImageSourceTiles; break; } } private void SetScale(double sliderPosition) { if (Numeric.IsLessOrEqual(sliderPosition, SliderPositionSmall)) Scale = 1.0; else if (Numeric.IsLess(sliderPosition, SliderPositionMedium)) Scale = ((sliderPosition - 116) / 4) * 0.25 + 1.25; else if (Numeric.AreEqual(sliderPosition, SliderPositionMedium)) Scale = 3; else if (Numeric.IsLess(sliderPosition, SliderPositionLarge)) Scale = ((sliderPosition - 155) / 4) * 0.5 + 3.5; else if (Numeric.AreEqual(sliderPosition, SliderPositionLarge)) Scale = 6; else if (Numeric.IsLess(sliderPosition, SliderPositionExtraLarge)) Scale = ((sliderPosition - 184) / 4) + 7; else Scale = 16; } private void SetScale(ExplorerViewMode mode) { switch (mode) { case ExplorerViewMode.ExtraLargeIcons: Scale = ScaleExtraLarge; break; case ExplorerViewMode.LargeIcons: Scale = ScaleLarge; break; case ExplorerViewMode.MediumIcons: Scale = ScaleMedium; break; case ExplorerViewMode.SmallIcons: Scale = ScaleSmall; break; default: // Do not set scale in other cases, // because those modes do not affect the scale. break; } } private void SetSliderPosition(double scale) { if (Numeric.IsGreater(scale, ScaleSmall)) { // When scale > 1.0 then update the slider. if (Numeric.IsLessOrEqual(scale, ScaleSmall)) SliderPosition = SliderPositionSmall; else if (Numeric.IsLess(scale, ScaleMedium)) SliderPosition = (scale - 1.25) / 0.25 * 4 + 116; else if (Numeric.AreEqual(scale, ScaleMedium)) SliderPosition = SliderPositionMedium; else if (Numeric.IsLess(scale, ScaleLarge)) SliderPosition = (scale - 3.5) / 0.5 * 4 + 155; else if (Numeric.AreEqual(scale, ScaleLarge)) SliderPosition = SliderPositionLarge; else if (Numeric.IsLess(scale, ScaleExtraLarge)) SliderPosition = (scale - 7) * 4 + 184; else SliderPosition = SliderPositionExtraLarge; } } private void SetSliderPosition(ExplorerViewMode mode) { switch (mode) { case ExplorerViewMode.ExtraLargeIcons: SliderPosition = SliderPositionExtraLarge; break; case ExplorerViewMode.LargeIcons: SliderPosition = SliderPositionLarge; break; case ExplorerViewMode.MediumIcons: SliderPosition = SliderPositionMedium; break; case ExplorerViewMode.SmallIcons: SliderPosition = SliderPositionSmall; break; case ExplorerViewMode.List: SliderPosition = SliderPositionList; break; case ExplorerViewMode.Details: SliderPosition = SliderPositionDetails; break; default: SliderPosition = SliderPositionTiles; break; } } private void SetMode(double sliderPosition) { if (Numeric.IsLess(sliderPosition, SliderPositionDetails)) Mode = ExplorerViewMode.Tiles; else if (Numeric.IsLess(sliderPosition, SliderPositionList)) Mode = ExplorerViewMode.Details; else if (Numeric.IsLess(sliderPosition, SliderPositionSmall)) Mode = ExplorerViewMode.List; else if (Numeric.IsLess(sliderPosition, SliderPositionMedium)) Mode = ExplorerViewMode.SmallIcons; else if (Numeric.IsLess(sliderPosition, SliderPositionLarge)) Mode = ExplorerViewMode.MediumIcons; else if (Numeric.IsLess(sliderPosition, SliderPositionExtraLarge)) Mode = ExplorerViewMode.LargeIcons; else Mode = ExplorerViewMode.ExtraLargeIcons; } #endregion } }
using ordercloud.integrations.library; using OrderCloud.SDK; namespace Headstart.Models.Headstart { [SwaggerModel] public class HSCreditCard: CreditCard<HSCreditCardXP> { } [SwaggerModel] public class HSBuyerCreditCard : BuyerCreditCard<HSCreditCardXP> { } [SwaggerModel] public class HSCreditCardXP { [Required] public Address CCBillingAddress { get; set; } } }
using Warden.Common.Queries; using Warden.Common.Types; namespace Warden.Api.Filters { public interface IFilterResolver { IFilter<TResult, TQuery> Resolve<TResult, TQuery>() where TQuery : IQuery; } }
using System; using System.Collections.Generic; using UnityEngine; public static class SetupUtils { public static GameObject[] PlaceRandomCubes(int count, float radius) { var cubes = new GameObject[count]; var cubeToCopy = MakeStrippedCube(); for (int i = 0; i < count; i++) { var cube = GameObject.Instantiate(cubeToCopy); cube.transform.position = UnityEngine.Random.insideUnitSphere * radius; cubes[i] = cube; } GameObject.Destroy(cubeToCopy); return cubes; } public static GameObject[] PlaceRandomCubes(int count) { var radius = count / 10f; return PlaceRandomCubes(count, radius); } public static GameObject MakeStrippedCube() { var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); //turn off shadows entirely var renderer = cube.GetComponent<MeshRenderer>(); renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; renderer.receiveShadows = false; // disable collision var collider = cube.GetComponent<Collider>(); collider.enabled = false; return cube; } }
namespace AzureBot.Tests { using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// Tests all common commands /// </summary> [TestClass] public class CommonInteractionsTests { [TestMethod] [TestCategory("Parallel")] public async Task ShouldShowHelp() { var testCase = new BotTestCase() { Action = "help", ExpectedReply = "I can help you", }; await TestRunner.RunTestCase(testCase); } [TestMethod] [TestCategory("Parallel")] public async Task ShouldNotifyIfActionIsNotUnderstood() { var message = "I love AzureBot"; var testCase = new BotTestCase() { Action = message, ExpectedReply = $"Sorry, I did not understand '{message}'. Type 'help' if you need assistance.", }; await TestRunner.RunTestCase(testCase); } } }
using KWQuotesApp.Configuration; using KWQuotesApp.Views; using Prism.Commands; using Prism.Mvvm; using Prism.Regions; namespace KWQuotesApp.ViewModels { public class MainWindowViewModel : BindableBase { private string _title = "KW quotes analyser"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private IRegionManager regionManager { get; set; } public MainWindowViewModel(IRegionManager regionManager) { this.regionManager = regionManager; regionManager.RegisterViewWithRegion(RegionsNames.MainRegion, typeof(QuotesPull)); } } }
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Batch.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for IPAddressProvisioningType. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum IPAddressProvisioningType { /// <summary> /// A public IP will be created and managed by Batch. There may be /// multiple public IPs depending on the size of the Pool. /// </summary> [EnumMember(Value = "BatchManaged")] BatchManaged, /// <summary> /// Public IPs are provided by the user and will be used to provision /// the Compute Nodes. /// </summary> [EnumMember(Value = "UserManaged")] UserManaged, /// <summary> /// No public IP Address will be created for the Compute Nodes in the /// Pool. /// </summary> [EnumMember(Value = "NoPublicIPAddresses")] NoPublicIPAddresses } internal static class IPAddressProvisioningTypeEnumExtension { internal static string ToSerializedValue(this IPAddressProvisioningType? value) { return value == null ? null : ((IPAddressProvisioningType)value).ToSerializedValue(); } internal static string ToSerializedValue(this IPAddressProvisioningType value) { switch( value ) { case IPAddressProvisioningType.BatchManaged: return "BatchManaged"; case IPAddressProvisioningType.UserManaged: return "UserManaged"; case IPAddressProvisioningType.NoPublicIPAddresses: return "NoPublicIPAddresses"; } return null; } internal static IPAddressProvisioningType? ParseIPAddressProvisioningType(this string value) { switch( value ) { case "BatchManaged": return IPAddressProvisioningType.BatchManaged; case "UserManaged": return IPAddressProvisioningType.UserManaged; case "NoPublicIPAddresses": return IPAddressProvisioningType.NoPublicIPAddresses; } return null; } } }
using Xunit; namespace XamarinBoilerplate.Droid.Test.Sample { public class SampleXunitTests { [Fact] public void PassedDroidTest() { Assert.True(true); } [Fact(Skip = "Skip this Test")] public void SkippedDroidTest() { Assert.False(true, "We were supposed to skip this!"); } } }
namespace GitExtensions.GitLab { using GitUIPluginInterfaces.RepositoryHosts; using System; using System.Web; internal class GitLabHostedRemote : IHostedRemote { private GitLabRepo repo; public GitLabHostedRemote(string name, string owner, string remoteRepositoryName, string url) { Name = name; Owner = owner; RemoteRepositoryName = remoteRepositoryName; RemoteUrl = url; CloneProtocol = url.IsUrlUsingHttp() ? GitProtocol.Https : GitProtocol.Ssh; GetHostedRepository(); } public IHostedRepository GetHostedRepository() { if (repo == null) { repo = new GitLabRepo(GitLabPlugin.Instance.GitLabClient.GetRepository( HttpUtility.UrlEncode($"{Owner}/{RemoteRepositoryName}"))) { CloneProtocol = CloneProtocol }; } return repo; } public int Id { get { return repo?.Id ?? 0; } } /// <summary> /// Local name of the remote, 'origin' /// </summary> public string Name { get; } /// <summary> /// Owner of the remote repository, in /// git@gitlab.com:ahmeturun/GitLabPlugin.git this is ahmeturun /// </summary> public string Owner { get; } /// <summary> /// Name of the remote repository, in /// git@gitlab.com:ahmeturun/GitLabPlugin.git this is 'GitLabPlugin' /// </summary> public string RemoteRepositoryName { get; } public string RemoteUrl { get; } public GitProtocol CloneProtocol { get; } public string Data => Owner + "/" + RemoteRepositoryName; public string DisplayData => Data; public bool IsOwnedByMe => repo.CanCreateMergeRequestIn; public string GetBlameUrl(string commitHash, string fileName, int lineIndex) { throw new NotImplementedException(); //return $"{GitHub3Plugin.Instance.GitHubEndpoint}/{Data}/blame/{commitHash}/{fileName}#L{lineIndex}"; } } }
using Application.Storage.Interfaces; using Common; using Domain.Interfaces.Entities; using QueryAny; using ServiceStack; using Storage.Properties; namespace Storage { public class GeneralCommandStorage<TEntity> : ICommandStorage<TEntity> where TEntity : IPersistableEntity { private readonly string containerName; private readonly IDomainFactory domainFactory; private readonly IRecorder recorder; private readonly IRepository repository; public GeneralCommandStorage(IRecorder recorder, IDomainFactory domainFactory, IRepository repository) { recorder.GuardAgainstNull(nameof(recorder)); domainFactory.GuardAgainstNull(nameof(domainFactory)); repository.GuardAgainstNull(nameof(repository)); this.recorder = recorder; this.domainFactory = domainFactory; this.repository = repository; this.containerName = typeof(TEntity).GetEntityNameSafe(); } public void Delete(Identifier id, bool destroy = true) { id.GuardAgainstNull(nameof(id)); var entity = this.repository.Retrieve(this.containerName, id, RepositoryEntityMetadata.FromType<TEntity>()); if (entity == null) { return; } if (destroy) { this.repository.Remove(this.containerName, id); this.recorder.TraceDebug("Entity {Id} was destroyed in repository", id); return; } if (entity.IsDeleted.GetValueOrDefault(false)) { return; } entity.IsDeleted = true; this.repository.Replace(this.containerName, id, entity); this.recorder.TraceDebug("Entity {Id} was soft-deleted in repository", id); } public TEntity ResurrectDeleted(Identifier id) { var entity = this.repository.Retrieve(this.containerName, id, RepositoryEntityMetadata.FromType<TEntity>()); if (entity == null) { return default; } if (!entity.IsDeleted.GetValueOrDefault(false)) { return entity.ToDomainEntity<TEntity>(this.domainFactory); } entity.IsDeleted = false; this.repository.Replace(this.containerName, id, entity); this.recorder.TraceDebug("Entity {Id} was resurrected in repository", id); return entity.ToDomainEntity<TEntity>(this.domainFactory); } public TEntity Get(Identifier id, bool includeDeleted = false) { id.GuardAgainstNull(nameof(id)); var entity = this.repository.Retrieve(this.containerName, id, RepositoryEntityMetadata.FromType<TEntity>()); if (entity == null) { return default; } if (entity.IsDeleted.GetValueOrDefault(false) && !includeDeleted) { return default; } this.recorder.TraceDebug("Entity {Id} was retrieved from repository", id); return entity.ToDomainEntity<TEntity>(this.domainFactory); } public TEntity Upsert(TEntity entity, bool includeDeleted = false) { entity.GuardAgainstNull(nameof(entity)); if (!entity.Id.HasValue() || entity.Id.IsEmpty()) { throw new ResourceNotFoundException(Resources.GeneralCommandStorage_EntityMissingIdentifier); } var current = this.repository.Retrieve(this.containerName, entity.Id, RepositoryEntityMetadata.FromType<TEntity>()); if (current == null) { var added = this.repository.Add(this.containerName, CommandEntity.FromDomainEntity(entity)); this.recorder.TraceDebug("Entity {Id} was added to repository", added.Id); return added.ToDomainEntity<TEntity>(this.domainFactory); } if (current.IsDeleted.GetValueOrDefault(false)) { if (!includeDeleted) { throw new ResourceNotFoundException(Resources.GeneralCommandStorage_EntityDeleted); } } var latest = MergeEntity(entity, current); if (current.IsDeleted.GetValueOrDefault(false)) { latest.IsDeleted = false; } var updated = this.repository.Replace(this.containerName, entity.Id, latest); this.recorder.TraceDebug("Entity {Id} was updated in repository", entity.Id); return updated.ToDomainEntity<TEntity>(this.domainFactory); } public long Count() { return this.repository.Count(this.containerName); } public void DestroyAll() { this.repository.DestroyAll(this.containerName); this.recorder.TraceDebug("All entities were deleted from repository"); } private CommandEntity MergeEntity(TEntity updated, CommandEntity persisted) { var persistedAsEntity = persisted.ToDomainEntity<TEntity>(this.domainFactory); persistedAsEntity.PopulateWith(updated); return CommandEntity.FromDomainEntity(persistedAsEntity); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cocos2D { public class CCScale9SpriteFile : CCScale9Sprite { public CCScale9SpriteFile(string file, CCRect rect, CCRect capInsets) { InitWithFile(file, rect, capInsets); } public CCScale9SpriteFile(string file, CCRect rect) { InitWithFile(file, rect); } public CCScale9SpriteFile(CCRect capInsets, string file) { InitWithFile(capInsets, file); } public CCScale9SpriteFile(string file) { InitWithFile(file); } } }
namespace DotNetLocalizer.Core { public class LocalizationOptions { public string ResourcesPath { get; set; } } }
// 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.Collections.Generic; using Xunit; namespace System.Security.Cryptography.Encryption.Tests.Symmetric { public class MinimalTests { [Fact] public static void TestMinimalProperties() { using (Minimal s = new Minimal()) { Assert.Equal(0, s.KeySize); Assert.Equal(0, s.BlockSize); object ignored; Assert.Throws<GenerateKeyNotImplementedException>(() => ignored = s.Key); Assert.Throws<GenerateIvNotImplementedException>(() => ignored = s.IV); Assert.Equal(CipherMode.CBC, s.Mode); Assert.Equal(PaddingMode.PKCS7, s.Padding); // Desktop compat: LegalBlockSizes and LegalKeySizes have to be overridden for these // properties (and the class as a whole) to be of any use. Assert.Throws<NullReferenceException>(() => ignored = s.LegalBlockSizes); Assert.Throws<NullReferenceException>(() => ignored = s.LegalKeySizes); Assert.Throws<NullReferenceException>(() => ignored = s.KeySize = 5); Assert.Throws<NullReferenceException>(() => s.Key = new byte[5]); s.Mode = CipherMode.CBC; Assert.Equal(CipherMode.CBC, s.Mode); s.Mode = CipherMode.ECB; Assert.Equal(CipherMode.ECB, s.Mode); Assert.Throws<CryptographicException>(() => s.Mode = CipherMode.CTS); Assert.Throws<CryptographicException>(() => s.Mode = (CipherMode)12345); Assert.Equal(CipherMode.ECB, s.Mode); s.Padding = PaddingMode.None; Assert.Equal(PaddingMode.None, s.Padding); s.Padding = PaddingMode.Zeros; Assert.Equal(PaddingMode.Zeros, s.Padding); s.Padding = PaddingMode.PKCS7; Assert.Equal(PaddingMode.PKCS7, s.Padding); Assert.Throws<CryptographicException>(() => s.Padding = (PaddingMode)12345); Assert.Equal(PaddingMode.PKCS7, s.Padding); } } private class Minimal : SymmetricAlgorithm { public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw new CreateDecryptorNotImplementedException(); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw new CreateEncryptorNotImplementedException(); } public override void GenerateIV() { throw new GenerateIvNotImplementedException(); } public override void GenerateKey() { throw new GenerateKeyNotImplementedException(); } } private class GenerateIvNotImplementedException : Exception { } private class GenerateKeyNotImplementedException : Exception { } private class CreateDecryptorNotImplementedException : Exception { } private class CreateEncryptorNotImplementedException : Exception { } } }
using System.Collections.Generic; using Pugzor.Core.Helpers; using Xunit; namespace Pugzor.Test { [Trait("Category", "Helper")] public class PathHelperTests { public static IEnumerable<object[]> Paths = new List<object[]> { new object[]{ "/this/is/absolute.pug", true }, new object[]{ "~/this/is/absolute.pug", true }, new object[]{ "this/is/relative.pug", false } }; [Theory] [MemberData(nameof(Paths))] public void PathHelperIsRelativePath_WithPath_ReturnsCorrectValue(string path, bool expectedResult) { Assert.Equal(!expectedResult, PathHelper.IsRelativePath(path)); } [Theory] [MemberData(nameof(Paths))] public void PathHelperIsAbsolutePath_WithPath_ReturnsCorrectValue(string path, bool expectedResult) { Assert.Equal(expectedResult, PathHelper.IsAbsolutePath(path)); } } }
using System; using System.Collections; namespace UnityRayFramework.Runtime { public class SceneUnLoaderTask { readonly Action OnSuccess; readonly Action<float> OnProgess; readonly Action OnFailed; public SceneUnLoaderTask(Action success, Action<float> progess, Action failed) { OnSuccess = success; OnProgess = progess; OnFailed = failed; } public IEnumerator UnLoadScene(string sceneAssetName) { var task = UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync(sceneAssetName); if (task == null) { OnFailed?.Invoke(); } while (!task.isDone) { yield return null; OnProgess?.Invoke(task.progress); } OnSuccess?.Invoke(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using ZeldaWpf.Resources; namespace ZeldaWpf.Controls { /// <summary>An image tree view item that displays a folder.</summary> public class FolderTreeViewItem : ImageTreeViewItem { /// <summary>Constructs the base folder tree view item.</summary> public FolderTreeViewItem(FolderColor color, Orientation orientation) { SourceExpanded = WpfImages.GetFolder(color, orientation, true); SourceCollapsed = WpfImages.GetFolder(color, orientation, false); UpdateExpandedSource(); } /// <summary>Constructs the base folder tree view item.</summary> public FolderTreeViewItem(FolderColor color, Orientation orientation, object header, bool expanded) : base(null, header, expanded) { SourceExpanded = WpfImages.GetFolder(color, orientation, true); SourceCollapsed = WpfImages.GetFolder(color, orientation, false); UpdateExpandedSource(); } } /// <summary>An image tree view item that displays a blue horizontal folder.</summary> public class FolderBlueHTreeViewItem : FolderTreeViewItem { /// <summary>Constructs an empty folder.</summary> public FolderBlueHTreeViewItem() : base(FolderColor.Blue, Orientation.Horizontal) { } /// <summary>Constructs a folder with the name and expanded state.</summary> public FolderBlueHTreeViewItem(object header, bool expanded) : base(FolderColor.Blue, Orientation.Horizontal, header, expanded) { } } /// <summary>An image tree view item that displays a blue vertical folder.</summary> public class FolderBlueVTreeViewItem : FolderTreeViewItem { /// <summary>Constructs an empty folder.</summary> public FolderBlueVTreeViewItem() : base(FolderColor.Blue, Orientation.Vertical) { } /// <summary>Constructs a folder with the name and expanded state.</summary> public FolderBlueVTreeViewItem(object header, bool expanded) : base(FolderColor.Blue, Orientation.Vertical, header, expanded) { } } /// <summary>An image tree view item that displays a manilla horizontal folder.</summary> public class FolderManillaHTreeViewItem : FolderTreeViewItem { /// <summary>Constructs an empty folder.</summary> public FolderManillaHTreeViewItem() : base(FolderColor.Manilla, Orientation.Horizontal) { } /// <summary>Constructs a folder with the name and expanded state.</summary> public FolderManillaHTreeViewItem(object header, bool expanded) : base(FolderColor.Manilla, Orientation.Horizontal, header, expanded) { } } /// <summary>An image tree view item that displays a manilla vertical folder.</summary> public class FolderManillaVTreeViewItem : FolderTreeViewItem { /// <summary>Constructs an empty folder.</summary> public FolderManillaVTreeViewItem() : base(FolderColor.Manilla, Orientation.Vertical) { } /// <summary>Constructs a folder with the name and expanded state.</summary> public FolderManillaVTreeViewItem(object header, bool expanded) : base(FolderColor.Manilla, Orientation.Vertical, header, expanded) { } } }
using System; namespace GoCardless.Exceptions { /// <summary> ///Thrown when a webhook body's signature header does not match the computed ///HMAC of the body. /// </summary> public class InvalidSignatureException : Exception { } }
using System.Collections.Generic; using System.Linq; using CourseLibrary.Api.Entities; using CourseLibrary.Api.Models; namespace CourseLibrary.Api.Services { public class PropertyMappingService : IPropertyMappingService { private readonly IList<IPropertyMapping> _propertyMappings = new List<IPropertyMapping>(); public PropertyMappingService() { _propertyMappings.Add(new PropertyMapping<AuthorDto, Author>(new Dictionary<string, PropertyMappingValue> { ["Id"] = new PropertyMappingValue(new string[] { "Id" }), ["MainCategory"] = new PropertyMappingValue(new string[] { "MainCategory" }), ["Age"] = new PropertyMappingValue(new string[] { "DateOfBirth" }, revert: true), ["Name"] = new PropertyMappingValue(new string[] { "FirstName", "LastName" }), })); } public bool ValidMappingExistsFor<TSource, TDestination>(string fields) { if (string.IsNullOrWhiteSpace(fields)) { return true; } var propertyMapping = GetPropertyMapping<TSource, TDestination>(); return fields.Split(',').Select(it => it.Trim()).All(it => { var indexFirstWhiteSpace = it.IndexOf(" "); var propertyName = indexFirstWhiteSpace == -1 ? it : it.Remove(indexFirstWhiteSpace); return propertyMapping.ContainsKey(propertyName); }); } public IDictionary<string, PropertyMappingValue> GetPropertyMapping<TSource, TDestination>() { return _propertyMappings.OfType<PropertyMapping<TSource, TDestination>>().First().MappingDictionary; } } }
using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Authorization; using Autofac; using Adnc.Infr.Consul; using Adnc.Usr.Application; using Adnc.WebApi.Shared; namespace Adnc.Usr.WebApi { public class Startup { private readonly IConfiguration _configuration; private readonly IWebHostEnvironment _environment; private readonly ServiceInfo _serviceInfo; public Startup(IConfiguration configuration , IWebHostEnvironment environment) { _configuration = configuration; _environment = environment; _serviceInfo = ServiceInfo.Create(Assembly.GetExecutingAssembly()); } public void ConfigureServices(IServiceCollection services) { services.AddAdncServices<PermissionHandlerLocal>(_configuration, _environment, _serviceInfo); } public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterAdncModules<AdncUsrApplicationModule>(_configuration); } public void Configure(IApplicationBuilder app) { app.UseAdncMiddlewares(); if (_environment.IsProduction() || _environment.IsStaging()) { app.RegisterToConsul(); } } } }
using CoinPaprika.Consumer.EndPoints; using CoinPaprika.Consumer.Interfaces; using CoinPaprika.Consumer.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace CoinAPI.Consumer { public class CoinApiClient : ICoinApiClient { private readonly ICoinEndpoint coinEndpoint; public CoinApiClient(ICoinEndpoint coinEndpoint) { this.coinEndpoint = coinEndpoint; } public async Task<IEnumerable<Coin>> GetCoinsAsync() { return await coinEndpoint.GetCoins(); } public async Task<Coin> GetCoinAsync() { return await coinEndpoint.GetCoin(); } } }
// 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.md file in the project root for more information. using Microsoft.VisualStudio.ProjectSystem.VS.Tree.Dependencies; using Moq; namespace Microsoft.VisualStudio.ProjectSystem { internal static class IProjectDependenciesSubTreeProviderFactory { public static IProjectDependenciesSubTreeProvider2 Implement( string? providerType = null, IDependencyModel? createRootDependencyNode = null, MockBehavior mockBehavior = MockBehavior.Strict, ProjectTreeFlags? groupNodeFlags = null) { var mock = new Mock<IProjectDependenciesSubTreeProvider2>(mockBehavior); if (providerType != null) { mock.Setup(x => x.ProviderType).Returns(providerType); } if (createRootDependencyNode != null) { mock.Setup(x => x.CreateRootDependencyNode()).Returns(createRootDependencyNode); } if (groupNodeFlags != null) { mock.SetupGet(x => x.GroupNodeFlag).Returns(groupNodeFlags.Value); } return mock.Object; } } }
using System; namespace Singleton { class Program { static void Main(string[] args) { var singleton = new Singleton(); var policy1 = singleton.GetPolicy(); var policy2 = singleton.GetPolicy(); if(policy1 == policy2) { Console.WriteLine("Singleton Object Created"); } } } public class Singleton { private static readonly Policy _Policy = new Policy(); public Policy GetPolicy() { return _Policy; } } public class Policy { public string Name { get; set; } } }
using LoanManager.Models; using LoanManager.Repo; namespace LoanManager.Service { public interface IMenuPermissionService : IRepository<MenuPermission> { DTResult<MenuPermissionViewModel> GetGrid(DTParameters param,int user,int role); } }
using System; using System.Collections.Generic; using System.Text; namespace refly.Services { public interface IWorldService { void Load(string storyFile); void Create(); void Destroy(); void Map(); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; // para red, UnityWebRequest using Newtonsoft.Json; //JsonConvert using UnityEngine.SceneManagement; /* Muestra el uso de UnityWebRequest para comunicarse con un servidor en la red. Actualiza datos de la partida en la base de datos. Miguel Ángel Pérez López */ public class ActualizarDatos : MonoBehaviour { //Encapsular los datos para convertir f�cilmente a JSON public struct DatosPartida { public string usuarioUsuario; public string nivelNumNivel;//checar con Ari porque public int vidas; public int preguntas; public int intentoPreguntas; public int puntos; public string horaInicioInicioSesion; public string horaFinalInicioSesion; } public DatosPartida datos; public static ActualizarDatos instance; private void Awake() { instance = this; } public void EscribirJson() //Bot�n { //Concurrente StartCoroutine(SubirJson()); } //Parte de este c�digo se ejecuta en paralelo private IEnumerator SubirJson() { var currentScene = SceneManager.GetActiveScene(); var currentSceneName = currentScene.name; string pathRelativo = Application.persistentDataPath + "/usuario.txt"; string texto = System.IO.File.ReadAllText(pathRelativo); datos.usuarioUsuario = texto;//Menu.instance.usuarioTexto.text; datos.nivelNumNivel = currentSceneName; datos.vidas = SaludPersonaje.instance.vidas; datos.preguntas = SaludPersonaje.instance.preguntasCorrectasEdif1; datos.intentoPreguntas = SaludPersonaje.instance.intentoPreguntas; datos.puntos = SaludPersonaje.instance.monedas; datos.horaInicioInicioSesion = "2020-04-04";//Menu.instance.inicioSesion; datos.horaFinalInicioSesion = DateTime.Now.ToString("yyyy-MM-dd"); WWWForm forma = new WWWForm(); forma.AddField("UsuarioUsuario", datos.usuarioUsuario); forma.AddField("NivelNumNivel", datos.nivelNumNivel); forma.AddField("vidas", datos.vidas); forma.AddField("preguntas", datos.preguntas); forma.AddField("intentoPreguntas", datos.intentoPreguntas); forma.AddField("puntos", datos.puntos); forma.AddField("fechaInicio", datos.horaInicioInicioSesion); forma.AddField("fechaFinal", datos.horaFinalInicioSesion); UnityWebRequest request = UnityWebRequest.Post("http://3.17.77.93:8080/usuario/agregarUsuarioNivel", forma); //Aqu� es la bifurcaci�n. yield return request.SendWebRequest(); //Regresa, ejecuta y espera // Ya regres�, se termin� de ejecutar. } }
// <copyright file="IStockService.cs" company="cwkuehl.de"> // Copyright (c) cwkuehl.de. All rights reserved. // </copyright> namespace CSBP.Apis.Services { using System; using System.Collections.Generic; using System.Text; using CSBP.Apis.Models; public interface IStockService { /// <summary> /// Gets a list of stocks. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="inactive">Get also inactive investments?</param> /// <param name="desc">Affected Description.</param> /// <param name="pattern">Affected Pattern.</param> /// <param name="uid">Affected ID.</param> /// <param name="search">Affected text search.</param> /// <returns>List of stocks.</returns> ServiceErgebnis<List<WpWertpapier>> GetStockList(ServiceDaten daten, bool inactive, string desc = null, string pattern = null, string uid = null, string search = null); /// <summary> /// Gets a stock. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <returns>Stock or null.</returns> ServiceErgebnis<WpWertpapier> GetStock(ServiceDaten daten, string uid); /// <summary> /// Saves a stock. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <param name="desc">Affected description.</param> /// <param name="abbreviation">Affected abbreviation.</param> /// <param name="signal1">Affected signal price 1.</param> /// <param name="sort">Affected sorting criteria.</param> /// <param name="source">Affected source.</param> /// <param name="state">Affected state.</param> /// <param name="relationuid">Affected relationuid.</param> /// <param name="memo">Affected memo.</param> /// <param name="type">Affected type.</param> /// <param name="currency">Affected currency.</param> /// <param name="inv">Create also an investment?</param> /// <returns>Created or changed stock.</returns> ServiceErgebnis<WpWertpapier> SaveStock(ServiceDaten daten, string uid, string desc, string abbreviation, decimal? signal1, string sort, string source, string state, string relationuid, string memo, string type = null, string currency = null, bool inv = false); /// <summary> /// Deletes a stock. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="e">Affected entity.</param> /// <returns>Possibly errors.</returns> ServiceErgebnis DeleteStock(ServiceDaten daten, WpWertpapier e); /// <summary> /// Gets a list of states. /// </summary> /// <param name="daten">Service data for database access.</param> /// <returns>List of states.</returns> ServiceErgebnis<List<MaParameter>> GetStateList(ServiceDaten daten); /// <summary> /// Gets a list of providers. /// </summary> /// <param name="daten">Service data for database access.</param> /// <returns>List of providers.</returns> ServiceErgebnis<List<MaParameter>> GetProviderList(ServiceDaten daten); /// <summary> /// Gets a list of configurations. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="extended">Get more data?</param> /// <param name="state">Affected configuration state.</param> /// <returns>List of configurations.</returns> ServiceErgebnis<List<WpKonfiguration>> GetConfigurationList(ServiceDaten daten, bool extended, string state); /// <summary> /// Gets a configuration. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <param name="def">Returns defaults if empty.</param> /// <returns>Configurations or null.</returns> ServiceErgebnis<WpKonfiguration> GetConfiguration(ServiceDaten daten, string uid, bool def = false); /// <summary> /// Saves a configuration. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <param name="desc">Affected description.</param> /// <param name="box">Affected box size.</param> /// <param name="reversal">Affected reversal.</param> /// <param name="method">Affected method.</param> /// <param name="duration">Affected duration.</param> /// <param name="relative">Is it relative Calculation?</param> /// <param name="scale">Affected scale.</param> /// <param name="state">Affected state.</param> /// <param name="memo">Affected memo.</param> /// <returns>Created or changed configuration.</returns> ServiceErgebnis<WpKonfiguration> SaveConfiguration(ServiceDaten daten, string uid, string desc, decimal box, int reversal, int method, int duration, bool relative, int scale, string state, string memo); /// <summary> /// Deletes a configuration. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="e">Affected entity.</param> /// <returns>Possibly errors.</returns> ServiceErgebnis DeleteConfiguration(ServiceDaten daten, WpKonfiguration e); /// <summary> /// Gets a list of scales. /// </summary> /// <param name="daten">Service data for database access.</param> /// <returns>List of scales.</returns> ServiceErgebnis<List<MaParameter>> GetScaleList(ServiceDaten daten); /// <summary> /// Gets a list of PnF methods. /// </summary> /// <param name="daten">Service data for database access.</param> /// <returns>List of PnF methods.</returns> ServiceErgebnis<List<MaParameter>> GetMethodList(ServiceDaten daten); /// <summary> /// Gets a list of prices or rates for a period. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="from">Beginning of the period.</param> /// <param name="to">End of the period.</param> /// <param name="uid">Affected stock uid.</param> /// <param name="relative">Relative prices to relation?</param> /// <returns>List of prices.</returns> ServiceErgebnis<List<SoKurse>> GetPriceList(ServiceDaten daten, DateTime from, DateTime to, string uid, bool relative); /// <summary> /// Gets a list of investments. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="inactive">Get also inactive investments?</param> /// <param name="desc">Affected Description.</param> /// <param name="uid">Affected ID.</param> /// <param name="stuid">Affected stock ID.</param> /// <param name="search">Affected text search.</param> /// <returns>List of investments.</returns> ServiceErgebnis<List<WpAnlage>> GetInvestmentList(ServiceDaten daten, bool inactive, string desc = null, string uid = null, string stuid = null, string search = null); /// <summary> /// Gets an investment. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <returns>Investment or null.</returns> ServiceErgebnis<WpAnlage> GetInvestment(ServiceDaten daten, string uid); /// <summary> /// Saves an investment. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <param name="stuid">Affected stock ID.</param> /// <param name="desc">Affected description.</param> /// <param name="memo">Affected memo.</param> /// <param name="state">Affected state.</param> /// <param name="pfuid">Affected portfolio account ID.</param> /// <param name="smuid">Affected settlement account ID.</param> /// <param name="icuid">Affected income account ID.</param> /// <param name="valuta">Affected value date.</param> /// <param name="value">Affected value.</param> /// <returns>Created or changed investment.</returns> ServiceErgebnis<WpAnlage> SaveInvestment(ServiceDaten daten, string uid, string stuid, string desc, string memo, int state, string pfuid, string smuid, string icuid, DateTime? valuta, decimal value); /// <summary> /// Deletes an investment. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="e">Affected entity.</param> /// <returns>Possibly errors.</returns> ServiceErgebnis DeleteInvestment(ServiceDaten daten, WpAnlage e); /// <summary> /// Calculates all investments. /// </summary> /// <returns>Possibly errors.</returns> /// <param name="daten">Service data for database access.</param> /// <param name="desc">Affected Description.</param> /// <param name="uid">Affected ID.</param> /// <param name="stuid">Affected stock ID.</param> /// <param name="date">Affected date.</param> /// <param name="inactive">Also inactive investmenst?</param> /// <param name="search">Affected text search.</param> /// <param name="status">Status of backup is always updated.</param> /// <param name="cancel">Cancel backup if not empty.</param> ServiceErgebnis CalculateInvestments(ServiceDaten daten, string desc, string uid, string stuid, DateTime date, bool inactive, string search, StringBuilder status, StringBuilder cancel); /// <summary> /// Gets a list of bookings. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="desc">Affected Description.</param> /// <param name="uid">Affected ID.</param> /// <param name="stuid">Affected stock ID.</param> /// <param name="inuid">Affected investment ID.</param> /// <returns>List of bookings.</returns> ServiceErgebnis<List<WpBuchung>> GetBookingList(ServiceDaten daten, string desc = null, string uid = null, string stuid = null, string inuid = null); /// <summary> /// Gets a booking. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <returns>Booking or null.</returns> ServiceErgebnis<WpBuchung> GetBooking(ServiceDaten daten, string uid); /// <summary> /// Gets list of events for an investment. /// </summary> /// <returns>List of events.</returns> /// <param name="daten">Service data for database access.</param> /// <param name="iuid">Affected investment ID.</param> ServiceErgebnis<List<HhEreignis>> GetEventList(ServiceDaten daten, string iuid); /// <summary> /// Saves a booking with optional budget booking. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected ID.</param> /// <param name="inuid">Affected investment ID.</param> /// <param name="date">Affected date.</param> /// <param name="payment">Affected payment.</param> /// <param name="discount">Affected discount.</param> /// <param name="shares">Affected shares.</param> /// <param name="interest">Affected interest.</param> /// <param name="desc">Affected description.</param> /// <param name="memo">Affected memo.</param> /// <param name="price">Affected price.</param> /// <param name="buid">Affected budget booking ID.</param> /// <param name="vd">Affected value date.</param> /// <param name="v">Affected value in EUR.</param> /// <param name="duid">Affected debit account ID.</param> /// <param name="cuid">Affected credit account ID.</param> /// <param name="text">Affected posting text.</param> /// <returns>Created or changed booking.</returns> ServiceErgebnis<WpBuchung> SaveBooking(ServiceDaten daten, string uid, string inuid, DateTime date, decimal payment, decimal discount, decimal shares, decimal interest, string desc, string memo, decimal price, string buid, DateTime vd, decimal v, string duid, string cuid, string text); /// <summary> /// Deletes a booking. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="e">Affected entity.</param> /// <returns>Possibly errors.</returns> ServiceErgebnis DeleteBooking(ServiceDaten daten, WpBuchung e); /// <summary> /// Gets a list of prices. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="uid">Affected stock ID.</param> /// <param name="from">Beginning of the period.</param> /// <param name="to">End of the period.</param> /// <returns>List of prices.</returns> ServiceErgebnis<List<WpStand>> GetPriceList(ServiceDaten daten, string uid = null, DateTime? from = null, DateTime? to = null); /// <summary> /// Gets a price. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="stuid">Affected stock ID.</param> /// <param name="date">Affected date.</param> /// <returns>Price or null.</returns> ServiceErgebnis<WpStand> GetPrice(ServiceDaten daten, string stuid, DateTime date); /// <summary> /// Saves a price. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="stuid">Affected stock ID.</param> /// <param name="date">Affected date.</param> /// <param name="price">Affected price.</param> /// <returns>Created or changed price.</returns> ServiceErgebnis<WpStand> SavePrice(ServiceDaten daten, string stuid, DateTime date, decimal price); /// <summary> /// Deletes a price. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="e">Affected entity.</param> /// <returns>Possibly errors.</returns> ServiceErgebnis DeletePrice(ServiceDaten daten, WpStand e); } }
using EventOrganizer.DAL.DbContext; using EventOrganizer.DAL.Interfaces; using EventOrganizer.DAL.Models; using System; using System.Collections.Generic; using System.Text; namespace EventOrganizer.DAL.Repositories { public class CategoryRepository : ICategoryRepository { private readonly EventOrganizerDbContext _eventOrganizerDbContext; public CategoryRepository(EventOrganizerDbContext eventOrganizerDbContext) { _eventOrganizerDbContext = eventOrganizerDbContext; } public virtual IEnumerable<Category> Categories => _eventOrganizerDbContext.Categories; public virtual void Create(Category item) { _eventOrganizerDbContext.Categories.Add(item); _eventOrganizerDbContext.SaveChanges(); } } }
using UnityEngine; namespace Hecomi.HoloLensPlayground { public class TouchOscUI4 : MonoBehaviour { [Header("Toggle")] [SerializeField] Toggle toggle1; [SerializeField] Toggle toggle2; [SerializeField] Toggle toggle3; [SerializeField] Toggle toggle4; [SerializeField] MultiToggle multitoggle; public void OnMessage(string[] address, Osc.Message msg) { var ui = address[1]; var value = (float)msg.data[0]; switch (ui) { case "toggle1" : toggle1.value = value; break; case "toggle2" : toggle2.value = value; break; case "toggle3" : toggle3.value = value; break; case "toggle4" : toggle4.value = value; break; case "multitoggle" : OnMultiToggleChanged(address, value); break; } } void OnMultiToggleChanged(string[] address, float value) { if (address.Length < 4) return; var y = int.Parse(address[2]) - 1; var x = int.Parse(address[3]) - 1; multitoggle[y, x] = value; } } }
using System.Collections.Generic; using System.Threading.Tasks; using KaLib.Brigadier.Context; namespace KaLib.Brigadier.Suggests { public class SuggestionsBuilder { private readonly string _input; private readonly string _inputLowerCase; private readonly int _start; private readonly string _remaining; private readonly string _remainingLowerCase; private readonly List<Suggestion> _result = new List<Suggestion>(); public SuggestionsBuilder(string input, string inputLowerCase, int start) { this._input = input; this._inputLowerCase = inputLowerCase; this._start = start; #if NETCOREAPP this._remaining = input[start..]; this._remainingLowerCase = inputLowerCase[start..]; #else this._remaining = input.Substring(start); this._remainingLowerCase = inputLowerCase.Substring(start); #endif } public SuggestionsBuilder(string input, int start) : this(input, input.ToLowerInvariant(), start) { } public string GetInput() { return _input; } public int GetStart() { return _start; } public string GetRemaining() { return _remaining; } public string GetRemainingLowerCase() { return _remainingLowerCase; } public Suggestions Build() { return Suggestions.Create(_input, _result); } public async Task<Suggestions> BuildFuture() { await Task.Yield(); return Build(); } public SuggestionsBuilder Suggest(string text) { if (text.Equals(_remaining)) { return this; } _result.Add(new Suggestion(StringRange.Between(_start, _input.Length), text)); return this; } public SuggestionsBuilder Suggest(string text, IMessage tooltip) { if (text.Equals(_remaining)) { return this; } _result.Add(new Suggestion(StringRange.Between(_start, _input.Length), text, tooltip)); return this; } public SuggestionsBuilder Suggest(int value) { _result.Add(new IntegerSuggestion(StringRange.Between(_start, _input.Length), value)); return this; } public SuggestionsBuilder Suggest(int value, IMessage tooltip) { _result.Add(new IntegerSuggestion(StringRange.Between(_start, _input.Length), value, tooltip)); return this; } public SuggestionsBuilder Add(SuggestionsBuilder other) { _result.AddRange(other._result); return this; } public SuggestionsBuilder CreateOffset(int start) { return new SuggestionsBuilder(_input, _inputLowerCase, start); } public SuggestionsBuilder Restart() { return CreateOffset(_start); } } }
// Copyright (c) 2021 Yoakke. // Licensed under the Apache License, Version 2.0. // Source repository: https://github.com/LanguageDev/Yoakke using System.Collections.Generic; namespace Yoakke.Utilities.FiniteAutomata { /// <summary> /// Represents a nondeterministic finite automata that has multiple ways to step on a symbol as /// well as epsilon transitions. /// </summary> /// <typeparam name="TSymbol">The symbol type the automata steps on.</typeparam> public interface INondeterministicFiniteAutomata<TSymbol> : IFiniteAutomata<TSymbol> { /// <summary> /// Retrieves the epsilon-closure of a given state, which is all the states reachable with only /// epsilon transitions. /// </summary> /// <param name="state">The state to calculate the epsilon-closure from.</param> /// <returns>The states of the epsilon-closure.</returns> public IEnumerable<State> EpsilonClosure(State state); /// <summary> /// Determinizes this nondeterministic finite automaton into a deterministic one. /// </summary> /// <returns>The constructed DFA.</returns> public IDeterministicFiniteAutomata<TSymbol> Determinize(); } }
using System; using System.Collections.Generic; using Xms.Business.Filter.Domain; using Xms.Schema.Domain; namespace Xms.Business.Filter { public interface IFilterRuleDependency { bool Create(FilterRule entity); bool Delete(params Guid[] id); List<Schema.Domain.Attribute> GetRequireds(FilterRule entity); bool Update(FilterRule entity); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ASCII_house { // This class is used for storing a 2D Array. There can be only 2 values in the Array 1 or -1. 1 representing // an asterick and -1 representing a blank class Coordinates { private int[,] array; private int maxXCoordinate; private int maxYCoordinate; public Coordinates(int x,int y) { if(x>0 && y>0) { array = new int[x, y]; this.maxXCoordinate = x; this.maxYCoordinate = y; } else { Console.WriteLine("Invalid input"); } } public bool addCoordinates(int x,int y,int value) { if (x > 0 && y > 0 && (value == -1 || value == 1) && x<maxXCoordinate && y<maxYCoordinate) { this.array[x, y] = value; return true; } else return false; } public int getValue(int x,int y) { if (x > 0 && y > 0 && x < maxXCoordinate && y < maxYCoordinate) return array[x, y]; else return 0; } public int getMaxXCoordinate() { return this.maxXCoordinate; } public int getMaxYCoordinate() { return this.maxYCoordinate; } public int[,] getAllCoordinates() { return this.array; } } }
// Copyright (c) 2016 Framefield. All rights reserved. // Released under the MIT license. (see LICENSE.txt) using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Framefield.Core; using Un4seen; using Un4seen.Bass; namespace Framefield.Tooll.Components.Helper { public static class GenerateSoundImage { public static string GenerateSoundSprectrumAndVolume(String soundFilePath) { if ( String.IsNullOrEmpty(soundFilePath) || !File.Exists(soundFilePath)) return null; var imageFilePath = soundFilePath+".waveform.png"; if (File.Exists(imageFilePath)) { Logger.Info("Reusing sound image file: {0}", imageFilePath); return imageFilePath; } Logger.Info("Generating {0}...", imageFilePath); Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_LATENCY, IntPtr.Zero); var stream = Bass.BASS_StreamCreateFile(soundFilePath, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_STREAM_PRESCAN); const int SAMPLING_FREQUENCY = 100; //warning: in TimelineImage this samplingfrequency is assumed to be 100 const double SAMPLING_RESOLUTION = 1.0 / SAMPLING_FREQUENCY; var sampleLength = Bass.BASS_ChannelSeconds2Bytes(stream, SAMPLING_RESOLUTION); var numSamples = Bass.BASS_ChannelGetLength(stream, BASSMode.BASS_POS_BYTES) / sampleLength; Bass.BASS_ChannelPlay(stream, false); const int spectrumLength = 1024; const int imageHeight = 256; var spectrumImage = new Bitmap((int)numSamples, imageHeight); var volumeImage = new Bitmap((int)numSamples, imageHeight); var tempBuffer = new float[spectrumLength]; const float maxIntensity = 500; const int COLOR_STEPS = 255; const int PALETTE_SIZE = 3 * COLOR_STEPS; int a, b, r, g; var palette = new Color[PALETTE_SIZE]; int palettePos; for (palettePos = 0; palettePos < PALETTE_SIZE; ++palettePos) { a = 255; if (palettePos < PALETTE_SIZE * 0.666f) a = (int)(palettePos * 255 / (PALETTE_SIZE * 0.666f)); b = 0; if (palettePos < PALETTE_SIZE * 0.333f) b = palettePos; else if (palettePos < PALETTE_SIZE * 0.666f) b = -palettePos + 510; r = 0; if (palettePos > PALETTE_SIZE * 0.666f) r = 255; else if (palettePos > PALETTE_SIZE * 0.333f) r = palettePos - 255; g = 0; if (palettePos > PALETTE_SIZE * 0.666f) g = palettePos - 510; palette[palettePos] = Color.FromArgb(a, r, g, b); } var f = (float)(spectrumLength / Math.Log((float)(imageHeight + 1))); var f2 = (float)((PALETTE_SIZE - 1) / Math.Log(maxIntensity + 1)); var f3 = (float)((imageHeight - 1) / Math.Log(32768.0f + 1)); for (var sampleIndex = 0; sampleIndex < numSamples; ++sampleIndex) { Bass.BASS_ChannelSetPosition(stream, sampleIndex * sampleLength, BASSMode.BASS_POS_BYTES); Bass.BASS_ChannelGetData(stream, tempBuffer, (int)Un4seen.Bass.BASSData.BASS_DATA_FFT2048); for (var rowIndex = 0; rowIndex < imageHeight; ++rowIndex) { var j_ = (int)(f * Math.Log(rowIndex + 1)); var pj_ = (int)(rowIndex > 0 ? f * Math.Log(rowIndex - 1 + 1) : j_); var nj_ = (int)(rowIndex < imageHeight - 1 ? f * Math.Log(rowIndex + 1 + 1) : j_); float intensity = 125.0f * tempBuffer[spectrumLength - pj_ - 1] + 750.0f * tempBuffer[spectrumLength - j_ - 1] + 125.0f * tempBuffer[spectrumLength - nj_ - 1]; intensity = Math.Min(maxIntensity, intensity); intensity = Math.Max(0.0f, intensity); palettePos = (int)(f2 * Math.Log(intensity + 1)); spectrumImage.SetPixel(sampleIndex, rowIndex, palette[palettePos]); } if (sampleIndex%1000 == 0) { Logger.Info(" computing sound image {0}% complete", (100*sampleIndex/numSamples)); } } spectrumImage.Save(imageFilePath); Bass.BASS_ChannelStop(stream); Bass.BASS_StreamFree(stream); return imageFilePath; } } }
[TaskCategoryAttribute] // RVA: 0x154D20 Offset: 0x154E21 VA: 0x154D20 [TaskDescriptionAttribute] // RVA: 0x154D20 Offset: 0x154E21 VA: 0x154D20 public class GetCenter : Action // TypeDefIndex: 11341 { // Fields [TooltipAttribute] // RVA: 0x191730 Offset: 0x191831 VA: 0x191730 public SharedGameObject targetGameObject; // 0x50 [TooltipAttribute] // RVA: 0x191770 Offset: 0x191871 VA: 0x191770 [RequiredFieldAttribute] // RVA: 0x191770 Offset: 0x191871 VA: 0x191770 public SharedVector3 storeValue; // 0x58 private BoxCollider boxCollider; // 0x60 private GameObject prevGameObject; // 0x68 // Methods // RVA: 0x279B120 Offset: 0x279B221 VA: 0x279B120 Slot: 5 public override void OnStart() { } // RVA: 0x279B220 Offset: 0x279B321 VA: 0x279B220 Slot: 6 public override TaskStatus OnUpdate() { } // RVA: 0x279B310 Offset: 0x279B411 VA: 0x279B310 Slot: 16 public override void OnReset() { } // RVA: 0x279B3A0 Offset: 0x279B4A1 VA: 0x279B3A0 public void .ctor() { } }
using System; using System.Collections.Generic; using System.Dynamic; using System.IO; using HandlebarsDotNet; using HandlebarsDotNet.Compiler; using Sitegen.Models.Config; namespace Sitegen.Services { /// <summary> /// Converts Handlebars (`.hbs`) content to HTML (`.html`) /// </summary> public class HandlebarsConverter { private readonly IHandlebars handlebars; private readonly TopLevelConfig topLevelConfig; private Config Config => topLevelConfig.Config; public HandlebarsConverter(TopLevelConfig topLevelConfig) { this.topLevelConfig = topLevelConfig; handlebars = Handlebars.Create(); handlebars.RegisterHelper("include", IncludeHelper); handlebars.RegisterHelper("markdown", MarkdownHelper); handlebars.RegisterHelper("set", SetHelper); handlebars.RegisterHelper("ifeq", IfEqHelper); } public string Convert(string source, IDictionary<string, object> extraData = null) { var template = handlebars.Compile(source); var data = new ExpandoObject() as IDictionary<string, object>; data.Add("now", DateTime.Now); data.Add("site", topLevelConfig.Site); foreach ((string key, object value) in extraData ?? new Dictionary<string, object>()) { data.Add(key, value); } return template(data); } private void IncludeHelper(TextWriter writer, dynamic context, object[] parameters) { if (parameters.Length != 1) { throw new HandlebarsException("{{include}} helper must have exactly one argument"); } if (!(parameters[0] is string fileName)) { throw new HandlebarsException("{{include}} expected string parameter, not " + parameters[0].GetType().Name); } string templateSource = File.ReadAllText(Path.Join(Config.SourceDir, fileName)); var template = handlebars.Compile(templateSource); string result = template(context); writer.WriteSafeString(result); } private void MarkdownHelper(TextWriter writer, HelperOptions options, dynamic context, object[] arguments) { var stringWriter = new StringWriter(); options.Template(stringWriter, context); string html = MarkdownConverter.ToHtml(stringWriter.ToString(), topLevelConfig.Config.LineBreaks); writer.WriteSafeString(html); } private static void SetHelper(TextWriter writer, dynamic dynamicContext, object[] parameters) { var context = (IDictionary<string, object>) dynamicContext; if (parameters.Length == 0) { throw new HandlebarsException("{{set}} helper must have at least one argument"); } foreach (object parameter in parameters) { if (!(parameter is HashParameterDictionary dictionary)) { throw new HandlebarsException("{{set}} parameter must use key=value notation"); } foreach ((string key, object value) in dictionary) { context.Add(key, value); } } } /// <summary> /// `{{#ifeq}}` block helper. /// /// Use like this: /// /// ``` /// {{#ifeq language 'foo'}} /// Content shown if the variable equals 'foo' /// {{/else}} /// Optional content shown if the comparison is not true. /// {{/ifeq}} /// ``` /// </summary> /// <param name="output">The TextWriter to write the output to.</param> /// <param name="options">The HelperOptions to use.</param> /// <param name="context">The context, where parameters can have been defined.</param> /// <param name="arguments">The arguments, as provided in the Handlebars source file.</param> /// <exception cref="HandlebarsException">If the number of arguments does not equal two.</exception> private static void IfEqHelper(TextWriter output, HelperOptions options, dynamic context, object[] arguments) { if (arguments.Length != 2) { throw new HandlebarsException("{{ifeq}} helper must have exactly two arguments"); } var left = arguments[0] as string; var right = arguments[1] as string; if (left == right) { options.Template(output, context); } else { options.Inverse(output, context); } } } }
using UnityEngine; namespace UniFlow.Connector.ValueComparer { [AddComponentMenu("UniFlow/ValueComparer/BoolComparer", (int) ConnectorType.ValueComparerBool)] public class BoolComparer : ComparerBase<bool, BoolCollector> { protected override bool Compare(bool actual) { return Expect == actual; } } }
namespace _02_DirectoryTraverser { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Program { static void Main() { ExeFinder finder = new ExeFinder(); finder.GetSubDirectories(@"D:"); } } }
/******************************************************************** created: 2015/08/19 created: 19:8:2015 11:17 filename: MD5Hash.cs file path: Assets\Code\FrameWork\Dipper file base: MD5Hash file ext: cs author: 来自网络,表示感谢 purpose: *********************************************************************/ using System; using System.IO; using System.Security.Cryptography; using System.Text; public static class MD5Hash { static StringBuilder stringBuilder; public static string Get(string input) { return Get(Encoding.Default.GetBytes(input)); } public static string Get(byte[] input) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(input); if (stringBuilder == null) { stringBuilder = new StringBuilder(); } stringBuilder.Remove(0, stringBuilder.Length); for (int i = 0; i < data.Length; ++i) stringBuilder.Append(data[i].ToString("x2")); string md5 = stringBuilder.ToString(); stringBuilder.Remove(0, stringBuilder.Length); return md5; } public static string Get(Stream stream) { //MD5 md5 = MD5.Create(); MD5 md5Hasher = new MD5CryptoServiceProvider(); byte[] data = md5Hasher.ComputeHash(stream); if (stringBuilder == null) { stringBuilder = new StringBuilder(); } stringBuilder.Remove(0, stringBuilder.Length); for (int i = 0; i < data.Length; ++i) stringBuilder.Append(data[i].ToString("x2")); string md5 = stringBuilder.ToString(); stringBuilder.Remove(0, stringBuilder.Length); return md5; } public static bool Verify(string input, string hash) { string hashOfInput = Get(input); StringComparer comparer = StringComparer.OrdinalIgnoreCase; return (0 == comparer.Compare(hashOfInput, hash)); } public static bool Verify(byte[] input, string hash) { string hashOfInput = Get(input); StringComparer comparer = StringComparer.OrdinalIgnoreCase; return (0 == comparer.Compare(hashOfInput, hash)); } public static bool Verify(Stream input, string hash) { string hashOfInput = Get(input); StringComparer comparer = StringComparer.OrdinalIgnoreCase; return (0 == comparer.Compare(hashOfInput, hash)); } }
namespace Frigg { using System; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public abstract class ConditionAttribute : Attribute, IAttribute { public EConditionType ConditionType { get; } public string MemberName { get; } public string Expression { get; } public bool ExpectedValue { get; private set; } protected ConditionAttribute(string expression) { this.Expression = expression; this.ConditionType = EConditionType.ByExpression; } protected ConditionAttribute(string memberName, bool expectedValue) { this.ConditionType = EConditionType.ByCondition; this.MemberName = memberName; this.ExpectedValue = expectedValue; } } public enum EConditionType { ByExpression = 0, ByCondition = 1 } }
using GoodToCode.Shared.Domain; using System; namespace GoodToCode.Subjects.Models { public interface IPerson : IDomainEntity<IPerson> { DateTime BirthDate { get; set; } string FirstName { get; set; } string GenderCode { get; set; } string LastName { get; set; } string MiddleName { get; set; } Guid PersonKey { get; set; } } }
using System.Net.Sockets; namespace Tcp.Core { public static class TcpNetOperationExtensions { public static bool IsConnected(this Socket socket) { return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Mvp.Project.MvpSite.Configuration { public class SitecoreOptions { public static readonly string Key = "Sitecore"; public Uri InstanceUri { get; set; } public string LayoutServicePath { get; set; } = "/sitecore/api/layout/render/jss"; public string DefaultSiteName { get; set; } public string ApiKey { get; set; } public Uri RenderingHostUri { get; set; } public bool EnableExperienceEditor { get; set; } public Dictionary<string, string> Sites { get; set; } public Uri LayoutServiceUri { get { if (InstanceUri == null) return null; return new Uri(InstanceUri, LayoutServicePath); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [System.Serializable] public enum RotationDirections { CW,CCW } public class RotateEventArgs : EventArgs { public Touch Finger1 { get; private set; } public Touch Finger2 { get; private set; } public float Angle { get; private set; } public RotationDirections RotationDirection { get; private set; } public GameObject HitObject { get; private set; } public RotateEventArgs(Touch f1, Touch f2, float A, RotationDirections dir, GameObject obj) { Finger1 = f1; Finger2 = f2; Angle = A; RotationDirection = dir; HitObject = obj; } }
namespace Palmmedia.GitHistory2Yuml.Core { /// <summary> /// Interface to create Yuml graphs from GIT History. /// </summary> public interface IYumlGraphBuilder { /// <summary> /// Creates the Yuml graph. /// </summary> /// <param name="directory">The directory.</param> /// <returns>The Yuml graph.</returns> string CreateYumlGraph(string directory); /// <summary> /// Creates the merged Yuml graph. /// </summary> /// <param name="directory">The directory.</param> /// <returns>The merged Yuml graph.</returns> string CreateMergedYumlGraph(string directory); } }
using UnityEngine; public class EmptyScript : MonoBehaviour { // Проверочный пустой скрипт для проверки живых MonoBehaviour // Test empty script for checking alive MonoBehaviours up }
using System; using System.Windows.Forms; namespace FontConv { class Util { static public void Error(Exception ex_) { MessageBox.Show(ex_.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); } } }
using System.Collections.Generic; namespace Net6_RabbitMQ.Consumer { public class MessageReceivedArgs { public IDictionary<string, object> MessageHeaders { get; } public string ConsumerTag { get; } public ulong DeliveryTag { get; } public string Exchange { get; } public bool Redelivered { get; } public string RoutingKey { get;} public int RetryCount { get; } internal MessageReceivedArgs(IDictionary<string, object> messageHeaders, string consumerTag, ulong deliveryTag, string exchange, bool redelivered, string routingKey, int retryCount) { MessageHeaders = messageHeaders; ConsumerTag = consumerTag; DeliveryTag = deliveryTag; Exchange = exchange; Redelivered = redelivered; RoutingKey = routingKey; RetryCount = retryCount; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Threading.Channels; using Microsoft.Azure.Functions.Worker.Grpc.Messages; namespace Microsoft.Azure.Functions.Worker { internal class GrpcHostChannel { public GrpcHostChannel(Channel<StreamingMessage> channel) { Channel = channel ?? throw new ArgumentNullException(nameof(channel)); } public Channel<StreamingMessage> Channel { get; } } }
using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace DotNetRu.Azure { public static class StringExtensions { internal static string ConvertToUsualUrl(this string input, List<KeyValuePair<string, string>> replacements) { var returnString = new StringBuilder(input); foreach (var replacement in replacements) { returnString.Replace(replacement.Key, replacement.Value); } return Regex.Replace(returnString.ToString(), @"https:\/\/t\.co\/.+$", string.Empty); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace KPreisser { /// <summary> /// Contains extension methods for <see cref="AsyncReaderWriterLockSlim"/>. /// </summary> public static class AsyncReaderWriterLockSlimExtension { /// <summary> /// Enters the lock in read mode. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed.</returns> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static IDisposableLock GetReadLock( this AsyncReaderWriterLockSlim lockInstance, CancellationToken cancellationToken = default(CancellationToken)) { lockInstance.EnterReadLock(cancellationToken); return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false); } /// <summary> /// Asynchronously enters the lock in read mode and returns a <see cref="IDisposableLock"/> that /// will release the lock when disposed. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>A task that will complete with a <see cref="IDisposableLock"/> when the lock has been entered, /// which will release the lock when disposed.</returns> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static async Task<IDisposableLock> GetReadLockAsync( this AsyncReaderWriterLockSlim lockInstance, CancellationToken cancellationToken = default(CancellationToken)) { await lockInstance.EnterReadLockAsync(cancellationToken); return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false); } /// <summary> /// Tries to enter the lock in read mode, with an optional integer time-out. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 /// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed if the lock /// could be entered, or <c>null</c> otherwise.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number /// other than -1, which represents an infinite time-out.</exception> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static IDisposableLock TryGetReadLock( this AsyncReaderWriterLockSlim lockInstance, int millisecondsTimeout, CancellationToken cancellationToken = default(CancellationToken)) { bool returnValue = lockInstance.TryEnterReadLock( millisecondsTimeout, cancellationToken); if (returnValue) return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false); else return null; } /// <summary> /// Tries to asynchronously enter the lock in read mode, with an optional integer time-out. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 /// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>A task that will complete with a <see cref="IDisposableLock"/> that will release the lock /// when disposed if the lock could be entered, or with <c>null</c> otherwise.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number /// other than -1, which represents an infinite time-out.</exception> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static async Task<IDisposableLock> TryGetReadLockAsync( this AsyncReaderWriterLockSlim lockInstance, int millisecondsTimeout, CancellationToken cancellationToken = default(CancellationToken)) { bool returnValue = await lockInstance.TryEnterReadLockAsync( millisecondsTimeout, cancellationToken); if (returnValue) return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false); else return null; } /// <summary> /// Enters the lock in write mode. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed.</returns> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static IDisposableLock GetWriteLock( this AsyncReaderWriterLockSlim lockInstance, CancellationToken cancellationToken = default(CancellationToken)) { lockInstance.EnterWriteLock(cancellationToken); return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true); } /// <summary> /// Asynchronously enters the lock in write mode. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>>A task that will complete with a <see cref="IDisposableLock"/> when the lock has been entered, /// which will release the lock when disposed.</returns> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static async Task<IDisposableLock> GetWriteLockAsync( this AsyncReaderWriterLockSlim lockInstance, CancellationToken cancellationToken = default(CancellationToken)) { await lockInstance.EnterWriteLockAsync(cancellationToken); return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true); } /// <summary> /// Tries to enter the lock in write mode, with an optional integer time-out. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 /// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed if the lock /// could be entered, or <c>null</c> otherwise.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number /// other than -1, which represents an infinite time-out.</exception> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static IDisposableLock TryGetWriteLock( this AsyncReaderWriterLockSlim lockInstance, int millisecondsTimeout, CancellationToken cancellationToken = default(CancellationToken)) { bool returnValue = lockInstance.TryEnterWriteLock( millisecondsTimeout, cancellationToken); if (returnValue) return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true); else return null; } /// <summary> /// Tries to asynchronously enter the lock in write mode, with an optional integer time-out. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 /// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param> /// <returns>>A task that will complete with a <see cref="IDisposableLock"/> that will release the lock /// when disposed if the lock could be entered, or with <c>null</c> otherwise.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number /// other than -1, which represents an infinite time-out.</exception> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static async Task<IDisposableLock> TryGetWriteLockAsync( this AsyncReaderWriterLockSlim lockInstance, int millisecondsTimeout, CancellationToken cancellationToken = default(CancellationToken)) { bool returnValue = await lockInstance.TryEnterWriteLockAsync( millisecondsTimeout, cancellationToken); if (returnValue) return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true); else return null; } /// <summary> /// Downgrades the lock from write mode to read mode. /// </summary> /// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param> /// <param name="readLock">The <see cref="IDisposableLock"/> which should be downgraded.</param> /// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception> public static void DowngradeWriteLockToReadLock( this AsyncReaderWriterLockSlim lockInstance, IDisposableLock readLock) { if (readLock == null) throw new ArgumentNullException(nameof(readLock)); var myReadLock = readLock as ActionDisposableLock; if (myReadLock == null || myReadLock.LockOrigin != lockInstance || !myReadLock.IsWriteLock || myReadLock.IsDisposed) throw new ArgumentException(); // Downgrade the lock. lockInstance.DowngradeWriteLockToReadLock(); // Now mark the lock as being a read lock. myReadLock.IsWriteLock = false; } /// <summary> /// /// </summary> public interface IDisposableLock : IDisposable { } private class ActionDisposableLock : IDisposableLock { private readonly Action action; private readonly AsyncReaderWriterLockSlim lockOrigin; private bool isWriteLock; private bool isDisposed; public ActionDisposableLock( Action action, AsyncReaderWriterLockSlim lockOrigin, bool isWriteLock) { this.action = action; this.lockOrigin = lockOrigin; this.isWriteLock = isWriteLock; } ~ActionDisposableLock() { Dispose(false); } public AsyncReaderWriterLockSlim LockOrigin => this.lockOrigin; public bool IsWriteLock { get => this.isWriteLock; set => this.isWriteLock = value; } public bool IsDisposed => this.isDisposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { this.action(); } this.isDisposed = true; } } } } }
#region License // Copyright 2009-2015 Buu Nguyen // // 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. // // The latest version of this file can be found at https://github.com/buunguyen/combres #endregion using System.Collections.Generic; using System.Linq; namespace Combres.VersionGenerators { /// <summary> /// Use the inherent <c>GetHashCode()</c> on all contributing change factors (resources' contents/mode/cookie/minifier and /// resource set's applied filters/debug-enabled) to generate version string. /// </summary> /// <remarks>Resulted version string has the form of an integer. It doesn't /// guarantee no collision for 2 different resource sets. /// </remarks> public sealed class HashCodeVersionGenerator : IVersionGenerator { private static readonly ILogger Log = LoggerFactory.CreateLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <inheritdoc cref="IVersionGenerator.Generate" /> public string Generate(ResourceSet rs) { if (Log.IsDebugEnabled) Log.Debug("Computing hash for set " + rs.Name + ". Current hash: " + rs.Hash); var contributingFactors = new List<object> {rs.DebugEnabled}; rs.Filters.ToList().ForEach(contributingFactors.Add); rs.CacheVaryProviders.ToList().ForEach(contributingFactors.Add); rs.Resources.ToList().ForEach(r => { contributingFactors.Add(r.ReadFromCache(true)); contributingFactors.Add(r.ForwardCookie); contributingFactors.Add(r.Mode); contributingFactors.Add(r.Minifier); }); var hash = contributingFactors.Select(f => f.GetHashCode()) .Aggregate(17, (accum, element) => 31 * accum + element) .ToString(); if (Log.IsDebugEnabled) Log.Debug("New hash: " + hash); return hash; } } }
namespace MassTransit.KafkaIntegration.Tests { using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Confluent.Kafka; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NUnit.Framework; using TestFramework; public class HealthCheck_Specs : InMemoryTestFixture { [Test] public async Task Should_be_healthy() { var services = new ServiceCollection(); services.TryAddSingleton<ILoggerFactory>(LoggerFactory); services.TryAddSingleton(typeof(ILogger<>), typeof(Logger<>)); services.AddMassTransit(x => { x.UsingInMemory((context, cfg) => cfg.ConfigureEndpoints(context)); x.AddRider(rider => { rider.UsingKafka((context, k) => { k.Host("localhost:9092"); k.TopicEndpoint<Null, Ignore>("test", nameof(HealthCheck_Specs), c => { }); }); }); }); var provider = services.BuildServiceProvider(); var healthCheckService = provider.GetRequiredService<HealthCheckService>(); IEnumerable<IHostedService> hostedServices = provider.GetServices<IHostedService>().ToArray(); await healthCheckService.WaitForHealthStatus(HealthStatus.Unhealthy); try { await Task.WhenAll(hostedServices.Select(x => x.StartAsync(TestCancellationToken))); await healthCheckService.WaitForHealthStatus(HealthStatus.Healthy); } finally { await Task.WhenAll(hostedServices.Select(x => x.StopAsync(TestCancellationToken))); await provider.DisposeAsync(); } } } }
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using K4W.KinectVOD.Client.WinStore.Common; using K4W.KinectVOD.Shared; namespace K4W.KinectVOD.Client.WinStore.Pages { public sealed partial class VideoPage : Page { private ObservableDictionary defaultViewModel = new ObservableDictionary(); public ObservableDictionary DefaultViewModel { get { return this.defaultViewModel; } } public VideoPage() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { defaultViewModel["RecordingData"] = (e.Parameter) as RecordingData; } /// <summary> /// Return back to the global overview /// </summary> private void OnBackButtonClick(object sender, Windows.UI.Xaml.RoutedEventArgs e) { this.Frame.Navigate(typeof (MainPage)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using XenGameBase; using Microsoft.Xna.Framework; using Xen2D; namespace Demo_FarseerPlugin { class SquareElement : ComplexElement2D<SquareElement> { public static SquareElement Acquire( Vector2 position ) { var instance = _pool.Acquire(); instance.RenderingExtent.Anchor = position; return instance; } private StaticSprite _sprite = StaticSprite.Acquire( Textures.Get( TexId.Square ) ); public override void Reset() { //Note: always set Visual Component, then base.ResetDirectState() VisualComponents.Add( _sprite ); base.Reset(); CollisionClass = CollisionClasses.Default; } } }
using MyGeotabAPIAdapter.Database.Models; namespace MyGeotabAPIAdapter.Database { /// <summary> /// Interface for a class that lists names of objects (e.g. tables, views, etc.) in the Adapter database. /// </summary> public interface IAdapterDatabaseObjectNames { /// <summary> /// The nickname of the Adapter database. For use in logging. /// </summary> string AdapterDatabaseNickname { get; } /// <summary> /// The name of the database table associated with <see cref="DbBinaryData"/> entities. /// </summary> string DbBinaryDataTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbConfigFeedVersion"/> entities. /// </summary> string DbConfigFeedVersionsTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDevice"/> entities. /// </summary> string DbDeviceTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDiagnostic"/> entities. /// </summary> string DbDiagnosticTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDriverChange"/> entities. /// </summary> string DbDriverChangeTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDutyStatusAvailability"/> entities. /// </summary> string DbDutyStatusAvailabilityTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDVIRDefect"/> entities. /// </summary> string DbDVIRDefectTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDVIRDefectRemark"/> entities. /// </summary> string DbDVIRDefectRemarkTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDVIRDefectUpdate"/> entities. /// </summary> string DbDVIRDefectUpdatesTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbDVIRLog"/> entities. /// </summary> string DbDVIRLogTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbExceptionEvent"/> entities. /// </summary> string DbExceptionEventTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbFailedDVIRDefectUpdate"/> entities. /// </summary> string DbFailedDVIRDefectUpdatesTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbFaultData"/> entities. /// </summary> string DbFaultDataTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbLogRecord"/> entities. /// </summary> string DbLogRecordTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbRule"/> entities. /// </summary> string DbRuleTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbStatusData"/> entities. /// </summary> string DbStatusDataTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbTrip"/> entities. /// </summary> string DbTripTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbUser"/> entities. /// </summary> string DbUserTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbZone"/> entities. /// </summary> string DbZoneTableName { get; } /// <summary> /// The name of the database table associated with <see cref="DbZoneType"/> entities. /// </summary> string DbZoneTypeTableName { get; } } }
using Base.Services; using BaseWeb.Models; using BaseWeb.Services; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc; namespace BaseWeb.ViewComponents { //配合 _xp.js public class XgThViewComponent : ViewComponent { /// <summary> /// table th /// </summary> /// <param name="helper"></param> /// <param name="title">prog path list</param> /// <param name="tip"></param> /// <param name="required"></param> /// <returns></returns> public HtmlString Invoke(XgThDto dto) { var title = _Helper.GetRequiredSpan(dto.Required) + dto.Title; var html = (dto.Tip == "") ? "<th{0}>" + title + "</th>" : "<th{0} title='" + dto.Tip + "'>" + title + "<i class='ico-info'></i></th>"; var extClass = _Str.IsEmpty(dto.ExtClass) ? "" : " class='" + dto.ExtClass + "'"; return new HtmlString(string.Format(html, extClass)); } } //class }
using NUnit.Framework; namespace Sentry.Unity.iOS.Tests { public class SentryNativeIosTests { [Test] public void Configure_DefaultConfiguration_SetsScopeObserver() { var options = new SentryUnityOptions(); SentryNativeIos.Configure(options); Assert.IsAssignableFrom<IosNativeScopeObserver>(options.ScopeObserver); } [Test] public void Configure_NativeIosSupportDisabled_ObserverIsNull() { var options = new SentryUnityOptions { IosNativeSupportEnabled = false }; SentryNativeIos.Configure(options); Assert.Null(options.ScopeObserver); } [Test] public void Configure_DefaultConfiguration_EnablesScopeSync() { var options = new SentryUnityOptions(); SentryNativeIos.Configure(options); Assert.True(options.EnableScopeSync); } [Test] public void Configure_NativeIosSupportDisabled_DisabledScopeSync() { var options = new SentryUnityOptions { IosNativeSupportEnabled = false }; SentryNativeIos.Configure(options); Assert.False(options.EnableScopeSync); } } }
 using System; using Xamarin.Forms; using XamFormsReactiveUI.ValueConverters; namespace XamFormsReactiveUI.Views { public class Badge : AbsoluteLayout { /// <summary> /// The text property. /// </summary> public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(String), typeof(Badge), ""); /// <summary> /// The box color property. /// </summary> public static readonly BindableProperty BoxColorProperty = BindableProperty.Create("BoxColor", typeof(Color), typeof(Badge), Color.Default); /// <summary> /// The text. /// </summary> public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } /// <summary> /// Gets or sets the color of the box. /// </summary> public Color BoxColor { get { return (Color)GetValue(BoxColorProperty); } set { SetValue(BoxColorProperty, value); } } /// <summary> /// The box. /// </summary> protected RoundedBox Box; /// <summary> /// The label. /// </summary> protected Label Label; /// <summary> /// Initializes a new instance of the <see cref="Badge"/> class. /// </summary> public Badge(double size, double fontSize) { HeightRequest = size; WidthRequest = HeightRequest; // Box Box = new RoundedBox { CornerRadius = HeightRequest / 2 }; Box.SetBinding(BackgroundColorProperty, new Binding("BoxColor", source: this)); Children.Add(Box, new Rectangle(0, 0, 1.0, 1.0), AbsoluteLayoutFlags.All); // Label Label = new Label { TextColor = Color.White, FontSize = fontSize, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center }; Label.SetBinding(Label.TextProperty, new Binding("Text", BindingMode.OneWay, source: this)); Children.Add(Label, new Rectangle(0, 0, 1.0, 1.0), AbsoluteLayoutFlags.All); // Auto-width SetBinding(WidthRequestProperty, new Binding("Text", BindingMode.OneWay, new BadgeWidthConverter(WidthRequest), source: this)); // Hide if no value SetBinding(IsVisibleProperty, new Binding("Text", BindingMode.OneWay, new BadgeVisibleValueConverter(), source: this)); // Default color BoxColor = Color.Red; } } }
using Commands.CodeBaseSearch.Extensions; using Commands.CodeBaseSearch.Model; using Commands.CodeBaseSearch.Model.Subjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Commands.CodeBaseSearch.Conditions { public class AttributeNameTemplateCondition : BaseTemplateCondition<ISubject> { public override bool IsMet(ISubject value) { if (value.Type != SubjectTypeEnum.Type) { return false; } switch (value) { case ClassTypeSubject classType: return CheckBaseType(classType.ClassDeclaration.AttributeLists); case InterfaceTypeSubject interfaceType: return CheckBaseType(interfaceType.InterfaceDeclaration.AttributeLists); case StructTypeSubject structType: return CheckBaseType(structType.StructDeclaration.AttributeLists); default: return false; } } private bool CheckBaseType(SyntaxList<AttributeListSyntax> attributeList) { foreach (AttributeListSyntax attributeListSyntax in attributeList) foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) { if (regex.Value.IsMatch(attributeSyntax.Name.GetTypeName())) { return true; } } return false; } } }
using System; using System.Collections.Generic; using System.Text; using MinorShift.Emuera.GameData.Expression; using MinorShift.Emuera.GameData; namespace MinorShift.Emuera.Sub { enum LexEndWith { //いずれにせよEoLで強制終了 None = 0, EoL,//常に最後まで解析 Operator,//演算子を見つけたら終了。代入式の左辺 Question,//三項演算子?により終了。\@~~?~~#~~\@ Percent,//%により終了。%~~% RightCurlyBrace,//}により終了。{~~} Comma,//,により終了。TIMES第一引数 //Single,//Identifier一つで終了//1807 Single削除 GreaterThan,//'>'により終了。Htmlタグ解析 } enum FormStrEndWith { //いずれにせよEoLで強制終了 None = 0, EoL,//常に最後まで解析 DoubleQuotation,//"で終了。@"~~" Sharp,//#で終了。\@~~?~~#~~\@ の一つ目 YenAt,//\@で終了。\@~~?~~#~~\@ の二つ目 Comma,//,により終了。ANY_FORM引数 LeftParenthesis_Bracket_Comma_Semicolon,//[または(または,または;により終了。CALLFORM系の関数名部分。 } enum StrEndWith { //いずれにせよEoLで強制終了 None = 0, EoL,//常に最後まで解析 SingleQuotation,//"で終了。'~~' DoubleQuotation,//"で終了。"~~" Comma,//,により終了。PRINTV'~~, LeftParenthesis_Bracket_Comma_Semicolon,//[または(または,または;により終了。関数名部分。 } enum LexAnalyzeFlag { None = 0, AnalyzePrintV = 1,//PRINTVの引数で'に続けて文字列を書くと数式ではないが文字列として表示される AllowAssignment = 2,//代入演算子が使用できる場面であるFlag。このFlagなしで=が途中に出てきたらエラー AllowSingleQuotationStr = 4,//HTML_PRINT解析用。''で囲まれた文字列を許可する。 } /// <summary> /// 1756 TokenReaderより改名 /// Lexicalといいつつ構文解析を含む /// </summary> internal static class LexicalAnalyzer { const int MAX_EXPAND_MACRO = 100; //readonly static IList<char> operators = new char[] { '+', '-', '*', '/', '%', '=', '!', '<', '>', '|', '&', '^', '~', '?', '#' }; //readonly static IList<char> whiteSpaces = new char[] { ' ', ' ', '\t' }; //readonly static IList<char> endOfExpression = new char[] { ')', '}', ']', ',', ':' }; //readonly static IList<char> startOfExpression = new char[] { '(' }; //readonly static IList<char> stringToken = new char[] { '\"', }; //readonly static IList<char> stringFormToken = new char[] { '@', }; //readonly static IList<char> etcSymbol = new char[] { '[', '{', '$', '\\', }; //readonly static IList<char> decimalDigits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; readonly static IList<char> hexadecimalDigits = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' }; //1819 正規表現使うとやや遅い。いずれdoubleにも対応させたい。そのうち考える //readonly static Regex DigitsReg = new Regex("" + // "(" + // "((?<simple>[-]?[0-9]+)([^.xXbBeEpP]|$))" + // "|(" + // "(0(x|X)(?<hex>[0-9a-fA-F]+))|"+ // "(0(b|B)(?<bin>[01]+))|"+ // "(" + //base10 // "(?<integer>[-]?[0-9]*(?<double>[.][0-9])?)" + // "(((p|P)(?<exp2>[0-9]+))|" + // "((e|E)(?<exp10>[0-9]+)))?" + // ")"+ // "))" // , RegexOptions.Compiled); //readonly static Regex idReg = new Regex(@"[^][ \t+*/%=!<>|&^~?#(){},:$\\'""@.; -]+", RegexOptions.Compiled); //public static Int64 ReadInt64(StringStream st, bool retZero) //{ // Match m = DigitsReg.Match(st.RowString, st.CurrentPosition); // string numstr = m.Groups["simple"].Value; // if (numstr.Length > 0) // { // st.Jump(numstr.Length); // return Convert.ToInt64(numstr, 10); // } // st.Jump(m.Length); // if (m.Groups["bin"].Length > 0) // return Convert.ToInt64(m.Groups["bin"].Value, 2); // if(m.Groups["hex"].Length > 0) // return Convert.ToInt64(m.Groups["hex"].Value, 16); // numstr = m.Groups["number"].Value; // if (numstr.Length > 0) // { // int exp = 0; // string exp2 = m.Groups["exp2"].Value; // string exp10 = m.Groups["exp10"].Value; // if(m.Groups["double"].Length == 0 && exp2.Length == 0 && exp10.Length == 0) // { // return Convert.ToInt64(numstr,10); // } // double d = Convert.ToDouble(numstr); // if (exp2.Length > 0) // { // exp = Convert.ToInt32(exp2, 10); // d = d * Math.Pow(2, exp); // } // else if (exp10.Length > 0) // { // exp = Convert.ToInt32(exp10, 10); // d = d * Math.Pow(10, exp); // } // return ((Int64)(d + 0.49)); // } // throw new CodeEE("数字で始まるトークンが適切でありません"); //} public static bool UseMacro = true; #region read public static Int64 ReadInt64(StringStream st, bool retZero) { Int64 significand = 0; int expBase = 0; int exponent = 0; int stStartPos = st.CurrentPosition; int stEndPos = st.CurrentPosition; int fromBase = 10; if (st.Current == '0') { char c = st.Next; if ((c == 'x') || (c == 'X')) { fromBase = 16; st.ShiftNext(); st.ShiftNext(); } else if ((c == 'b') || (c == 'B')) { fromBase = 2; st.ShiftNext(); st.ShiftNext(); } //8進法は互換性の問題から採用しない。 //else if (dchar.IsDigit(c)) //{ // fromBase = 8; // st.ShiftNext(); //} } if (retZero && st.Current != '+' && st.Current != '-' && !char.IsDigit(st.Current)) { if (fromBase != 16) return 0; else if (!hexadecimalDigits.Contains(st.Current)) return 0; } significand = readDigits(st, fromBase); if ((st.Current == 'p') || (st.Current == 'P')) expBase = 2; else if ((st.Current == 'e') || (st.Current == 'E')) expBase = 10; if (expBase != 0) { st.ShiftNext(); unchecked { exponent = (int)readDigits(st, fromBase); } } stEndPos = st.CurrentPosition; if ((expBase != 0) && (exponent != 0)) { double d = significand * Math.Pow(expBase, exponent); if ((double.IsNaN(d)) || (double.IsInfinity(d)) || (d > Int64.MaxValue) || (d < Int64.MinValue)) throw new CodeEE("\"" + st.Substring(stStartPos, stEndPos) + "\"は64ビット符号付整数の範囲を超えています"); significand = (Int64)d; } return significand; } //static Regex reg = new Regex(@"[0-9A-Fa-f]+", RegexOptions.Compiled); private static Int64 readDigits(StringStream st, int fromBase) { int start = st.CurrentPosition; //1756 正規表現を使ってみたがほぼ変わらなかったので没 //Match m = reg.Match(st.RowString, st.CurrentPosition); //st.Jump(m.Length); char c = st.Current; if ((c == '-') || (c == '+')) { st.ShiftNext(); } if (fromBase == 10) { while (!st.EOS) { c = st.Current; if (char.IsDigit(c)) { st.ShiftNext(); continue; } break; } } else if (fromBase == 16) { while (!st.EOS) { c = st.Current; if (char.IsDigit(c) || hexadecimalDigits.Contains(c)) { st.ShiftNext(); continue; } break; } } else if (fromBase == 2) { while (!st.EOS) { c = st.Current; if (char.IsDigit(c)) { if ((c != '0') && (c != '1')) throw new CodeEE("二進法表記の中で使用できない文字が使われています"); st.ShiftNext(); continue; } break; } } string strInt = st.Substring(start, st.CurrentPosition - start); try { return Convert.ToInt64(strInt, fromBase); } catch (FormatException) { throw new CodeEE("\"" + strInt + "\"は整数値に変換できません"); } catch (OverflowException) { throw new CodeEE("\"" + strInt + "\"は64ビット符号付き整数の範囲を超えています"); } catch (ArgumentOutOfRangeException) { if (string.IsNullOrEmpty(strInt)) throw new CodeEE("数値として認識できる文字が必要です"); throw new CodeEE("文字列\"" + strInt + "\"は数値として認識できません"); } } /// <summary> /// TIMES第二引数のみが使用する。 /// Convertクラスが発行する例外をそのまま投げるので適切に処理すること。 /// </summary> /// <param name="st"></param> /// <returns></returns> public static double ReadDouble(StringStream st) { int start = st.CurrentPosition; //大雑把に読み込んでエラー処理はConvertクラスに任せる。 //仮数小数部 if ((st.Current == '-') || (st.Current == '+')) { st.ShiftNext(); } while (!st.EOS) {//仮数部 char c = st.Current; if (char.IsDigit(c) || (c == '.')) { st.ShiftNext(); continue; } break; } if ((st.Current == 'e') || (st.Current == 'E')) { st.ShiftNext(); if (st.Current == '-') { st.ShiftNext(); } while (!st.EOS) {//指数部 char c = st.Current; if (char.IsDigit(c) || (c == '.')) { st.ShiftNext(); continue; } break; } } return Convert.ToDouble(st.Substring(start, st.CurrentPosition - start)); } /// <summary> /// 行頭の単語の取得。マクロ展開あり。ただし単語でないマクロ展開はしない。 /// </summary> /// <param name="st"></param> /// <returns></returns> public static IdentifierWord ReadFirstIdentifierWord(StringStream st) { int startpos = st.CurrentPosition; string str = ReadSingleIdentifier(st); if (string.IsNullOrEmpty(str)) throw new CodeEE("不正な文字で行が始まっています"); //1808a3 先頭1単語の展開をやめる。-命令の置換を禁止。 //if (UseMacro) //{ // int i = 0; // while (true) // { // DefineMacro macro = GlobalStatic.IdentifierDictionary.GetMacro(str); // i++; // if (i > MAX_EXPAND_MACRO) // throw new CodeEE("マクロの展開数が1文あたりの上限を超えました(自己参照・循環参照のおそれ)"); // if (macro == null) // break; // //単語(識別子一個)でないマクロが出現したらここでは処理しない // if (macro.IDWord == null) // { // st.CurrentPosition = startpos; // return null;//変数処理に任せる。 // } // str = macro.IDWord.Code; // } //} return new IdentifierWord(str); } /// <summary> /// 単語の取得。マクロ展開あり。関数型マクロ展開なし /// </summary> /// <param name="st"></param> /// <returns></returns> public static IdentifierWord ReadSingleIdentifierWord(StringStream st) { string str = ReadSingleIdentifier(st); if (string.IsNullOrEmpty(str)) return null; if (UseMacro) { int i = 0; while (true) { DefineMacro macro = GlobalStatic.IdentifierDictionary.GetMacro(str); i++; if (i > MAX_EXPAND_MACRO) throw new CodeEE("マクロの展開数が1文あたりの上限値" + MAX_EXPAND_MACRO.ToString() + "を超えました(自己参照・循環参照のおそれ)"); if (macro == null) break; if (macro.IDWord != null) throw new CodeEE("マクロ" + macro.Keyword + "はこの文脈では使用できません(1単語に置き換えるマクロのみが使用できます)"); str = macro.IDWord.Code; } } return new IdentifierWord(str); } static readonly HashSet<char> kHashSet_ReadSingleIdentifier = new HashSet<char> { ' ', '\t', '+', '-', '*', '/', '%', '=', '!', '<', '>', '|', '&', '^', '~', '?', '#', ')', '}', ']', ',', ':', '(', '{', '[', '$', '\\', '\'', '\"', '@', '.', ';', }; /// <summary> /// 単語を文字列で取得。マクロ適用なし /// </summary> /// <param name="st"></param> /// <returns></returns> public static string ReadSingleIdentifier(StringStream st) { //1819 やや遅い。でもいずれやりたい //Match m = idReg.Match(st.RowString, st.CurrentPosition); //st.Jump(m.Length); //return m.Value; int start = st.CurrentPosition; char c; while (!st.EOS) { //switch (st.Current) //{ // case ' ': // case '\t': // case '+': // case '-': // case '*': // case '/': // case '%': // case '=': // case '!': // case '<': // case '>': // case '|': // case '&': // case '^': // case '~': // case '?': // case '#': // case ')': // case '}': // case ']': // case ',': // case ':': // case '(': // case '{': // case '[': // case '$': // case '\\': // case '\'': // case '\"': // case '@': // case '.': // case ';'://コメントに関しては直後に行われるであろうSkipWhiteSpaceなどが対応する。 // goto end; // case ' ': // if (!Config.SystemAllowFullSpace) // throw new CodeEE("予期しない全角スペースを発見しました(この警告はシステムオプション「" + Config.GetConfigName(ConfigCode.SystemAllowFullSpace) + "」により無視できます)"); // goto end; //} c = st.Current; if(kHashSet_ReadSingleIdentifier.Contains(c)) goto end; else if(c == ' ') { if(!Config.SystemAllowFullSpace) throw new CodeEE("予期しない全角スペースを発見しました(この警告はシステムオプション「" + Config.GetConfigName(ConfigCode.SystemAllowFullSpace) + "」により無視できます)"); goto end; } st.ShiftNext(); } end: return st.Substring(start, st.CurrentPosition - start); } /// <summary> /// endWithが見つかるまで読み込む。始点と終端のチェックは呼び出し側で行うこと。 /// エスケープあり。 /// </summary> /// <param name="st"></param> /// <returns></returns> public static string ReadString(StringStream st, StrEndWith endWith) { StringBuilder buffer = new StringBuilder(100); while (true) { switch (st.Current) { case '\0': goto end; case '\"': if (endWith == StrEndWith.DoubleQuotation) goto end; break; case '\'': if (endWith == StrEndWith.SingleQuotation) goto end; break; case ',': if ((endWith == StrEndWith.Comma) || (endWith == StrEndWith.LeftParenthesis_Bracket_Comma_Semicolon)) goto end; break; case '(': case '[': case ';': if (endWith == StrEndWith.LeftParenthesis_Bracket_Comma_Semicolon) goto end; break; case '\\'://エスケープ処理 st.ShiftNext();//\を読み飛ばす switch (st.Current) { case StringStream.EndOfString: throw new CodeEE("エスケープ文字\\の後に文字がありません"); case '\n': break; case 's': buffer.Append(' '); break; case 'S': buffer.Append(' '); break; case 't': buffer.Append('\t'); break; case 'n': buffer.Append('\n'); break; default: buffer.Append(st.Current); break; } st.ShiftNext();//\の次の文字を読み飛ばす continue; } buffer.Append(st.Current); st.ShiftNext(); } end: return buffer.ToString(); } /// <summary> /// 失敗したらCodeEE。OperatorManagerには頼らない /// OperatorCode.Assignmentを返すことがある。 /// </summary> /// <param name="st"></param> /// <returns></returns> public static OperatorCode ReadOperator(StringStream st, bool allowAssignment) { char cur = st.Current; st.ShiftNext(); char next = st.Current; switch (cur) { case '+': if (next == '+') { st.ShiftNext(); return OperatorCode.Increment; } return OperatorCode.Plus; case '-': if (next == '-') { st.ShiftNext(); return OperatorCode.Decrement; } return OperatorCode.Minus; case '*': return OperatorCode.Mult; case '/': return OperatorCode.Div; case '%': return OperatorCode.Mod; case '=': if (next == '=') { st.ShiftNext(); return OperatorCode.Equal; } if (allowAssignment) return OperatorCode.Assignment; throw new CodeEE("予期しない代入演算子'='を発見しました(等価比較には'=='を使用してください)"); case '!': if (next == '=') { st.ShiftNext(); return OperatorCode.NotEqual; } else if (next == '&') { st.ShiftNext(); return OperatorCode.Nand; } else if (next == '|') { st.ShiftNext(); return OperatorCode.Nor; } return OperatorCode.Not; case '<': if (next == '=') { st.ShiftNext(); return OperatorCode.LessEqual; } else if (next == '<') { st.ShiftNext(); return OperatorCode.LeftShift; } return OperatorCode.Less; case '>': if (next == '=') { st.ShiftNext(); return OperatorCode.GreaterEqual; } else if (next == '>') { st.ShiftNext(); return OperatorCode.RightShift; } return OperatorCode.Greater; case '|': if (next == '|') { st.ShiftNext(); return OperatorCode.Or; } return OperatorCode.BitOr; case '&': if (next == '&') { st.ShiftNext(); return OperatorCode.And; } return OperatorCode.BitAnd; case '^': if (next == '^') { st.ShiftNext(); return OperatorCode.Xor; } return OperatorCode.BitXor; case '~': return OperatorCode.BitNot; case '?': return OperatorCode.Ternary_a; case '#': return OperatorCode.Ternary_b; } throw new CodeEE("'" + cur + "'は演算子として認識できません"); } /// <summary> /// 失敗したらCodeEE。OperatorManagerには頼らない /// "="の時、OperatorCode.Assignmentを返す。"=="の時はEqual /// </summary> /// <param name="st"></param> /// <returns></returns> public static OperatorCode ReadAssignmentOperator(StringStream st) { OperatorCode ret = OperatorCode.NULL; char cur = st.Current; st.ShiftNext(); char next = st.Current; switch (cur) { case '+': if (next == '+') ret = OperatorCode.Increment; else if (next == '=') ret = OperatorCode.Plus; break; case '-': if (next == '-') ret = OperatorCode.Decrement; else if (next == '=') ret = OperatorCode.Minus; break; case '*': if (next == '=') ret = OperatorCode.Mult; break; case '/': if (next == '=') ret = OperatorCode.Div; break; case '%': if (next == '=') ret = OperatorCode.Mod; break; case '=': if (next == '=') { ret = OperatorCode.Equal; break; } return OperatorCode.Assignment; case '\'': if (next == '=') { ret = OperatorCode.AssignmentStr; break; } throw new CodeEE("\"\'\"は代入演算子として認識できません"); case '<': if (next == '<') { st.ShiftNext(); if (st.Current == '=') { ret = OperatorCode.LeftShift; break; } throw new CodeEE("'<'は代入演算子として認識できません"); } break; case '>': if (next == '>') { st.ShiftNext(); if (st.Current == '=') { ret = OperatorCode.RightShift; break; } throw new CodeEE("'>'は代入演算子として認識できません"); } break; case '|': if (next == '=') ret = OperatorCode.BitOr; break; case '&': if (next == '=') ret = OperatorCode.BitAnd; break; case '^': if (next == '=') ret = OperatorCode.BitXor; break; } if (ret == OperatorCode.NULL) throw new CodeEE("'" + cur + "'は代入演算子として認識できません"); st.ShiftNext(); return ret; } /// <summary> /// Consoleの文字表示用。字句解析や構文解析に使ってはならない /// </summary> public static int SkipAllSpace(StringStream st) { int count = 0; while (true) { switch (st.Current) { case ' ': case '\t': case ' ': count++; st.ShiftNext(); continue; } return count; } } public static bool IsWhiteSpace(char c) { return c == ' ' || c == '\t' || c == ' '; } /// <summary> /// 字句解析・構文解析用。ホワイトスペースの他、コメントも飛ばす。 /// </summary> public static int SkipWhiteSpace(StringStream st) { int count = 0; while (true) { switch (st.Current) { case ' ': case '\t': count++; st.ShiftNext(); continue; case ' ': if (!Config.SystemAllowFullSpace) return count; goto case ' '; case ';': if (st.CurrentEqualTo(";#;") && Program.DebugMode) { st.Jump(3); continue; } else if (st.CurrentEqualTo(";!;")) { st.Jump(3); continue; } st.Seek(0, System.IO.SeekOrigin.End); return count; } return count; } } /// <summary> /// 字句解析・構文解析用。文字列直前の半角スペースを飛ばす。性質上、半角スペースのみを見る。 /// </summary> public static int SkipHalfSpace(StringStream st) { int count = 0; while (st.Current == ' ') { count++; st.ShiftNext(); } return count; } #endregion #region analyse /// <summary> /// 解析できるものは関数宣言や式のみ。FORM文字列や普通の文字列を送ってはいけない /// return時にはendWithの文字がCurrentになっているはず。終端の適切さの検証は呼び出し元が行う。 /// </summary> /// <returns></returns> public static WordCollection Analyse(StringStream st, LexEndWith endWith, LexAnalyzeFlag flag) { WordCollection ret = new WordCollection(); int nestBracketS = 0; //int nestBracketM = 0; int nestBracketL = 0; while (true) { switch (st.Current) { case '\n': case '\0': goto end; case ' ': case '\t': st.ShiftNext(); continue; case ' ': if (!Config.SystemAllowFullSpace) throw new CodeEE("字句解析中に予期しない全角スペースを発見しました(この警告はシステムオプション「" + Config.GetConfigName(ConfigCode.SystemAllowFullSpace) + "」により無視できます)"); st.ShiftNext(); continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ret.Add(new LiteralIntegerWord(ReadInt64(st, false))); break; case '>': if(endWith == LexEndWith.GreaterThan) goto end; goto case '+'; case '+': case '-': case '*': case '/': case '%': case '=': case '!': case '<': case '|': case '&': case '^': case '~': case '?': case '#': if ((nestBracketS == 0) && (nestBracketL == 0)) { if (endWith == LexEndWith.Operator) goto end;//代入演算子のはずである。呼び出し元がチェックするはず else if ((endWith == LexEndWith.Percent) && (st.Current == '%')) goto end; else if ((endWith == LexEndWith.Question) && (st.Current == '?')) goto end; } ret.Add(new OperatorWord(ReadOperator(st, (flag & LexAnalyzeFlag.AllowAssignment) == LexAnalyzeFlag.AllowAssignment))); break; case ')': ret.Add(new SymbolWord(')')); nestBracketS--; st.ShiftNext(); continue; case ']': ret.Add(new SymbolWord(']')); nestBracketL--; st.ShiftNext(); continue; case '(': ret.Add(new SymbolWord('(')); nestBracketS++; st.ShiftNext(); continue; case '[': if (st.Next == '[') { //throw new CodeEE("字句解析中に予期しない文字'[['を発見しました"); ////1808alpha006 rename処理変更 //1808beta009 ここだけ戻す //現在の処理だとここに来た時点でrename失敗確定だが警告内容を元に戻すため if (ParserMediator.RenameDic == null) throw new CodeEE("字句解析中に予期しない文字\"[[\"を発見しました"); int start = st.CurrentPosition; int find = st.Find("]]"); if (find <= 2) { if (find == 2) throw new CodeEE("空の[[]]です"); else throw new CodeEE("対応する\"]]\"のない\"[[\"です"); } string key = st.Substring(start, find + 2); //1810 ここまでで置換できなかったものは強制エラーにする //行連結前に置換不能で行連結より置換することができるようになったものまで置換されていたため throw new CodeEE("字句解析中に置換(rename)できない符号" + key + "を発見しました"); //string value = null; //if (!ParserMediator.RenameDic.TryGetValue(key, out value)) // throw new CodeEE("字句解析中に置換(rename)できない符号" + key + "を発見しました"); //st.Replace(start, find + 2, value); //continue;//その場から再度解析スタート } ret.Add(new SymbolWord('[')); nestBracketL++; st.ShiftNext(); continue; case ':': ret.Add(new SymbolWord(':')); st.ShiftNext(); continue; case ',': if ((endWith == LexEndWith.Comma) && (nestBracketS == 0))// && (nestBracketL == 0)) goto end; ret.Add(new SymbolWord(',')); st.ShiftNext(); continue; //case '}': ret.Add(new SymbolWT('}')); nestBracketM--; continue; //case '{': ret.Add(new SymbolWT('{')); nestBracketM++; continue; case '\'': if ((flag & LexAnalyzeFlag.AllowSingleQuotationStr) == LexAnalyzeFlag.AllowSingleQuotationStr) { st.ShiftNext(); ret.Add(new LiteralStringWord(ReadString(st, StrEndWith.SingleQuotation))); if (st.Current != '\'') throw new CodeEE("\'が閉じられていません"); st.ShiftNext(); break; } if ((flag & LexAnalyzeFlag.AnalyzePrintV) != LexAnalyzeFlag.AnalyzePrintV) { //AssignmentStr用特殊処理 代入文の代入演算子を探索中で'=の場合のみ許可 if ((endWith == LexEndWith.Operator) && (nestBracketS == 0) && (nestBracketL == 0) && st.Next == '=' ) goto end; throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました"); } st.ShiftNext(); ret.Add(new LiteralStringWord(ReadString(st, StrEndWith.Comma))); if (st.Current == ',') goto case ',';//続きがあるなら,の処理へ。それ以外は行終端のはず goto end; case '}': if (endWith == LexEndWith.RightCurlyBrace) goto end; throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました"); case '\"': st.ShiftNext(); ret.Add(new LiteralStringWord(ReadString(st, StrEndWith.DoubleQuotation))); if (st.Current != '\"') throw new CodeEE("\"が閉じられていません"); st.ShiftNext(); break; case '@': if (st.Next != '\"') { ret.Add(new SymbolWord('@')); st.ShiftNext(); continue; } st.ShiftNext(); st.ShiftNext(); ret.Add(AnalyseFormattedString(st, FormStrEndWith.DoubleQuotation, false)); if (st.Current != '\"') throw new CodeEE("\"が閉じられていません"); st.ShiftNext(); break; case '.': ret.Add(new SymbolWord('.')); st.ShiftNext(); continue; case '\\': if (st.Next != '@') throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました"); { st.Jump(2); ret.Add(new StrFormWord(new string[] { "", "" }, new SubWord[] { AnalyseYenAt(st) })); } break; case '{': case '$': throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました"); case ';'://1807 行中コメント if (st.CurrentEqualTo(";#;") && Program.DebugMode) { st.Jump(3); break; } else if (st.CurrentEqualTo(";!;")) { st.Jump(3); break; } st.Seek(0, System.IO.SeekOrigin.End); goto end; default: { ret.Add(new IdentifierWord(ReadSingleIdentifier(st))); break; } } } end: if ((nestBracketS != 0) || (nestBracketL != 0)) { if (nestBracketS < 0) throw new CodeEE("字句解析中に対応する'('のない')'を発見しました"); else if (nestBracketS > 0) throw new CodeEE("字句解析中に対応する')'のない'('を発見しました"); if (nestBracketL < 0) throw new CodeEE("字句解析中に対応する'['のない']'を発見しました"); else if (nestBracketL > 0) throw new CodeEE("字句解析中に対応する']'のない'['を発見しました"); } if (UseMacro) return expandMacro(ret); return ret; } private static WordCollection expandMacro(WordCollection wc) { //マクロ展開 wc.Pointer = 0; int count = 0; while (!wc.EOL) { IdentifierWord word = wc.Current as IdentifierWord; if (word == null) { wc.ShiftNext(); continue; } string idStr = word.Code; DefineMacro macro = GlobalStatic.IdentifierDictionary.GetMacro(idStr); if (macro == null) { wc.ShiftNext(); continue; } count++; if (count > MAX_EXPAND_MACRO) throw new CodeEE("マクロの展開数が1文あたりの上限" + MAX_EXPAND_MACRO.ToString() + "を超えました(自己参照・循環参照のおそれ)"); if (!macro.HasArguments) { wc.Remove(); wc.InsertRange(macro.Statement); continue; } //関数型マクロ wc = expandFunctionlikeMacro(macro, wc); } wc.Pointer = 0; return wc; } private static WordCollection expandFunctionlikeMacro(DefineMacro macro, WordCollection wc) { int macroStart = wc.Pointer; wc.ShiftNext(); SymbolWord symbol = wc.Current as SymbolWord; if (symbol == null || symbol.Type != '(') throw new CodeEE("関数形式のマクロ" + macro.Keyword + "に引数がありません"); WordCollection macroWC = macro.Statement.Clone(); WordCollection[] args = new WordCollection[macro.ArgCount]; //引数部読み取りループ for (int i = 0; i < macro.ArgCount; i++) { int macroNestBracketS = 0; args[i] = new WordCollection(); while (true) { wc.ShiftNext(); if (wc.EOL) throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の用法が正しくありません"); symbol = wc.Current as SymbolWord; if (symbol == null) { args[i].Add(wc.Current); continue; } switch (symbol.Type) { case '(': macroNestBracketS++; break; case ')': if (macroNestBracketS > 0) { macroNestBracketS--; break; } if (i != macro.ArgCount - 1) throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の引数の数が正しくありません"); goto exitfor; case ',': if (macroNestBracketS == 0) goto exitwhile; break; } args[i].Add(wc.Current); } exitwhile: if (args[i].Collection.Count == 0) throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の引数を省略することはできません"); continue; } //引数部読み取りループ終端 exitfor: symbol = wc.Current as SymbolWord; if (symbol == null || symbol.Type != ')') throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の用法が正しくありません"); int macroLength = wc.Pointer - macroStart + 1; wc.Pointer = macroStart; for (int j = 0; j < macroLength; j++) wc.Collection.RemoveAt(macroStart); while (!macroWC.EOL) { MacroWord w = macroWC.Current as MacroWord; if (w == null) { macroWC.ShiftNext(); continue; } macroWC.Remove(); macroWC.InsertRange(args[w.Number]); macroWC.Pointer += args[w.Number].Collection.Count; } wc.InsertRange(macroWC); wc.Pointer = macroStart; return wc; } /// <summary> /// @"などの直後からの開始 /// return時にはendWithの文字がCurrentになっているはず。終端の適切さの検証は呼び出し元が行う。 /// </summary> /// <returns></returns> public static StrFormWord AnalyseFormattedString(StringStream st, FormStrEndWith endWith, bool trim) { List<string> strs = new List<string>(); List<SubWord> SWTs = new List<SubWord>(); StringBuilder buffer = new StringBuilder(100); while (true) { char cur = st.Current; switch (cur) { case '\n': case '\0': goto end; case '\"': if (endWith == FormStrEndWith.DoubleQuotation) goto end; buffer.Append(cur); break; case '#': if (endWith == FormStrEndWith.Sharp) goto end; buffer.Append(cur); break; case ',': if ((endWith == FormStrEndWith.Comma) || (endWith == FormStrEndWith.LeftParenthesis_Bracket_Comma_Semicolon)) goto end; buffer.Append(cur); break; case '(': case '[': case ';': if (endWith == FormStrEndWith.LeftParenthesis_Bracket_Comma_Semicolon) goto end; buffer.Append(cur); break; case '%': strs.Add(buffer.ToString()); buffer.Remove(0, buffer.Length); st.ShiftNext(); SWTs.Add(new PercentSubWord(Analyse(st, LexEndWith.Percent, LexAnalyzeFlag.None))); if (st.Current != '%') throw new CodeEE("\'%\'が使われましたが対応する\'%\'が見つかりません"); break; case '{': strs.Add(buffer.ToString()); buffer.Remove(0, buffer.Length); st.ShiftNext(); SWTs.Add(new CurlyBraceSubWord(Analyse(st, LexEndWith.RightCurlyBrace, LexAnalyzeFlag.None))); if (st.Current != '}') throw new CodeEE("\'{\'が使われましたが対応する\'}\'が見つかりません"); break; case '*': case '+': case '=': case '/': case '$': if (!Config.SystemIgnoreTripleSymbol && st.TripleSymbol()) { strs.Add(buffer.ToString()); buffer.Remove(0, buffer.Length); st.Jump(3); SWTs.Add(new TripleSymbolSubWord(cur)); continue; } else buffer.Append(cur); break; case '\\'://エスケープ文字の使用 st.ShiftNext(); cur = st.Current; switch (cur) { case '\0': throw new CodeEE("エスケープ文字\\の後に文字がありません"); case '\n': break; case 's': buffer.Append(' '); break; case 'S': buffer.Append(' '); break; case 't': buffer.Append('\t'); break; case 'n': buffer.Append('\n'); break; case '@'://\@~~?~~#~~\@ { if ((endWith == FormStrEndWith.YenAt) || (endWith == FormStrEndWith.Sharp)) goto end; strs.Add(buffer.ToString()); buffer.Remove(0, buffer.Length); st.ShiftNext(); SWTs.Add(AnalyseYenAt(st)); continue; } default: buffer.Append(cur); st.ShiftNext(); continue; } break; default: buffer.Append(cur); break; } st.ShiftNext(); } end: strs.Add(buffer.ToString()); string[] retStr = new string[strs.Count]; SubWord[] retSWTs = new SubWord[SWTs.Count]; strs.CopyTo(retStr); SWTs.CopyTo(retSWTs); if (trim && retStr.Length > 0) { retStr[0] = retStr[0].TrimStart(new char[] { ' ', '\t' }); retStr[retStr.Length - 1] = retStr[retStr.Length - 1].TrimEnd(new char[] { ' ', '\t' }); } return new StrFormWord(retStr, retSWTs); } /// <summary> /// \@直後からの開始、\@の直後がCurrentになる /// </summary> /// <param name="st"></param> /// <returns></returns> public static YenAtSubWord AnalyseYenAt(StringStream st) { WordCollection w = Analyse(st, LexEndWith.Question, LexAnalyzeFlag.None); if (st.Current != '?') throw new CodeEE("\'\\@\'が使われましたが対応する\'?\'が見つかりません"); st.ShiftNext(); StrFormWord left = AnalyseFormattedString(st, FormStrEndWith.Sharp, true); if (st.Current != '#') { if (st.Current != '@') throw new CodeEE("\'\\@\',\'?\'が使われましたが対応する\'#\'が見つかりません"); st.ShiftNext(); ParserMediator.Warn("\'\\@\',\'?\'が使われましたが対応する\'#\'が見つかりません", GlobalStatic.Process.GetScaningLine(), 1, false, false); return new YenAtSubWord(w, left, null); } st.ShiftNext(); StrFormWord right = AnalyseFormattedString(st, FormStrEndWith.YenAt, true); if (st.Current != '@') throw new CodeEE("\'\\@\',\'?\',\'#\'が使われましたが対応する\'\\@\'が見つかりません"); st.ShiftNext(); return new YenAtSubWord(w, left, right); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace Polly.Console.Classes { public class Logger { public void WriteInfo(string message, params object[] param) { System.Console.WriteLine($"{DateTime.Now}: {message}", param); } public void WriteError(string message, params object[] param) { System.Console.ForegroundColor = ConsoleColor.Red; System.Console.WriteLine($"{DateTime.Now}: {message}", param); System.Console.ResetColor(); } } }
namespace ApplicationCore { public class CatalogSettings : AppSettings { public string CatalogBaseUrl { get; set; } public decimal DefaultShippingCost { get; set; } = 3.35m; } }
using UnityEngine; using UnityEngine.UI; using System.Collections; [System.Serializable] public class ComboBoxItem { public string Label = ""; public string Value = ""; } public class ComboBox : MonoBehaviour { #region Public Attributes public ComboBoxItem[] Items; public string Label; #endregion Public Attributes #region Component References private Text _label; private LabelLocalization _value; #endregion Component References #region MonoBehaviour Methods void Awake() { _label = GetComponentInChildren<Text>(); _value = transform.Find("Options").GetComponentInChildren<LabelLocalization>(); _label.text = Label; } void Start() { UpdateItem(); } #endregion MonoBehaviour Methods #region Properties public int SelectedIndex {get; private set;} public ComboBoxItem SelectedItem { get { if (SelectedIndex < 0 || SelectedIndex >= Items.Length) return null; return Items[SelectedIndex]; } } public string SelectedValue { get { var item = SelectedItem; if (item != null) return item.Value; return null; } } #endregion Properties #region Events public void OnClick() { SelectedIndex = (SelectedIndex + 1) % Items.Length; UpdateItem(); } #endregion Events #region Private Methods private void UpdateItem() { var item = SelectedItem; //print("Updating Item: " + item); if (item != null) { _value.ChangeText( item.Label ); } } #endregion Private Methods }
using Shinobytes.Ravenfall.RavenNet.Models; namespace Shinobytes.Ravenfall.RavenNet.Modules { public class OpenNpcTradeWindow : EntityUpdated<Player> { public OpenNpcTradeWindow( Player entity, int npcServerId, string shopName, int[] itemId, int[] itemPrice, int[] itemStock) : base(entity) { NpcServerId = npcServerId; ShopName = shopName; ItemId = itemId; ItemPrice = itemPrice; ItemStock = itemStock; } public int NpcServerId { get; } public int[] ItemId { get; } public int[] ItemPrice { get; } public int[] ItemStock { get; } public string ShopName { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using API___ATC_Horas.Funcionamento; /// <summary> /// Controler apenas para responder as requisições de teste de conexão dos clientes /// Se os dados estiverem ok responde Sucesso! /// Se der algum problema na requisição responde Falha! /// Se o ApiKey não existir responde ApiKey Inexistente /// </summary> namespace API___ATC_Horas.Controllers { public class TesteController : ApiController { [AcceptVerbs("GET")] [Route("API/Teste/{ApiKey}/{Origem}")] // API/Teste?ApiKey=&Origem= public string RespostaTeste(string ApiKey, string Origem) { return Database.TesteConexao(ApiKey, Origem); } } }
using Zenject; namespace MokomoGames { public class PlayerSaveDataDebugRepositoryInstaller : Installer<PlayerSaveDataDebugRepositoryInstaller> { public override void InstallBindings() { Container .Bind<IPlayerSaveDataRepository>() .To<PlayerSaveDataDebugRepository>() .AsCached(); } } }
using Aspose.Email.Calendar; using Aspose.Email.Clients.Exchange.WebService; using Aspose.Email.Mime; using System; using System.Collections.Generic; using System.Linq; using System.Text; /* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from https://www.nuget.org/packages/Aspose.Email/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/email */ namespace Aspose.Email.Examples.CSharp.Email.Exchange_EWS { class CreatingUpdatingAndDeletingCalendarItemsUsingEWS { public static void Run() { try { // ExStart:CreatingUpdatingAndDeletingCalendarItemsUsingEWS IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "your.username", "your.Password"); DateTime date = DateTime.Now; DateTime startTime = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0); DateTime endTime = startTime.AddHours(1); string timeZone = "America/New_York"; Appointment app = new Appointment("Room 112", startTime, endTime, "organizeraspose-email.test3@domain.com","attendee@gmail.com"); app.SetTimeZone(timeZone); app.Summary = "NETWORKNET-34136" + Guid.NewGuid().ToString(); app.Description = "NETWORKNET-34136 Exchange 2007/EWS: Provide support for Add/Update/Delete calendar items"; string uid = client.CreateAppointment(app); Appointment fetchedAppointment1 = client.FetchAppointment(uid); app.Location = "Room 115"; app.Summary = "New summary for " + app.Summary; app.Description = "New Description"; client.UpdateAppointment(app); Appointment[] appointments1 = client.ListAppointments(); Console.WriteLine("Total Appointments: " + appointments1.Length); Appointment fetchedAppointment2 = client.FetchAppointment(uid); Console.WriteLine("Summary: " + fetchedAppointment2.Summary); Console.WriteLine("Location: " + fetchedAppointment2.Location); Console.WriteLine("Description: " + fetchedAppointment2.Description); client.CancelAppointment(app); Appointment[] appointments2 = client.ListAppointments(); Console.WriteLine("Total Appointments: " + appointments2.Length); // ExEnd:CreatingUpdatingAndDeletingCalendarItemsUsingEWS } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
namespace Steam.Models.SteamEconomy { public class TradeAssetModel { public uint AppId { get; set; } public uint ContextId { get; set; } /// <summary> /// Either assetid or currencyid will be set /// </summary> public ulong AssetId { get; set; } /// <summary> /// Either assetid or currencyid will be set /// </summary> public ulong CurrencyId { get; set; } /// <summary> /// Together with instanceid, uniquely identifies the display of the item /// </summary> public uint ClassId { get; set; } /// <summary> /// Together with classid, uniquely identifies the display of the item /// </summary> public uint InstanceId { get; set; } /// <summary> /// The amount offered in the trade, for stackable items and currency /// </summary> public uint AmountOffered { get; set; } /// <summary> /// A boolean that indicates the item is no longer present in the user's inventory /// </summary> public bool IsMissing { get; set; } } }
using UnityEngine; namespace DS { using ScriptableObjects; public class DSDialogue : MonoBehaviour { /* Dialogue Scriptable Objects */ [SerializeField] private DSDialogueContainerSO dialogueContainer; [SerializeField] private DSDialogueGroupSO dialogueGroup; [SerializeField] private DSDialogueSO dialogue; /* Filters */ [SerializeField] private bool groupedDialogues; [SerializeField] private bool startingDialoguesOnly; /* Indexes */ [SerializeField] private int selectedDialogueGroupIndex; [SerializeField] private int selectedDialogueIndex; } }
// Copyright (c) AltaModa Technologies. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Ext = AMT.Extensions.Logging.IP; using System.Net.Sockets; namespace Test.AMT.Extensions.Logging.IP { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; internal class UdpReceiver : IDisposable { private static int _maxQueuedMessages = 1024; private readonly BlockingCollection<string> _messageQueue = new BlockingCollection<string>(_maxQueuedMessages); private bool _stopListener = false; private UdpClient _client; public void Start(Ext.UdpLoggerOptions options) { _stopListener = false; _client = new UdpClient(options.IPEndPoint); var senderIP = new IPEndPoint(0,0); // Spawn Udp receiver System.Threading.Tasks.Task.Run( () => { while (!_stopListener) { var r = _client.ReceiveAsync().Result; if (r.Buffer.Length > 0) { string msg = System.Text.Encoding.ASCII.GetString(r.Buffer); _messageQueue.Add(msg); } } }); } public void Stop() { _stopListener = true; _messageQueue.CompleteAdding(); } public IEnumerable<string> RetrieveMessages() { return _messageQueue.GetConsumingEnumerable(); } #region IDisposable impl public void Dispose() { if (null != _client) { _client.Close(); _client.Dispose(); _client = null; } } #endregion IDisposable impl } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kartaskaigra { class Program { static void Main(string[] args) { int BrojacKarta = 0,Karte; string KarteZaStringUInt; while (BrojacKarta < 31) { Console.WriteLine("Upisite 1-13 za karte "); KarteZaStringUInt = (Console.ReadLine()); Karte = Convert.ToInt16(KarteZaStringUInt); if (Karte > 13 || Karte < 1) { Console.WriteLine("Upisali ste broj veci od 13 ili manji od 1 nemoze tako "); } else { BrojacKarta += Karte; } } if (BrojacKarta > 30) { Console.WriteLine("Bravo pobjedili ste imate " + BrojacKarta); } else { Console.WriteLine("izgubili ste imate " + BrojacKarta ); } Console.ReadLine(); } } }
namespace InsuranceHub.Client { using System; using System.Net; public interface IHttpWebRequestCreator { HttpWebRequest Create(Uri requestUri); } }
<!DOCTYPE html> <html lang="en"> <head><title>Feebl</title></head> <body> We're down for a sec! </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IntervalTree; using System.Diagnostics; namespace ZapocetADSI_Interval { class Program { static void Main(string[] args) { if (args.Length == 1 && args[0] == "console") { ConsoleTest(); } else { BasicTests(); } } static void ConsoleTest() { string line; var tree = new IntervalTree<int>(); Console.WriteLine("Enter intervals as \"p q\" to add to tree, each on a new line, end with 0:"); line = Console.ReadLine(); while (line != "0") { string[] bits = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (bits.Length != 2) { break; } int start, end; if (Int32.TryParse(bits[0], out start) && Int32.TryParse(bits[1], out end)) { tree.Add(new Interval<int>(start, end)); } else { break; } line = Console.ReadLine(); } foreach (var n in tree) { Console.Write("{0} ", n); } Console.WriteLine(); Console.WriteLine("Enter intervals as \"p q\" to delete from tree, each on a new line, end with 0:"); line = Console.ReadLine(); while (line != "0") { string[] bits = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (bits.Length != 2) { break; } int start, end; if (Int32.TryParse(bits[0], out start) && Int32.TryParse(bits[1], out end)) { tree.Remove(new Interval<int>(start, end)); } else { break; } line = Console.ReadLine(); } foreach (var n in tree) { Console.Write("{0} ", n); } Console.WriteLine(); Console.WriteLine("Enter intervals as \"p q\", first overlapping interval will be found, end with 0:"); line = Console.ReadLine(); while (line != "0") { string[] bits = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (bits.Length != 2) { break; } int start, end; if (Int32.TryParse(bits[0], out start) && Int32.TryParse(bits[1], out end)) { try { Console.WriteLine(tree.SearchFirstOverlapping(new Interval<int>(start, end))); } catch (KeyNotFoundException e) { Console.WriteLine("Not found"); } } else { break; } line = Console.ReadLine(); } Console.ReadLine(); } static void BasicTests() { var tree = createCormenTree(); Debug.Assert(new Interval<long>(0, 3).Equals(tree.SearchFirstOverlapping(new Interval<long>(2, 4)))); Debug.Assert( tree.Search(18).Count == 3 // <17, 19>, <16, 21>, <15, 23> ); Debug.Assert( tree.Search(12).Count == 0 ); Debug.Assert( tree.Search(-5).Count == 0 ); foreach (var n in tree) { Console.Write("{0} ", n); } Console.WriteLine(); // Remove root (two children) tree.Remove(new Interval<long>(16, 21)); foreach (var n in tree) { Console.Write("{0} ", n); } Console.WriteLine(); // Remove root (leaf) tree.Remove(new Interval<long>(26, 26)); foreach (var n in tree) { Console.Write("{0} ", n); } Console.WriteLine(); System.Threading.Thread.Sleep(3000); // Test a lot of random numbers for tree consinstency and speed LargeDatasetTest(60000, 1000); } /// <summary> /// Tree from Introduction to algorithms /// </summary> /// <returns></returns> static IntervalTree<long> createCormenTree() { var tree = new IntervalTree<long>(); int[] starts = new int[] { 16, 8, 25, 0, 26, 17, 15, 6, 19, 5 }; int[] ends = new int[] { 21, 9, 30, 3, 26, 19, 23, 10, 20, 8 }; for (int i = 0; i < starts.Length; i++) { tree.Add(new Interval<long>(starts[i], ends[i])); } return tree; } static void LargeDatasetTest(int n, int steps) { Random randGen = new Random(); int[] vals = new int[n]; int[] ends = new int[n]; for (int i = 0; i < n; i++) { vals[i] = randGen.Next(1, n - 1); ends[i] = randGen.Next(vals[i], n); } for (int i = 0; i < n; i += steps) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); var tree = new IntervalTree<int>(); for (int j = 0; j < i; j++) { tree.Add(new Interval<int>(vals[j], ends[j])); } Console.WriteLine("Insert\t{0}\t {1}", i, sw.ElapsedMilliseconds); Console.WriteLine("Memory after insert\t{0}", GC.GetTotalMemory(true)); sw.Reset(); sw.Start(); // Delete half of the inserted for (int k = 0; k < i; k++) { int index = randGen.Next(0, i); var xafu = new Interval<int>(vals[index], ends[index]); tree.Remove(xafu); //Console.WriteLine("Just delted {0}", xafu); } sw.Stop(); Console.WriteLine("Delete\t{0}\t {1}", i, sw.ElapsedMilliseconds); // Does not seem to track memory correctly on Mono (as if no GC) // On Windows, memory footprint is cca. 50% after delete, as expected Console.WriteLine("Memory after delete\t{0}", GC.GetTotalMemory(true)); Console.Error.WriteLine("\nTesting {0}", i); } } } }
using System; using System.Collections.Generic; using System.Text; namespace CommDeviceCore.Common { public interface IProtocol//<TIn, TOut> //where TIn: ILayerPackable //where TOut : ILayerPackage { //public TOut Pack(TIn layerPackage); //public TIn UnPack(TOut layerackage); } }
using org.apache.zookeeper.client; using Xunit; namespace org.apache.zookeeper.test { public class ConnectStringParserTest { [Fact] public void testSingleServerChrootPath() { const string chrootPath = "/hallo/welt"; const string servers = "10.10.10.1"; assertChrootPath(chrootPath, new ConnectStringParser(servers + chrootPath)); } [Fact] public void testMultipleServersChrootPath() { const string chrootPath = "/hallo/welt"; const string servers = "10.10.10.1,10.10.10.2"; assertChrootPath(chrootPath, new ConnectStringParser(servers + chrootPath)); } [Fact] public void testParseServersWithoutPort() { const string servers = "10.10.10.1,10.10.10.2"; ConnectStringParser parser = new ConnectStringParser(servers); Assert.assertEquals("10.10.10.1", parser.getServerAddresses()[0].Host); Assert.assertEquals("10.10.10.2", parser.getServerAddresses()[1].Host); } [Fact] public void testParseServersWithPort() { const string servers = "10.10.10.1:112,10.10.10.2:110"; ConnectStringParser parser = new ConnectStringParser(servers); Assert.assertEquals("10.10.10.1", parser.getServerAddresses()[0].Host); Assert.assertEquals("10.10.10.2", parser.getServerAddresses()[1].Host); Assert.assertEquals(112, parser.getServerAddresses()[0].Port); Assert.assertEquals(110, parser.getServerAddresses()[1].Port); } private void assertChrootPath(string expected, ConnectStringParser parser) { Assert.assertEquals(expected, parser.getChrootPath()); } } }
using System; using Synnduit.Properties; namespace Synnduit { /// <summary> /// Extension methods for the <see cref="IContext" /> interface. /// </summary> public static class ContextExtensions { /// <summary> /// Gets the specified parameter value converted to the specified enumeration type. /// </summary> /// <typeparam name="TEnum">The enumeration type.</typeparam> /// <param name="context">The context.</param> /// <param name="parameterName">The parameter name.</param> /// <param name="defaultValue"> /// The default value; will be returned if the specified parameter doesn't exist /// (i.e., isn't specified). /// </param> /// <returns> /// The parameter value converted to the specified enumeration type. /// </returns> public static TEnum GetParameter<TEnum>( this IContext context, string parameterName, TEnum defaultValue) where TEnum : struct { TEnum value = defaultValue; if(context.Parameters.TryGetValue(parameterName, out string valueAsString)) { if(Enum.TryParse(valueAsString, out value) == false) { throw new InvalidOperationException( string.Format( Resources.ParameterCannotBeConvertedToEnum, valueAsString, typeof(TEnum).FullName)); } } return value; } } }
// Copyright © 2020-present Derek Thurn // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // https://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using DG.Tweening; using TMPro; using UnityEngine; #nullable enable namespace Nighthollow.Components { public sealed class DamageText : MonoBehaviour { public enum HitSize { Small, Medium, Big } [SerializeField] TextMeshProUGUI _text = null!; [SerializeField] float _duration; [SerializeField] int _offset; [SerializeField] RectTransform _rectTransform = null!; void OnValidate() { _text = GetComponent<TextMeshProUGUI>(); _rectTransform = GetComponent<RectTransform>(); } public void Initialize(string text, Vector3 position) { _rectTransform.anchoredPosition = position; _text.text = text; _text.alpha = 1f; var offset = new Vector3(Random.Range(-_offset, _offset), Random.Range(-_offset, _offset)); DOTween .Sequence() .Insert(atPosition: 0f, transform.DOMove(transform.position + offset, _duration)) .Insert(atPosition: 0f, _text.DOFade(endValue: 0f, _duration).SetEase(Ease.InQuad)) .AppendCallback(() => gameObject.SetActive(value: false)); } } }
using System.Collections.Generic; using DomainService.Domain.Models; using Newtonsoft.Json; namespace DomainService.Domain { public class JSONConvert { public string Convert(StarModel star){ return JsonConvert.SerializeObject(star); } public string Convert(ConstellationModel constellation){ return JsonConvert.SerializeObject(constellation); } public string Convert(PlanetModel planet){ return JsonConvert.SerializeObject(planet); } public string Convert(SolarSystemModel solarSystem){ return JsonConvert.SerializeObject(solarSystem); } public string Convert(List<StarModel> stars){ return JsonConvert.SerializeObject(stars); } public string Convert(List<ConstellationModel> constellations){ return JsonConvert.SerializeObject(constellations); } public string Convert(List<PlanetModel> planets){ return JsonConvert.SerializeObject(planets); } public string Convert(List<SolarSystemModel> solarSystems){ return JsonConvert.SerializeObject(solarSystems); } } }
using SolrExpress.Builder; using SolrExpress.Search; using SolrExpress.Search.Parameter; using SolrExpress.Search.Parameter.Extension; using SolrExpress.Search.Parameter.Validation; using SolrExpress.Solr4.Search.Parameter; using SolrExpress.Utility; using System.Collections.Generic; using System.Reflection; using SolrExpress.Options; using Xunit; namespace SolrExpress.Solr4.UnitTests.Search.Parameter { public class SortParameterTests { /// <summary> /// Where Using a SortParameter instance /// When Invoking method "Execute" /// What Create a valid string /// </summary> [Fact] public void SortParameter001() { // Arrange var container = new List<string>(); var solrOptions = new SolrExpressOptions(); var solrConnection = new FakeSolrConnection<TestDocument>(); var expressionBuilder = new ExpressionBuilder<TestDocument>(solrOptions, solrConnection); expressionBuilder.LoadDocument(); var parameter = (ISortParameter<TestDocument>)new SortParameter<TestDocument>(expressionBuilder); parameter.FieldExpression(q => q.Id); // Act ((ISearchItemExecution<List<string>>)parameter).Execute(); ((ISearchItemExecution<List<string>>)parameter).AddResultInContainer(container); // Assert Assert.Single(container); Assert.Equal("sort=id asc", container[0]); } /// <summary> /// Where Using a SortParameter instance /// When Checking custom attributes of class /// What Has FieldMustBeIndexedTrueAttribute /// </summary> [Fact] public void SortParameter002() { // Arrange / Act var fieldMustBeIndexedTrueAttribute = typeof(SortParameter<TestDocument>) .GetTypeInfo() .GetCustomAttribute<FieldMustBeIndexedTrueAttribute>(true); // Assert Assert.NotNull(fieldMustBeIndexedTrueAttribute); } } }
/* * ruby.cs * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace vexillographer { class ruby : BindingWriter { private static Dictionary<ParamType, String> typeMap = new Dictionary<ParamType, String>() { { ParamType.None, "nil" }, { ParamType.Int, "0" }, { ParamType.String, "''" }, { ParamType.Bytes, "''" } }; private static string getRubyLine(Option o) { return String.Format(" \"{0}\" => [{1}, \"{2}\", {3}, {4}],", o.name.ToUpper(), o.code, o.comment, typeMap[o.paramType], o.paramDesc == null ? "nil" : "\"" + o.paramDesc + "\""); } private static void writeRubyHash(TextWriter outFile, Scope scope, IEnumerable<Option> options) { outFile.WriteLine(" @@{0} = {{", scope.ToString()); outFile.WriteLine(string.Join("\n", options.Where(f => !f.hidden).Select(f => getRubyLine(f)).ToArray())); outFile.WriteLine(" }"); outFile.WriteLine(); } public void writeFiles(string filePath, IEnumerable<Option> options) { using (var rbFile = System.IO.File.Open(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { TextWriter outFile = new StreamWriter(rbFile); outFile.NewLine = "\n"; outFile.WriteLine(@"# FoundationDB Ruby API # Copyright (c) 2013-2017 Apple Inc. # 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. # Documentation for this API can be found at # https://apple.github.io/foundationdb/api-ruby.html module FDB"); foreach (Scope s in Enum.GetValues(typeof(Scope))) { writeRubyHash(outFile, s, options.Where(o => o.scope == s && o.scope != Scope.ErrorPredicate)); } outFile.WriteLine("end"); outFile.Flush(); } } } }
#Thu Jul 11 13:34:38 BST 2019 lib/com.ibm.ws.request.probe.servlet_1.0.30.jar=bd13c8cdad89f31581cbc7a108e773f8 lib/features/com.ibm.websphere.appserver.autoRequestProbeServlet-1.0.mf=be3fa13f6503c35fea5d2fc17374f172