content
stringlengths
23
1.05M
using AutoSandbox.Materials; using AutoSandbox.Units; namespace AutoSandbox.Automotive.Components.Tubing { /// <summary> /// Base type that defines basic properties of a type that is typically cylindrical and used /// either as a mechanism to contain lengths or transport certain types of materials /// that consume the volume of the tube. /// </summary> public abstract class Tube : IMaterial { private MeasuringUnit<double, LengthUnits> _diameter; private MeasuringUnit<double, LengthUnits> _length; private MaterialType _material; /// <summary> /// Initializes a new instance of the <see cref="Tube"/> class. /// </summary> protected Tube() { this._diameter.Value = 0D; this._diameter.Unit = LengthUnits.Centimeters; this._length.Value = 1D; this._length.Unit = LengthUnits.Inches; } // end default constructor /// <summary> /// Gets or sets the diameter of the tube. /// </summary> public virtual MeasuringUnit<double, LengthUnits> Diamater { get { return this._diameter; } set { this._diameter = value; } } // end property Diameter /// <summary> /// Gets or sets the length of the tube. /// </summary> public virtual MeasuringUnit<double, LengthUnits> Length { get { return this._length; } set { this._length = value; } } // end property Length /// <summary> /// Gets the type of the material the tube is made of. /// </summary> public abstract MaterialType Material { get; } } // end class Tube } // end namespace
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace Gear.CloudStorage.Abstractions.Infrastructure { public interface ICloudStorageDb { DbSet<IdentityUserToken<Guid>> AspNetUserTokens { get; set; } Task<int> SaveChangesAsync(CancellationToken cancellationToken); } }
using DotJEM.Json.Validation.Context; using DotJEM.Json.Validation.Descriptive; using Newtonsoft.Json.Linq; namespace DotJEM.Json.Validation.Constraints.Common { [JsonConstraintDescription("null or empty")] public class NullOrEmptyConstraint : JsonConstraint { public override bool Matches(JToken token, IJsonValidationContext context) { switch (token?.Type) { case null: case JTokenType.Null: return true; case JTokenType.Array: case JTokenType.Object: return !token.HasValues; case JTokenType.String: return string.IsNullOrEmpty((string)token); } return false; } } }
using System; using System.Linq; using System.Linq.Expressions; using GrobExp.Compiler; using NUnit.Framework; namespace Mutators.Tests { [Parallelizable(ParallelScope.All)] public class ExpressionHashCalculatorTest : TestBase { [Test] public void Test1() { Expression<Func<TestClassA, string>> exp1 = a => a.S; Expression<Func<TestClassA, string>> exp2 = aa => aa.S; var hash1 = ExpressionHashCalculator.CalcHashCode(exp1, true); var hash2 = ExpressionHashCalculator.CalcHashCode(exp2, true); Assert.AreNotEqual(hash1, hash2); hash1 = ExpressionHashCalculator.CalcHashCode(exp1, false); hash2 = ExpressionHashCalculator.CalcHashCode(exp2, false); Assert.AreEqual(hash1, hash2); } [Test] public void Test2() { Expression<Func<TestClassA, string>> exp1 = a => a.S; Expression<Func<TestClassB, string>> exp2 = a => a.S; var hash1 = ExpressionHashCalculator.CalcHashCode(exp1, true); var hash2 = ExpressionHashCalculator.CalcHashCode(exp2, true); Assert.AreNotEqual(hash1, hash2); hash1 = ExpressionHashCalculator.CalcHashCode(exp1, false); hash2 = ExpressionHashCalculator.CalcHashCode(exp2, false); Assert.AreNotEqual(hash1, hash2); } [Test] public void Test3() { Expression<Func<TestClassA, string>> exp1 = a => a.ArrayB.First(b => b.S.Length > 0).S; Expression<Func<TestClassA, string>> exp2 = aa => aa.ArrayB.First(bb => bb.S.Length > 0).S; var hash1 = ExpressionHashCalculator.CalcHashCode(exp1, true); var hash2 = ExpressionHashCalculator.CalcHashCode(exp2, true); Assert.AreNotEqual(hash1, hash2); hash1 = ExpressionHashCalculator.CalcHashCode(exp1, false); hash2 = ExpressionHashCalculator.CalcHashCode(exp2, false); Assert.AreEqual(hash1, hash2); } private class TestClassA { public string S { get; set; } public TestClassB[] ArrayB { get; set; } } private class TestClassB { public string S { get; set; } } } }
@{ var contentPickerField = (Orchard.ContentPicker.Fields.ContentPickerField)Model.ContentField; string text = ""; if(contentPickerField.ContentItems.Count() > 0) { Orchard.ContentManagement.ContentItem item = contentPickerField.ContentItems.FirstOrDefault(); dynamic titlePart = item.Parts.FirstOrDefault(x => x.PartDefinition.Name == "TitlePart"); if(titlePart != null) { text = titlePart.Title; } } } @if(string.IsNullOrWhiteSpace(text) == false) { <text>@contentPickerField.DisplayName: @text<br /></text> }
using System.IO; using Aperture; using Captain.Common; using SharpDX.WIC; using static Captain.Application.Application; namespace Captain.Application { /// <inheritdoc /> /// <summary> /// Implements a WIC-enabled PNG image codec /// </summary> [Aperture.DisplayName("PNG")] [MediaType("image/png", "png")] [OptionProvider(typeof(CustomOptionProvider))] internal sealed class PngWicStillImageCodec : WicStillImageCodec { /// <inheritdoc /> /// <summary> /// Defines options logic for this plugin /// </summary> private class CustomOptionProvider : IOptionProvider { /// <inheritdoc /> /// <summary> /// Displays the UI for configuring this plugin /// </summary> /// <param name="options">The current plugin options</param> /// <returns>The new options for this plugin</returns> public object DisplayOptionUi(object options) { Log.Info("Hello, world!"); return options; } /// <inheritdoc /> /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } } /// <inheritdoc /> /// <summary> /// Class constructor /// </summary> /// <param name="width">Capture width, in pixels</param> /// <param name="height">Capture height, in pixels</param> /// <param name="destStream">Destination stream</param> public PngWicStillImageCodec(int width, int height, Stream destStream) : base( width, height, destStream, ContainerFormatGuids.Png) { /* that's all folks! */ } } }
using System; using System.Linq.Expressions; namespace DevZest { internal static partial class ObjectExtensions { internal static Action<T> GetPropertyOrFieldSetter<T>(this object obj, string propertyName) { var constantExpression = Expression.Constant(obj); ParameterExpression paramExpression = Expression.Parameter(typeof(T), propertyName); MemberExpression propertyGetterExpression = Expression.PropertyOrField(constantExpression, propertyName); Action<T> result = Expression.Lambda<Action<T>> ( Expression.Assign(propertyGetterExpression, paramExpression), paramExpression ).Compile(); return result; } } }
using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Meziantou.GitLab { public interface IAuthenticator { Task AuthenticateAsync(HttpRequestMessage message, CancellationToken cancellationToken); } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2016 Hotcakes Commerce, LLC // // 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. #endregion using System; using System.Collections.Generic; using System.Web; using DocumentFormat.OpenXml.Extensions; using DocumentFormat.OpenXml.Spreadsheet; using Hotcakes.Commerce.Utilities; using Hotcakes.Web.OpenXml; namespace Hotcakes.Commerce.Catalog { public class GiftCardExport { #region Fields private readonly HotcakesApplication _hccApp; #endregion #region Constructor public GiftCardExport(HotcakesApplication hccApp) { _hccApp = hccApp; } #endregion /// <summary> /// Export the gift card to excel. /// </summary> /// <param name="response">Response stream on which excel file will be writted</param> /// <param name="fileName">File name which exported</param> /// <param name="giftCards">List of <see cref="GiftCard" /> instances</param> public void ExportToExcel(HttpResponse response, string fileName, List<GiftCard> giftCards) { var writer = new ExcelWriter("Main"); var mainWriter = new MainSheetWriter(writer, _hccApp); mainWriter.Write(giftCards); writer.Save(); writer.WriteToResponse(response, fileName); } internal class MainSheetWriter { protected int _firstRow; private readonly HotcakesApplication _hccApp; protected SpreadsheetStyle _headerStyle; protected SpreadsheetStyle _rowStyle; protected ExcelWriter _writer; internal MainSheetWriter(ExcelWriter writer, HotcakesApplication hccApp) { _writer = writer; _rowStyle = writer.GetStyle(); _headerStyle = writer.GetStyle(); _headerStyle.IsBold = true; _hccApp = hccApp; } /// <summary> /// Write <see cref="GiftCard" /> to file. /// </summary> /// <param name="cards">List of cards</param> public void Write(List<GiftCard> cards) { WriteHeader(); var rowIndex = _firstRow; foreach (var gc in cards) { rowIndex = WriteRow(gc, rowIndex); } } /// <summary> /// Write excel file header. /// </summary> private void WriteHeader() { var centerStyle = _writer.GetStyle(); centerStyle.SetHorizontalAlignment(HorizontalAlignmentValues.Center); _writer.WriteRow("A", 1, new List<string> { "Issue Date", "Expiration Date", "Recipient Name", "Recipient Email", "Card Number", "Amount", "Balance", "Enabled" }, _headerStyle); _firstRow = 2; } /// <summary> /// Write individual GiftCard to the file. /// </summary> /// <param name="gc"><see cref="GiftCard" /> instance</param> /// <param name="rowIndex">Row index on which this record going to be written on excel file</param> /// <returns>Returns row index</returns> private int WriteRow(GiftCard gc, int rowIndex) { _writer.WriteRow("A", rowIndex, new List<string> { GetDateTimeString(gc.IssueDateUtc), GetDateTimeString(gc.ExpirationDateUtc), gc.RecipientName, gc.RecipientEmail, gc.CardNumber, gc.Amount.ToString(), (gc.Amount - gc.UsedAmount).ToString(), GetYesNo(gc.Enabled) }, _rowStyle); return ++rowIndex; } /// <summary> /// Returns Yes or No based on gift card enabled or not. /// </summary> /// <param name="val">Value of the Gift Card enabled</param> /// <returns>Returns string presentation of the Gift Card enabled</returns> protected string GetYesNo(bool? val) { if (val.HasValue) return val.Value ? "YES" : "NO"; return string.Empty; } /// <summary> /// Get datetime string /// </summary> /// <param name="utcTime">Datetime instance</param> /// <returns>Returns the datetime string</returns> protected string GetDateTimeString(DateTime utcTime) { return DateHelper.ConvertUtcToStoreTime(_hccApp, utcTime).ToShortDateString(); } } } }
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NSeed; using SmokeTests.ServiceConfiguration; namespace SmokeTests.Seeds { class SeedingSetup : ISeedingSetup { public IConfiguration BuildConfiguration(string[] commandLineArguments) { return new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) .AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: false) .AddJsonFile("appsettings.Seeds.json", optional: false, reloadOnChange: false) .AddEnvironmentVariables() .AddCommandLine(commandLineArguments) .Build(); } public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { ServiceConfigurator.ConfigureServices(services, configuration); } } }
using Skahal.Common; namespace Buildron.Domain.Mods { /// <summary> /// The kind of preference that a mod can expose to an user. /// </summary> public enum PreferenceKind { /// <summary> /// String value. /// </summary> String, /// <summary> /// Integer value. /// </summary> Int, /// <summary> /// Float value. /// </summary> Float, /// <summary> /// Boolean value. /// </summary> Bool } /// <summary> /// Represents a preference that a mod can expose to an user. /// </summary> public class Preference { #region Fields private object m_defaultValue; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:Buildron.Domain.Mods.Preference"/> class. /// </summary> /// <param name="name">The preference name.</param> public Preference(string name) : this(name, name) { } /// <summary> /// Initializes a new instance of the <see cref="T:Buildron.Domain.Mods.Preference"/> class. /// </summary> /// <param name="name">The preference name.</param> /// <param name="title">The preference title. This value will be shown to the user.</param> public Preference(string name, string title) : this(name, title, PreferenceKind.String) { } /// <summary> /// Initializes a new instance of the <see cref="T:Buildron.Domain.Mods.Preference"/> class. /// </summary> /// <param name="name">The preference name.</param> /// <param name="title">The preference title. This value will be shown to the user.</param> /// <param name="kind">The preference kind.</param> public Preference(string name, string title, PreferenceKind kind) : this(name, title, kind, null) { } /// <summary> /// Initializes a new instance of the <see cref="T:Buildron.Domain.Mods.Preference"/> class. /// </summary> /// <param name="name">The preference name.</param> /// <param name="title">The preference title. This value will be shown to the user.</param> /// <param name="kind">The preference kind.</param> /// <param name="defaultValue">The default value.</param> public Preference(string name, string title, PreferenceKind kind, object defaultValue) { Throw.AnyNull(new { name, title, kind }); Name = name; Title = title; Kind = kind; DefaultValue = defaultValue; } #endregion #region Properties /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Gets or sets the title. /// </summary> /// <value>The title.</value> public string Title { get; set; } /// <summary> /// Gets or sets the description. /// </summary> /// <value>The description.</value> public string Description { get; set; } /// <summary> /// Gets or sets the kind. /// </summary> /// <value>The kind.</value> public PreferenceKind Kind { get; set; } /// <summary> /// Gets or sets the default value. /// </summary> /// <value>The default value.</value> public object DefaultValue { get { if (m_defaultValue == null) { switch (Kind) { case PreferenceKind.Bool: m_defaultValue = false; break; case PreferenceKind.Float: m_defaultValue = 0f; break; case PreferenceKind.Int: m_defaultValue = 0; break; case PreferenceKind.String: // Empty is not the default for string, but is a more suitable for preferences. m_defaultValue = string.Empty; break; } } return m_defaultValue; } set { m_defaultValue = value; } } #endregion } }
using System; using LimitedLiability.Content; using LimitedLiability.Descriptors; using System.Collections.Generic; namespace LimitedLiability.UserInterface { public class PurchasableItemPlacedEventArgs : EventArgs { public IPurchasable PurchasableItem { get; private set; } public IReadOnlyList<MapCell> HoveredMapCells { get; private set; } public PurchasableItemPlacedEventArgs(IPurchasable purchasableItem, IReadOnlyList<MapCell> hoveredMapCells) { PurchasableItem = purchasableItem; HoveredMapCells = hoveredMapCells; } } }
using System; using System.Collections.Generic; using System.Linq; public class GreedyTimes { private static readonly Dictionary<string, decimal> goldBag = new Dictionary<string, decimal>(); private static readonly Dictionary<string, decimal> gemBag = new Dictionary<string, decimal>(); private static readonly Dictionary<string, decimal> cashBag = new Dictionary<string, decimal>(); private static decimal allAmount; private static decimal goldAmount; private static decimal gemAmount; private static decimal cashAmount; public static void Main() { var bagCapacity = decimal.Parse(Console.ReadLine()); var itemQuantityPairs = Console.ReadLine() .Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries) .ToArray(); for (var index = 0; index < itemQuantityPairs.Length; index += 2) { var item = itemQuantityPairs[index]; var quantity = decimal.Parse(itemQuantityPairs[index + 1]); if (bagCapacity < allAmount + quantity) continue; Func<string, bool> gold = g => g.ToLower().Equals("Gold".ToLower()); Func<string, bool> gem = g => g.ToLower().EndsWith("Gem".ToLower()) && g.Length >= 4; Func<string, bool> cash = c => { var allIsLetter = true; foreach (var l in c) if (!char.IsLetter(l)) allIsLetter = false; return c.Length == 3 && allIsLetter; }; var hasAddingItem = false; if (Validate(item, gold)) { hasAddingItem = AddGold(new Item(item, quantity)); if (hasAddingItem) goldAmount += quantity; } else if (Validate(item, gem)) { hasAddingItem = AddGem(new Item(item, quantity)); if (hasAddingItem) gemAmount += quantity; } else if (Validate(item, cash)) { hasAddingItem = AddCash(new Item(item, quantity)); if (hasAddingItem) cashAmount += quantity; } if (hasAddingItem) allAmount += quantity; } Print(); } private static bool Validate(string item, Func<string, bool> isValid) { return isValid(item); } private static void Print() { if (goldBag.Any()) { PrintBag(goldBag, "Gold", goldAmount); if (gemBag.Any()) { PrintBag(gemBag, "Gem", gemAmount); if (cashBag.Any()) PrintBag(cashBag, "Cash", cashAmount); } } } private static void PrintBag(Dictionary<string, decimal> bag, string type, decimal amount) { Console.WriteLine($"<{type}> ${amount}"); foreach (var item in bag.OrderByDescending(k => k.Key).ThenBy(v => v.Value)) Console.WriteLine($"##{item.Key} - {item.Value}"); } private static bool AddGold(Item item) { if (!goldBag.ContainsKey(item.Name)) goldBag.Add(item.Name, 0); goldBag[item.Name] += item.Quantity; return true; } private static bool AddGem(Item item) { if (goldAmount < gemAmount + item.Quantity) return false; if (!gemBag.ContainsKey(item.Name)) gemBag.Add(item.Name, 0); gemBag[item.Name] += item.Quantity; return true; } private static bool AddCash(Item item) { if (gemAmount < cashAmount + item.Quantity) return false; if (!cashBag.ContainsKey(item.Name)) cashBag.Add(item.Name, 0); cashBag[item.Name] += item.Quantity; return true; } } public class Item { public Item(string name, decimal quantity) { Name = name; Quantity = quantity; } public string Name { get; set; } public decimal Quantity { get; set; } private bool Equals(Item other) { return Name == other.Name; } public override bool Equals(object obj) { var other = obj as Item; if (other == null) return false; return Equals(other); } public override int GetHashCode() { return GetHashCode(); } public override string ToString() { return $"##{Name} - {Quantity}"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gun : MonoBehaviour { public GameObject bullet = null; // 발사할 총알 오브젝트 public Transform shotTransform = null; // 총알이 발사될 위치 public float interval = 1.0f; // 총알을 발사하는 간격(방아쇠를 당기는 간격) public int shots = 5; // 한번 발사할때 몇연사를 할 것인가 public float rateOfFire = 0.1f; // 연사를 할 때 발사되는 간격 private IEnumerator shot = null; private bool isShoot = false; private void Awake() { shot = Shot(); } public void Initialize(float _interval, int _shots, float _rateOfFire) { this.interval = _interval; this.shots = _shots; this.rateOfFire = _rateOfFire; } public void StartFire() { if (isShoot == false) { StartCoroutine(shot); isShoot = true; } } public void StopFire() { StopCoroutine(shot); isShoot = false; } IEnumerator Shot() { while (true) { yield return new WaitForSeconds(interval - shots * rateOfFire); // 1초-0.1초*5 대기 // 총알 연사 시작 for (int i = 0; i < shots; i++) { //Instantiate(bullet, shotTransform.position, shotTransform.rotation); // 총알 생성 bullet = MemoryPool.Inst.GetObject(); bullet.transform.position = shotTransform.position; bullet.transform.rotation = shotTransform.rotation; bullet.transform.parent = MemoryPool.Inst.parent; yield return new WaitForSeconds(rateOfFire); // 0.1초 대기 } } } }
using System.Collections.Generic; using System.Threading.Tasks; using Ditch.EOS.Contracts.Eosio.Actions; using Ditch.EOS.Contracts.Eosio.Structs; using Ditch.EOS.Models; using Ditch.EOS.Tests.Apis; using NUnit.Framework; namespace Ditch.EOS.Tests.Examples { [TestFixture] public class HowToRunCommandsFromContractTest : BaseTest { [Test] public async Task Buyram_SuccessTest() { var op = new BuyramAction { Account = BuyramAction.ContractName, Args = new Buyram { Payer = User.Login, Receiver = User.Login, Quant = new Asset("100.0000 EOS") }, Authorization = new[] { new PermissionLevel { Actor = User.Login, Permission = "active" } } }; var resp = await Api.BroadcastActionsAsync(new[] { op }, new List<byte[]> { User.PrivateActiveKey }, CancellationToken).ConfigureAwait(false); WriteLine(resp); Assert.IsFalse(resp.IsError); } [Test] public async Task Delegatebw_SuccessTest() { var op = new DelegatebwAction { Account = DelegatebwAction.ContractName, Args = new Delegatebw { From = User.Login, Receiver = User.Login, StakeCpuQuantity = new Asset("100.0000 EOS"), StakeNetQuantity = new Asset("100.0000 EOS"), Transfer = false }, Authorization = new[] { new PermissionLevel { Actor = User.Login, Permission = "active" } } }; var resp = await Api.BroadcastActionsAsync(new[] { op }, new List<byte[]> { User.PrivateActiveKey }, CancellationToken).ConfigureAwait(false); WriteLine(resp); Assert.IsFalse(resp.IsError); } [Test] public async Task Undelegatebw_SuccessTest() { var op = new UndelegatebwAction { Account = UndelegatebwAction.ContractName, Args = new Undelegatebw { From = User.Login, Receiver = User.Login, UnstakeCpuQuantity = new Asset("100.0000 EOS"), UnstakeNetQuantity = new Asset("100.0000 EOS") }, Authorization = new[] { new PermissionLevel { Actor = User.Login, Permission = "active" } } }; var resp = await Api.BroadcastActionsAsync(new BaseAction[] { op }, new List<byte[]> { User.PrivateActiveKey }, CancellationToken).ConfigureAwait(false); WriteLine(resp); Assert.IsFalse(resp.IsError); } [Test] public async Task Transfer_SuccessTest() { var op = new Contracts.EosioToken.Actions.TransferAction { Account = "eosio.token", Args = new Contracts.EosioToken.Structs.Transfer { From = User.Login, To = "binancecleos", Quantity = new Asset("100.0000 EOS"), Memo = "000000000" }, Authorization = new[] { new PermissionLevel { Actor = User.Login, Permission = "active" } } }; var resp = await Api.BroadcastActionsAsync(new[] { op }, new List<byte[]> { User.PrivateActiveKey }, CancellationToken).ConfigureAwait(false); WriteLine(resp); Assert.IsFalse(resp.IsError); } } }
@{ var message = "Hello, World!"; } @message
namespace FireDaemon.Api { using System.IO; using System.Net; using Newtonsoft.Json; public class FireDaemonApiClient { public FireDaemonApiClient(string url) { if (!url.EndsWith("/")) { url += "/"; } BaseUrl = url; } public string BaseUrl { get; set; } public string AuthenticationCookie { get; set; } public bool Authenticate(string username, string password) { var queryString = $"username={username}&password={password}"; var httpWebRequest = WebRequest.Create($"{BaseUrl}login") as HttpWebRequest; httpWebRequest.AllowAutoRedirect = false; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = queryString.Length; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(queryString); streamWriter.Flush(); streamWriter.Close(); } var httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; AuthenticationCookie = httpWebResponse.Headers.Get("Set-Cookie"); return !string.IsNullOrEmpty(AuthenticationCookie); } public bool StartService(string serviceName) { return MakeRequest(serviceName, true); } public bool StopService(string serviceName) { return MakeRequest(serviceName, false); } private bool MakeRequest(string serviceName, bool start) { var action = start ? "start" : "stop"; var webClient = new WebClient(); webClient.Headers.Add(HttpRequestHeader.Cookie, AuthenticationCookie); var requestUrl = $"{BaseUrl}fd/{action}ajax?svcname={serviceName}"; var response = webClient.DownloadString(requestUrl); var deserialised = JsonConvert.DeserializeObject<ApiResponse>(response); return (deserialised?.ResultType ?? string.Empty) == "success"; } } }
using System; using System.Collections.Generic; using NZap.Entities; namespace Securitytesting.Helpers { public static class AlertHelper { public static void PrintAlertsToConsole(ICollection<IAlertResult> alerts) { foreach (var alert in alerts) { Console.WriteLine(alert.Alert + Environment.NewLine + alert.Cweid + Environment.NewLine + alert.Url + Environment.NewLine + alert.Wascid + Environment.NewLine + alert.Evidence + Environment.NewLine + alert.Param + Environment.NewLine ); } } } }
// Copyright (c) Nicola Biancolini, 2019. All rights reserved. // Licensed under the MIT license. See the LICENSE file in the project root for full license information. using System; using Cake.Board.Testing; using Cake.Testing; namespace Cake.Board.AzureBoards.Tests.Fixtures { public class WorkItemCommandFixture : IDisposable { private FakeCakeContext _context; public WorkItemCommandFixture() => this._context = new FakeCakeContext(logBehaviour: () => new FakeLog()); public void Dispose() => this._context = null; } }
//////////////////////////////////////////////////////////////////////////////// // // Microsoft Research Singularity // // Copyright (c) Microsoft Corporation. All rights reserved. // // File: MetaDataParser.cs // // TODO: fix comments in this file // // Note: This is a best-approximation of statically determinable metadata. // We can create a few general properties of an application, and we // can read the ConsoleCategory, Category, and DriverCategory attributes // using System; using System.Collections; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Xml; using Bartok.MSIL; public class ManifestBuilder { // // Note - This is a rather crude recursive descent parser // // This parser only deals in relatively flat xml, and as such we can use // a very straightforward parse methodology: // for a class decorated with a tag that is in the "triggers" list // - start a new xml tag // - check every decoration on that class according to the classAttributes // rules, and for each match add a child // - check every field in the class according to the fieldAttributes // rules, and for each match add a child private class ParseRules { public TriggerDefinition[] triggers; public ClassDefinition[] classAttributes; public FieldDefinition[] fieldAttributes; public ParseRules(ParseRules inheritFrom, TriggerDefinition[] triggers, ClassDefinition[] classAttributes, FieldDefinition[] fieldAttributes) { this.triggers = triggers; if (inheritFrom != null) { this.classAttributes = Inherit(inheritFrom.classAttributes, classAttributes); this.fieldAttributes = Inherit(inheritFrom.fieldAttributes, fieldAttributes); } else { this.classAttributes = classAttributes; this.fieldAttributes = fieldAttributes; } } private static ClassDefinition[] Inherit(ClassDefinition[] root, ClassDefinition[] grow) { ClassDefinition[] target = new ClassDefinition[root.Length + grow.Length]; int j = 0; for (int i = 0; i < root.Length; i++, j++) { target[j] = root[i]; } for (int i = 0; i < grow.Length; i++, j++) { target[j] = grow[i]; } return target; } private static FieldDefinition[] Inherit(FieldDefinition[] root, FieldDefinition[] grow) { FieldDefinition[] target = new FieldDefinition[root.Length + grow.Length]; int j = 0; for (int i = 0; i < root.Length; i++, j++) { target[j] = root[i]; } for (int i = 0; i < grow.Length; i++, j++) { target[j] = grow[i]; } return target; } } // Construct the parsing tables. private static readonly ParseRules[] rules; static ManifestBuilder() { ParseRules categoryRules = new ParseRules( null, // "triggers" new TriggerDefinition[] { new TriggerDefinition("category", null, "Microsoft.Singularity.Configuration.CategoryAttribute", "Microsoft.Singularity.Configuration.CategoryDeclaration", new string [] {"name"}), }, // "class" attributes new ClassDefinition[] {}, // "field" attributes new FieldDefinition[] { // NB: the constructor fields on these are handled specially, unlike // everything else in this tool. This is indicated by the "true" // value for the last parameter to the constructor // TODO: is this correct? Should Endpoint declarations in // ConsoleCategories and Configuration be given names so that they are more // human-configurable? Will an app ever declare multiple Endpoints of // the same type and require the kernel to user to patch those identical // endpoints to different (and conflicting) apps? Could this problem be // addressed via stronger typing? new EndpointDefinition("endpoints", "extension", "Microsoft.Singularity.Configuration.ExtensionEndpointAttribute", "Microsoft.Singularity.Channels.TRef_2" + "<Microsoft.Singularity.Extending." + "ExtensionContract+Exp,Microsoft.Singularity" + ".Extending.ExtensionContract+Start>"), new ServiceEndpointDefinition("endpoints", "serviceProvider", "Microsoft.Singularity.Configuration.ServiceEndpointAttribute", "Microsoft.Singularity.Channels.TRef_2" + "<Microsoft.Singularity.Directory." + "ServiceProviderContract+Exp,Microsoft." + "Singularity.Directory.ServiceProviderContract" + "+Start>"), // TODO: - the inheritance on this is not correct new EndpointDefinition("endpoints", "endpoint", "Microsoft.Singularity.Configuration.EndpointAttribute", null), new EndpointDefinition("endpoints", "customEndpoint", "Microsoft.Singularity.Configuration.CustomEndpointAttribute", null), new EndpointDefinition("endpoints", "inputPipe", "Microsoft.Singularity.Configuration.InputEndpointAttribute", null, new string [] {"Kind"}), new EndpointDefinition("endpoints", "outputPipe", "Microsoft.Singularity.Configuration.OutputEndpointAttribute", null, new string [] {"Kind"}), new ParameterDefinition("StringParameters", "StringParameter", "Microsoft.Singularity.Configuration.StringParameterAttribute", "STRING", new string [] {"Name"}), new ParameterDefinition("LongParameters", "LongParameter", "Microsoft.Singularity.Configuration.LongParameterAttribute", "I8", new string [] {"Name"}), new ParameterDefinition("BoolParameters", "BoolParameter", "Microsoft.Singularity.Configuration.BoolParameterAttribute", "BOOLEAN", new string [] {"Name"}), new ParameterDefinition("StringArrayParameters", "StringArrayParameter", "Microsoft.Singularity.Configuration.StringArrayParameterAttribute", "SZARRAY", new string [] {"Name"}), } ); ParseRules driverCategoryRules = new ParseRules( categoryRules, // inherit "class" and "field" rules from category. // "triggers" new TriggerDefinition[] { new TriggerDefinition("category", "driver", "Microsoft.Singularity.Io.DriverCategoryAttribute", "Microsoft.Singularity.Io.DriverCategoryDeclaration"), }, // "class" attributes new ClassDefinition[] { new ClassDefinition("device", "Microsoft.Singularity.Io.SignatureAttribute", new string [] {"signature"}), new ClassDefinition("enumerates", "Microsoft.Singularity.Io.EnumeratesDeviceAttribute", new string [] {"signature"}), }, // "field" attributes new FieldDefinition[] { new FieldDefinition("dynamicHardware", "ioPortRange", "Microsoft.Singularity.Io.IoPortRangeAttribute", "Microsoft.Singularity.Io.IoPortRange", new string [] {"id"}, new string [] {"Default","baseAddress", "Length","rangeLength", "Shared", "shared"}), new FieldDefinition("fixedHardware", "ioPortRange", "Microsoft.Singularity.Io.IoFixedPortRangeAttribute", "Microsoft.Singularity.Io.IoPortRange", new string [] {"id"}, new string [] {"Base","baseAddress", "Length","rangeLength", "Shared", "shared"}, new string [] {"fixed", "true"}), new FieldDefinition("dynamicHardware", "ioIrqRange", "Microsoft.Singularity.Io.IoIrqRangeAttribute", "Microsoft.Singularity.Io.IoIrqRange", new string [] {"id"}, new string [] {"Default","baseAddress", "Length","rangeLength", "Shared", "shared"}, new string [] {"rangeLength", "1"}), new FieldDefinition("fixedHardware", "ioIrqRange", "Microsoft.Singularity.Io.IoFixedIrqRangeAttribute", "Microsoft.Singularity.Io.IoIrqRange", new string [] {"id"}, new string [] {"Base","baseAddress", "Length","rangeLength", "Shared", "shared"}, new string [] {"fixed", "true", "rangeLength", "1"}), new FieldDefinition("dynamicHardware", "ioDmaRange", "Microsoft.Singularity.Io.IoDmaRangeAttribute", "Microsoft.Singularity.Io.IoDmaRange", new string [] {"id"}, new string [] {"Default","baseAddress", "Length","rangeLength", "Shared", "shared"}, new string [] {"rangeLength", "1"}), new FieldDefinition("dynamicHardware", "ioMemoryRange", "Microsoft.Singularity.Io.IoMemoryRangeAttribute", "Microsoft.Singularity.Io.IoMemoryRange", new string [] {"id"}, new string [] {"Default","baseAddress", "Length","rangeLength", "Shared", "shared"}), new FieldDefinition("fixedHardware", "ioMemoryRange", "Microsoft.Singularity.Io.IoFixedMemoryRangeAttribute", "Microsoft.Singularity.Io.IoMemoryRange", new string [] {"id"}, new string [] {"Base","baseAddress", "Length","rangeLength", "Shared", "shared", "AddressBits", "addressBits", "Alignment", "alignment"}, new string [] {"fixed", "true"}), } ); ParseRules consoleCategoryRules = new ParseRules( categoryRules, // inherit "class" and "field" rules from category. // "triggers" new TriggerDefinition[] { new TriggerDefinition("category", "console", "Microsoft.Singularity.Configuration.ConsoleCategoryAttribute", "Microsoft.Singularity.Configuration.ConsoleCategoryDeclaration"), }, // "class" attributes new ClassDefinition[] { }, // "field" attributes new FieldDefinition[] { } ); rules = new ParseRules[3] { driverCategoryRules, categoryRules, consoleCategoryRules, }; } ////////////////////////////////////////////////////////////////////////// // // the base path of the file cache private String cache; // the list of assembly files private ArrayList assemblies; // The metadata resolver private MetaDataResolver resolver; // the output file private XmlDocument manifest; // the process node private XmlNode process; // the Bartok/code generation parameters. private XmlNode codegen; // the linker parameters. private XmlNode linker; private int warningCount; private int errorCount; public ManifestBuilder(String cache, ArrayList assemblies) { this.cache = cache.ToLower(); this.assemblies = assemblies; // create a blank manifest without an <?xml> header: manifest = new XmlDocument(); } // create a manifest for an app, without looking at any assemblies // this creates the stub manifest into which each assembly's info will // go public bool CreateNewManifest(string appname, string x86filename) { warningCount = 0; errorCount = 0; // Create this.resolver using this.assemblyfilename InitializeResolver(); // Create the basic XML tree. XmlNode application = AddElement(manifest, "application"); AddAttribute(application, "name", appname); process = AddElement(application, "process"); AddAttribute(process, "id", "0"); AddAttribute(process, "main", "true"); AddAttribute(process, "path", StripPathFromPath(x86filename)); AddAttribute(process, "cache", StripCacheFromPath(x86filename)); bool seenPublisher = false; XmlNode privileges = null; // here we assume that the first assembly is the app assembly // extract the publisher name from there MetaData md0 = (MetaData)resolver.MetaDataList[0]; MetaDataAssembly mda0 = (MetaDataAssembly)md0.Assemblies[0]; if (mda0.CustomAttributes != null) { foreach (MetaDataCustomAttribute ca in mda0.CustomAttributes) { if (ca.Name == "Microsoft.Singularity.Security.ApplicationPublisherAttribute") { if (!seenPublisher && ca.FixedArgs != null && ca.FixedArgs[0] != null) { AddAttribute(application, "publisher", (string)ca.FixedArgs[0]); seenPublisher = true; } } else if (ca.Name == "Microsoft.Singularity.Security.AssertPrivilegeAttribute") { if (ca.FixedArgs != null && ca.FixedArgs[0] != null) { if (privileges == null) privileges = AddElement(application, "privileges"); XmlNode privilege = AddElement(privileges, "privilege"); AddAttribute(privilege, "name", (string)ca.FixedArgs[0]); } } } } // Create the list of assemblies. XmlNode assemblies = AddElement(process, "assemblies"); foreach (MetaData md in resolver.MetaDataList) { MetaDataAssembly mda = (MetaDataAssembly)md.Assemblies[0]; string file = md.Name; string assemblyname = StripPathFromPath(file); XmlNode assembly = AddElement(assemblies, "assembly"); AddAttribute(assembly, "name", assemblyname); if (mda.MajorVersion != 0 || mda.MinorVersion != 0 || mda.BuildNumber != 0 || mda.RevisionNumber != 0) { AddAttribute(assembly, "version", String.Format("{0}.{1}.{2}.{3}", mda.MajorVersion, mda.MinorVersion, mda.BuildNumber, mda.RevisionNumber)); } if (mda.PublicKey != null & mda.PublicKey.Length > 0) { AddAttribute(assembly, "publickey", String.Format("{0}", KeyToString(mda.PublicKey))); } if (mda.Locale != null && mda.Locale != "") { AddAttribute(assembly, "locale", mda.Locale); } AddAttribute(assembly, "cache", StripCacheFromPath(file)); } // Create a placeholder for // now go through every class in the assembly to locate ConsoleCategory, // Category, and DriverCategory attributes int categoryIndex = 0; XmlNode categories = null; foreach (MetaData md in resolver.MetaDataList) { // NB: md.TypeDefs is a flat list of all classes in this assembly, // regardless of nesting foreach (MetaDataTypeDefinition type in md.TypeDefs) { for (int i = 0; i < rules.Length; i++) { if (ProcessType(type, rules[i], process, ref categoryIndex, ref categories)) { break; } } } } if (errorCount != 0) { return false; } return true; } public bool AddCodegenParameter(string param) { if (codegen == null) { codegen = AddElement(process, "codegen"); } XmlNode node = AddElement(codegen, "parameter"); AddAttribute(node, "value", param); return true; } public bool AddLinkerParameter(string param) { if (linker == null) { linker = AddElement(process, "linker"); } XmlNode node = AddElement(linker, "parameter"); AddAttribute(node, "value", param); return true; } public void Save(XmlTextWriter writer) { manifest.Save(writer); } ///////////////////////////////////////////// Methods to help with errors. // private static string LastName(string value) { if (value != null) { int period = value.LastIndexOf('.'); if (period > 0 && period < value.Length) { return value.Substring(period + 1); } } return value; } public void Error(string message, params object[] args) { Console.Write("mkmani: Error: "); Console.WriteLine(message, args); errorCount++; } private void Warning(string message, params object[] args) { Console.Write("mkmani: Warning: "); Console.WriteLine(message, args); warningCount++; } //////////////////////////////////////////////// Methods to help with XML. // private XmlNode AddElement(XmlNode parent, string name) { XmlNode element = manifest.CreateNode(XmlNodeType.Element, name, ""); if (parent != null) { parent.AppendChild(element); } return element; } public void AddAttribute(XmlNode node, string name, string value) { XmlAttribute attr = manifest.CreateAttribute(name); attr.Value = value; node.Attributes.Append(attr); } // this method creates a MetaData resolver and loads all the assemblies into // it private void InitializeResolver() { resolver = new MetaDataResolver(assemblies, new ArrayList(), new DateTime(), false, false); MetaDataResolver.ResolveCustomAttributes( new MetaDataResolver[] {resolver}); } // parse utility function to ensure that a type's inheritance matches the // inheritance specified in the TokenDefinition public bool MatchInheritance(string derivesFromClass, MetaDataTypeDefinition type) { //Console.WriteLine("derives=({0}), type = {1}", // derivesFromClass, // type.Extends == null ? null: ((MetaDataTypeReference)type.Extends).FullName); // // if (derivesFromClass != null) { // if (type.Extends == null || // ((MetaDataTypeReference)type.Extends).FullName != // derivesFromClass) { // return false; // } // } // return true; } // parse utility function to ensure that the class of a field matches the // class name specified in a TokenDefinition public bool MatchFieldType(FieldDefinition rule, MetaDataField field) { if (rule.matchClassType != null) { MetaDataObject classobj = field.Signature.FieldType.ClassObject; string classtype = ""; // Since we can pass in different objects as field, we need to be // careful here about how we get the class type if (classobj is MetaDataTypeDefinition) { classtype = ((MetaDataTypeDefinition) classobj).FullName; } else if (classobj is MetaDataTypeReference) { classtype = ((MetaDataTypeReference) classobj).FullName; } else if (classobj == null) { classtype = field.Signature.FieldType.ElementType.ToString(); } if (classtype != rule.matchClassType) { Error("{0} can't be applied to {1}", LastName(rule.attribute), field.FullName); Error("{0}does not match {1}", classtype, rule.matchClassType); return false; } } return true; } // This is the only way we create XML tags (except for Endpoints) public XmlNode CreateNode(MetaDataCustomAttribute data, TokenDefinition rule) { XmlNode node = AddElement(null, rule.xmlTagName); // make an attribute for each constructor argument if (data.FixedArgs.Length != 0) { for (int i = 0; i < data.FixedArgs.Length; i++) { string name = rule.constructorFields[i]; if (data.FixedArgs[i] == null) { AddAttribute(node, name, ""); } else { string value = data.FixedArgs[i].ToString(); AddAttribute(node, name, value); } } } // make an attribute for each constructor-time property for (int i = 0; i < data.NamedArgs.Length; i++) { string name = rule.FindPropertyReplacement(data.NamedArgs[i].Name); object arg = data.NamedArgs[i].Value; string value; if (arg == null) { // REVIEW: do we want "" or null here? value = null; } else { value = data.NamedArgs[i].Value.ToString(); if (arg is System.UInt32) { // We output unsigned types as 0x because they are generally // hardware-related numbers which are documented in hexadecimal. value = String.Format("0x{0:x}", arg); } } AddAttribute(node, name, value); } // make an attribute for each default field for (int i = 0; i < rule.defaultFields.Length; i += 2) { string name = rule.defaultFields[i]; AddAttribute(node, name, rule.defaultFields[i+1]); } return node; } private XmlNode GetEndpointHierarchy(string nodeName, string endpointType) { XmlNode node = AddElement(null, nodeName); MetaDataTypeDefinition epType = resolver.ResolveName(endpointType); XmlNode oldChild = null; XmlNode newChild = null; while (epType.FullName != "Microsoft.Singularity.Channels.Endpoint") { newChild = manifest.CreateNode(XmlNodeType.Element, "inherit", ""); AddAttribute(newChild, "name", epType.FullName); if (oldChild == null) { node.AppendChild(newChild); } else { node.InsertBefore(newChild, oldChild); } oldChild = newChild; string nextName; if (epType.Extends is MetaDataTypeReference) { nextName = ((MetaDataTypeReference) epType.Extends).FullName; if (nextName == "Exp" || nextName == "Imp") { MetaDataTypeReference mdtr = (MetaDataTypeReference) epType.Extends; nextName = ((MetaDataTypeReference)mdtr.ResolutionScope).FullName + "." + nextName; } } else if (epType.Extends is MetaDataTypeDefinition) { nextName = ((MetaDataTypeDefinition) epType.Extends).FullName; } else { return node; } epType = resolver.ResolveName(nextName); } newChild = manifest.CreateNode(XmlNodeType.Element, "inherit", ""); AddAttribute(newChild, "name", epType.FullName); if (oldChild == null) { node.AppendChild(newChild); } else { node.InsertBefore(newChild, oldChild); oldChild = newChild; } return node; } public XmlNode CreateNodeIndexed(MetaDataCustomAttribute data, TokenDefinition rule, int index ) { XmlNode node = CreateNode(data, rule); AddAttribute(node, "id", index.ToString()); return node; } // Endpoints are special in a lot of ways, and require a special method public XmlNode CreateEndpointNode(MetaDataCustomAttribute data, EndpointDefinition rule, int index) { // assume that the constructor to an endpoint always takes one argument, // and that the argument looks like this: // "<discard*> contractname+Exp*,AssemblyName, Version=foo, // Culture=bar, PublicKeyToken=fbar" // we'll parse this to get all the attributes of the top-level tag, and // then parse field that is being decorated to get the rest of the // information we need. // get the type of the field that is decorated: MetaDataObject t = (MetaDataObject) ((MetaDataField)data.Parent).Signature.FieldType.ClassObject; // split the field to get the parts we need string typeName = t.FullName; typeName = typeName.Replace("<", ","); typeName = typeName.Replace(">", ""); typeName = typeName.Replace("+", ","); string [] nameParts = typeName.Split(','); string contractName = nameParts[1]; string impName = contractName + ".Imp"; string expName = contractName + ".Exp"; string stateName = contractName + "." + nameParts[4]; XmlNode impNode = GetEndpointHierarchy("imp", impName); XmlNode expNode = GetEndpointHierarchy("exp", expName); MetaDataTypeDefinition r1 = resolver.ResolveName(impName); MetaDataTypeDefinition r2 = resolver.ResolveName(expName); MetaDataTypeDefinition r3 = resolver.ResolveName(stateName); string startState = ""; for (int i = 0; i < r3.Fields.Length; i++) { if (r3.Fields[i].Name == "Value") { startState = r3.Fields[0].DefaultValue.ToString(); break; } } XmlNode node = manifest.CreateNode(XmlNodeType.Element, rule.xmlTagName, ""); node.AppendChild(impNode); node.AppendChild(expNode); AddAttribute(node, "id", index.ToString()); if (startState != "") { AddAttribute(node, "startStateId", startState); } // Contract name comes from either the attribute argument // or the TRef type depending on the endpoint kind rule.AddContractNameAttribute(this, node, data, contractName); // add an attribute for each constructor argument if there is one // This should only be true for input/ouput pipes if (rule.constructorFields != null && rule.constructorFields.Length != 0) { if (data.FixedArgs.Length != 0) { for (int i = 0; i < data.FixedArgs.Length; i++) { if (rule.constructorFields[i] != null) { string name = rule.constructorFields[i]; if (data.FixedArgs[i] == null) { AddAttribute(node, name, ""); } else { string value = data.FixedArgs[i].ToString(); AddAttribute(node, name, value); } } else { Console.WriteLine(" fixed=({0}), no matching constructor?", data.FixedArgs[i] == null? null : data.FixedArgs[i].ToString() ); } } } } return node; } // this does the processing of each field-level decoration on a type, // according to rules.fieldAttributes private void ProcessFieldAttributes(MetaDataTypeDefinition type, FieldDefinition[] rules, XmlNode parent) { int endpointIndex = 0; int intParameterIndex = 0; int stringParameterIndex = 0; int stringArrayParameterIndex = 0; int boolParameterIndex = 0; foreach (MetaDataField field in type.Fields) { if (field.CustomAttributes == null) { continue; } foreach (MetaDataCustomAttribute attrib in field.CustomAttributes) { foreach (FieldDefinition rule in rules) { if (attrib.Name == rule.attribute) { // type check it if (MatchFieldType(rule, field)) { // custom step if Endpoint: XmlNode node; EndpointDefinition edrule = rule as EndpointDefinition; if (edrule != null) { node = CreateEndpointNode(attrib, edrule, endpointIndex++); } else if (rule is ParameterDefinition) { int index; if (rule.matchClassType == "I8") { index = intParameterIndex++; } else if (rule.matchClassType == "STRING") { index = stringParameterIndex++; } else if (rule.matchClassType == "BOOLEAN") { index = boolParameterIndex++; } else if (rule.matchClassType == "SZARRAY") { index = stringArrayParameterIndex++; } else { index =999; } node = CreateNodeIndexed(attrib, rule, index); } else { node = CreateNode(attrib, rule); } if (node != null) { XmlNode group = parent[rule.xmlGroup]; if (group == null) { group = AddElement(parent, rule.xmlGroup); } group.AppendChild(node); } } } } } } } // this does the processing of each class-level decoration on a type, as // described in rules.classAttributes private void ProcessClassAttributes(MetaDataTypeDefinition type, ClassDefinition[] rules, XmlNode parent) { if (type.CustomAttributes == null) { return; } foreach (MetaDataCustomAttribute attrib in type.CustomAttributes) { foreach (ClassDefinition rule in rules) { if (attrib.Name == rule.attribute) { XmlNode node = CreateNode(attrib, rule); parent.AppendChild(node); } } } } // this kicks off the processing of a type; see if it is decorated by // rules.triggers, and if so, then build an xml node and process the rest // of the rules object for this type private bool ProcessType(MetaDataTypeDefinition type, ParseRules rules, XmlNode parent, ref int categoryIndex, ref XmlNode categories) { if (type.CustomAttributes == null) { return false; } foreach (MetaDataCustomAttribute attrib in type.CustomAttributes) { foreach (TriggerDefinition rule in rules.triggers) { if (attrib.Name == rule.attribute) { // only process this entry if the ancestry is valid if (MatchInheritance(rule.derivesFromClass, type)) { if (categoryIndex == 0) { categories = AddElement(parent,"categories"); } // create an xml node from (attrib, rule) XmlNode node = CreateNode(attrib, rule); AddAttribute(node, "id", (categoryIndex++).ToString()); if (rule.categoryName != null) { AddAttribute(node, "name", rule.categoryName); } AddAttribute(node, "class", type.FullName); // then do the rules.classDefinitions work ProcessClassAttributes(type, rules.classAttributes, node); // then do the rules.fieldDefinitions work ProcessFieldAttributes(type, rules.fieldAttributes, node); // then append this xml node to the manifest root doc if (categories == null) { Console.WriteLine(" categories is null at index {0}",categoryIndex); } else { categories.AppendChild(node); } // once we match once, we stop operating on this type return true; } } } } return false; } private String KeyToString(byte[] key) { StringBuilder sb = new StringBuilder(""); int count = key.Length; if (count > 0) { for (int i = 0; i < count; i++) { sb.Append(key[i].ToString("x2")); } } return sb.ToString(); } private String StripPathFromPath(string path) { int index = Math.Max(path.LastIndexOf(':'), Math.Max(path.LastIndexOf('\\'), path.LastIndexOf('/'))); if (index >= 0) { return path.Substring(index + 1); } return path; } private String StripCacheFromPath(string path) { if (cache != null && path.ToLower().StartsWith(cache)) { return path.Substring(cache.Length).Replace('\\', '/'); } return path.Replace('\\', '/'); } // augment a manifest based on the assembly given. This touches: // <assemblies>, <ConsoleCategory>, <category>, and <drivercategory> private void ParseAssemblies(XmlNode assemblies) { } }
using System.Linq; using System.Web.Http; using XamarinCRM.Models; namespace XamarinCRMv2DataService.Controllers { /// <summary> /// Products API. /// </summary> public class ProductController : BaseController<Product> { // GET tables/Product public IQueryable<Product> GetAllProducts() { return Query(); } // GET tables/Product/48D68C86-6EA6-4C25-AA33-223FC9A27959 public SingleResult<Product> GetProduct(string id) { return Lookup(id); } // Other methods go here if your service is to support CUD operations } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace day07 { class Program { static void Main(string[] args) { var lines = File.ReadAllLines("data.txt"); part1(lines); part2(lines); } static void part1(string[] lines) { var dictionary= OrganizeBags(lines); var shinyGoldBag = dictionary["shiny gold"]; var names = GetParentNamesRecursive(shinyGoldBag); Console.WriteLine($"Part1: {names.ToList().Distinct().Count()-1}"); } static void part2(string[] lines){ var dictionary= OrganizeBags(lines); var shinyGoldBag = dictionary["shiny gold"]; Console.WriteLine($"Part1: {CountBagsInsideRecursive(shinyGoldBag)}"); } public static int CountBagsInsideRecursive(Bag bag) { var output = 0; foreach(var bagInside in bag.InsideBags) { var count = bagInside.Item2; var insideBags = CountBagsInsideRecursive(bagInside.Item1); output +=count +insideBags*count; } return output; } public static Dictionary<string,Bag> OrganizeBags(string[] lines) { var dictionary = new Dictionary<string, Bag>(); foreach(var line in lines) { var splitted = line.Split(" contain "); var mainBagName = splitted[0].Replace("bags","").Trim(); if(dictionary.ContainsKey(mainBagName) == false) dictionary.Add(mainBagName,new Bag(){Name = mainBagName}); var b = dictionary[mainBagName]; if(splitted[1].StartsWith("no other bags")) continue; if(splitted[1].Contains(',')) { var insideSplitted = splitted[1].Split(", "); foreach(var split in insideSplitted) { var name = GetName(split); var number = GetNumber(split); if(dictionary.ContainsKey(name) == false) dictionary.Add(name,new Bag(){ Name = name }); b.AddBags(dictionary[name],number); } } else { var name = GetName(splitted[1]); var number = GetNumber(splitted[1]); if(dictionary.ContainsKey(name) == false) dictionary.Add(name,new Bag(){ Name = name }); b.AddBags(dictionary[name],number); } } return dictionary; } public static int GetNumber(string stringToParse) { return Convert.ToInt32(stringToParse.Substring(0,stringToParse.IndexOf(" "))); } public static string GetName(string stringToParse) { var name = stringToParse.Substring(stringToParse.IndexOf(" ")); return name.Replace("bags","").Replace("bag","").Replace(".","").Trim(); } private static List<String> GetParentNamesRecursive(Bag bag) { var list= new List<String>(); list.Add(bag.Name); foreach(var parentBag in bag.ParentBags) { foreach(var parentParent in GetParentNamesRecursive(parentBag)) list.Add(parentParent); } return list; } } public class Bag { public List<Bag> ParentBags {get;set;} = new List<Bag>(); public String Name { get; set; } public List<Tuple<Bag,int>> InsideBags {get;set;} = new List<Tuple<Bag, int>>(); public void AddBags(Bag bag,int amount) { InsideBags.Add(new Tuple<Bag,int>(bag,amount)); bag.ParentBags.Add(this); } public override string ToString() { return $"{Name}, CountOfBags: {InsideBags.Count}"; } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Twitter.Models.UserModels; namespace Twitter.Models.GroupModels { public class Reply { [Key] public int Id { get; set; } public int TweetId { get; set; } [ForeignKey("TweetId")] public virtual Tweet Tweet { get; set; } [Required] [MinLength(1)] [MaxLength(250)] public string Content { get; set; } [Required] public string AuthorId { get; set; } public virtual User Author { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime PublishTime { get; set; } } }
using System; using GTA_RP.Items; namespace GTA_RP.Misc { /// <summary> /// Class that represents loot from loot table /// </summary> public class Loot { public int chance, itemId; // chance is a number from 1 to 1000 which is the drop chance, -1 always drop public Loot(int itemId, int chance) { this.chance = chance; this.itemId = itemId; } } /// <summary> /// Class that represents a loot table /// For example used on fishing spots, could also be used on trasure hunting /// </summary> class LootTable { private int[] lootTable = new int[1000]; private Random random = new Random(); public LootTable(Loot[] loots) { int spot = 0; foreach (Loot loot in loots) { int i = 0; for (; i < loot.chance; i++) lootTable[i + spot] = loot.itemId; spot += i + 1; } for (; spot < 1000; spot++) { lootTable[spot] = -1; } } /// <summary> /// Creates an item for ID /// </summary> /// <param name="id">Item id</param> /// <returns>Item</returns> private Item CreateItemForId(int id) { if (id == -1) { return null; } return ItemManager.Instance().CreateItemForId(id); } /// <summary> /// Returns the item received for 1 roll /// </summary> /// <returns>Null if no item, otherwise return item</returns> public Item GetLoot() { int rdn = random.Next(0, 1000); int itemId = lootTable[rdn]; return CreateItemForId(itemId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeusClientCore.Packets { public abstract class PacketAnswer : Packet { public bool IsSuccess { get; set; } public PacketAnswer(EPacketType type) : base(type) { } public override ushort EstimateCurrentSerializedSize() { return (ushort)(sizeof(bool) + EstimateAnswerCurrentSerializedSize()); } public override void OnDeserialize(byte[] buffer, int index) { bool isSuccess = false; Serializer.DeserializeData(buffer, ref index, out isSuccess); IsSuccess = isSuccess; OnAnswerDeserialize(buffer, index); } public override byte[] OnSerialize() { List<byte> result = new List<byte>(); result.AddRange(Serializer.SerializeData(IsSuccess)); result.AddRange(OnAnswerSerialize()); return result.ToArray(); } public abstract void OnAnswerDeserialize(byte[] buffer, int index); public abstract byte[] OnAnswerSerialize(); public abstract ushort EstimateAnswerCurrentSerializedSize(); } }
using Landis.Species; using Wisc.Flel.GeospatialModeling.Landscapes.DualScale; namespace Landis.Succession { /// <summary> /// Default implementations of some of the reproduction delegates. /// </summary> public static class ReproductionDefaults { /// <summary> /// The default method for determining if there is sufficient light at /// a site for a species to germinate/resprout. /// </summary> public static bool SufficientLight(ISpecies species, ActiveSite site) { byte siteShade = SiteVars.Shade[site]; bool sufficientLight; sufficientLight = (species.ShadeTolerance <= 4 && species.ShadeTolerance > siteShade) || (species.ShadeTolerance == 5 && siteShade > 1); // pg 14, Model description, this ----------------^ may be 2? return sufficientLight; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using SoulsFormats; // Infomation to link a Unity Map to a DS3 MSB for exporting purposes public class MSBAssetLink : MonoBehaviour { public string Interroot; public string MapID; public string MapPath; }
using System; using Metal; namespace Magnesium.Metal { public class AmtBlitCopyBufferToImageRegionRecord { public nuint BufferImageAllocationSize { get; internal set; } public nuint BaseArrayLayer { get; internal set; } public uint ImageLayerCount { get; internal set; } public MTLOrigin ImageOffset { get; internal set; } public nuint ImageMipLevel { get; internal set; } public MTLSize ImageSize { get; internal set; } public nuint BufferBytesPerRow { get; internal set; } public nuint BufferOffset { get; internal set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RunScript : MonoBehaviour { public void Run (Rigidbody2D rigidBody, float Speed) { print("Run!!!"); rigidBody.velocity = new Vector2(Speed, rigidBody.velocity.y); } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using NetworthDomain.Enums; namespace NetworthInfrastructure.Persistence.Configuration { public class AccountTypesConfiguration : IEntityTypeConfiguration<AccountType> { public void Configure(EntityTypeBuilder<AccountType> builder) { builder.ToTable("AccountTypes"); builder.HasKey(e => e.Value); builder.Property(t => t.Value) .IsRequired(); builder.Property(t => t.Name) .HasMaxLength(200) .IsRequired(); } public static void SeedData(ModelBuilder builder) { builder.Entity<AccountType>().HasData(AccountType.Rrsp); builder.Entity<AccountType>().HasData(AccountType.Tfsa); builder.Entity<AccountType>().HasData(AccountType.Lira); builder.Entity<AccountType>().HasData(AccountType.Taxable); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FxCopAnalyzers.Design; namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design { /// <summary> /// Implements CA1027 and CA2217 /// /// 1) CA1027: Mark enums with FlagsAttribute /// /// Cause: /// The values of a public enumeration are powers of two or are combinations of other values that are defined in the enumeration, /// and the System.FlagsAttribute attribute is not present. /// To reduce false positives, this rule does not report a violation for enumerations that have contiguous values. /// /// 2) CA2217: Do not mark enums with FlagsAttribute /// /// Cause: /// An externally visible enumeration is marked with FlagsAttribute and it has one or more values that are not powers of two or /// a combination of the other defined values on the enumeration. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class CSharpEnumWithFlagsDiagnosticAnalyzer : EnumWithFlagsDiagnosticAnalyzer { protected override Location GetDiagnosticLocation(SyntaxNode type) { return ((EnumDeclarationSyntax)type).Identifier.GetLocation(); } } }
//<Snippet5> // Example of the decimal.ToSingle and decimal.ToDouble methods. using System; class DecimalToSgl_DblDemo { static string formatter = "{0,30}{1,17}{2,23}"; // Convert the decimal argument; no exceptions are thrown. public static void DecimalToSgl_Dbl( decimal argument ) { object SingleValue; object DoubleValue; // Convert the argument to a float value. SingleValue = decimal.ToSingle( argument ); // Convert the argument to a double value. DoubleValue = decimal.ToDouble( argument ); Console.WriteLine( formatter, argument, SingleValue, DoubleValue ); } public static void Main( ) { Console.WriteLine( "This example of the \n" + " decimal.ToSingle( decimal ) and \n" + " decimal.ToDouble( decimal ) \nmethods " + "generates the following output. It \ndisplays " + "several converted decimal values.\n" ); Console.WriteLine( formatter, "decimal argument", "float", "double" ); Console.WriteLine( formatter, "----------------", "-----", "------" ); // Convert decimal values and display the results. DecimalToSgl_Dbl( 0.0000000000000000000000000001M ); DecimalToSgl_Dbl( 0.0000000000123456789123456789M ); DecimalToSgl_Dbl( 123M ); DecimalToSgl_Dbl( new decimal( 123000000, 0, 0, false, 6 ) ); DecimalToSgl_Dbl( 123456789.123456789M ); DecimalToSgl_Dbl( 123456789123456789123456789M ); DecimalToSgl_Dbl( decimal.MinValue ); DecimalToSgl_Dbl( decimal.MaxValue ); } } /* This example of the decimal.ToSingle( decimal ) and decimal.ToDouble( decimal ) methods generates the following output. It displays several converted decimal values. decimal argument float double ---------------- ----- ------ 0.0000000000000000000000000001 1E-28 1E-28 0.0000000000123456789123456789 1.234568E-11 1.23456789123457E-11 123 123 123 123.000000 123 123 123456789.123456789 1.234568E+08 123456789.123457 123456789123456789123456789 1.234568E+26 1.23456789123457E+26 -79228162514264337593543950335 -7.922816E+28 -7.92281625142643E+28 79228162514264337593543950335 7.922816E+28 7.92281625142643E+28 */ //</Snippet5>
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace GaitoBotEditor { public class EULA : Form { private bool _bestaetigt; private bool _darfSchliessen; private IContainer components = null; private WebBrowser webBrowserEULA; private Button buttonDrucken; private Button buttonAkzeptieren; private Button buttonAblehnen; public bool DarfSchliessen { set { this._darfSchliessen = value; } } public bool Bestaetigt { get { return this._bestaetigt; } } public EULA() { this.InitializeComponent(); } private void EULA_Load(object sender, EventArgs e) { this.webBrowserEULA.DocumentText = ResReader.Reader.GetString("EULA"); this.webBrowserEULA.AllowNavigation = false; this.webBrowserEULA.IsWebBrowserContextMenuEnabled = false; base.FormClosing += this.EULA_FormClosing; } private void buttonAblehnen_Click(object sender, EventArgs e) { base.Hide(); } private void buttonAkzeptieren_Click(object sender, EventArgs e) { this._bestaetigt = true; base.Hide(); } private void buttonDrucken_Click(object sender, EventArgs e) { this.webBrowserEULA.Print(); } private void EULA_FormClosing(object sender, FormClosingEventArgs e) { if (!this._darfSchliessen) { base.Hide(); e.Cancel = true; } } protected override void Dispose(bool disposing) { if (disposing && this.components != null) { this.components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { ComponentResourceManager componentResourceManager = new ComponentResourceManager(typeof(EULA)); this.webBrowserEULA = new WebBrowser(); this.buttonDrucken = new Button(); this.buttonAkzeptieren = new Button(); this.buttonAblehnen = new Button(); base.SuspendLayout(); componentResourceManager.ApplyResources(this.webBrowserEULA, "webBrowserEULA"); this.webBrowserEULA.MinimumSize = new Size(20, 20); this.webBrowserEULA.Name = "webBrowserEULA"; componentResourceManager.ApplyResources(this.buttonDrucken, "buttonDrucken"); this.buttonDrucken.Name = "buttonDrucken"; this.buttonDrucken.UseVisualStyleBackColor = true; this.buttonDrucken.Click += this.buttonDrucken_Click; componentResourceManager.ApplyResources(this.buttonAkzeptieren, "buttonAkzeptieren"); this.buttonAkzeptieren.Name = "buttonAkzeptieren"; this.buttonAkzeptieren.UseVisualStyleBackColor = true; this.buttonAkzeptieren.Click += this.buttonAkzeptieren_Click; componentResourceManager.ApplyResources(this.buttonAblehnen, "buttonAblehnen"); this.buttonAblehnen.DialogResult = DialogResult.Cancel; this.buttonAblehnen.Name = "buttonAblehnen"; this.buttonAblehnen.UseVisualStyleBackColor = true; this.buttonAblehnen.Click += this.buttonAblehnen_Click; base.AcceptButton = this.buttonAblehnen; componentResourceManager.ApplyResources(this, "$this"); base.AutoScaleMode = AutoScaleMode.Font; base.CancelButton = this.buttonAblehnen; base.Controls.Add(this.buttonAblehnen); base.Controls.Add(this.buttonAkzeptieren); base.Controls.Add(this.buttonDrucken); base.Controls.Add(this.webBrowserEULA); base.Name = "EULA"; base.Load += this.EULA_Load; base.ResumeLayout(false); } } }
namespace SecondMonitor.F12019Connector.Datamodel { using System; using System.Runtime.InteropServices; [Serializable] [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct PacketMotionData { public PacketHeader MHeader; // Header [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 20)] public CarMotionData[] MCarMotionData; // Data for all cars on track // Extra player car ONLY data [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public float[] MSuspensionPosition; // Note: All wheel arrays have the following order: [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public float[] MSuspensionVelocity; // RL, RR, FL, FR [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public float[] MSuspensionAcceleration; // RL, RR, FL, FR [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public float[] MWheelSpeed; // Speed of each wheel [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public float[] MWheelSlip; // Slip ratio for each wheel public float MLocalVelocityX; // Velocity in local space public float MLocalVelocityY; // Velocity in local space public float MLocalVelocityZ; // Velocity in local space public float MAngularVelocityX; // Angular velocity x-component public float MAngularVelocityY; // Angular velocity y-component public float MAngularVelocityZ; // Angular velocity z-component public float MAngularAccelerationX; // Angular velocity x-component public float MAngularAccelerationY; // Angular velocity y-component public float MAngularAccelerationZ; // Angular velocity z-component public float MFrontWheelsAngle; // Current front wheels angle in radians }; }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using System; using UnityEngine.Events; public class StatuesController : MonoBehaviour { [SerializeField] private UnityEvent GimmickClearEvent = new UnityEvent(); [SerializeField] private int[] answer; private List<GameObject> StatueList; private List<GameObject> FloatingTextList; [SerializeField] private List<int> playerAnswer; [SerializeField] private bool DebugLog = true; // 像が点灯したら、像側から呼ばれる public void StatueIgnited(int No) { playerAnswer.Add(No); } private void Awake() { StatueList = new List<GameObject>(); FloatingTextList = new List<GameObject>(); playerAnswer = new List<int>(); } void Start() { // 像の取得 this.GetStatues(); // 問題の作成 this.CreateQuestion(); // テキストの取得 this.GetFloatingText(); } private void FixedUpdate() { if(answer.Length == playerAnswer.Count) { if (answer.SequenceEqual(playerAnswer)) { GimmickClearEvent.Invoke(); playerAnswer.Clear(); // クリアフラグの代わり if (DebugLog) { Debug.Log("GimmickClear"); } } else { playerAnswer.Clear(); foreach(var obj in StatueList) { obj.transform.GetComponent<Statue>().FireExtinguishing(); } if (DebugLog) { Debug.Log("GimmickMistake"); } } Debug.Log(playerAnswer); } } private void GetStatues() { var count = 0; while (true) { GameObject child; try { child = transform.GetChild(0).GetChild(count++).gameObject; } catch { break; } var statue = child.transform.GetComponent<Statue>(); if (statue) { statue.No = count - 1; StatueList.Add(child); } } } private void GetFloatingText() { var count = 0; while (true) { GameObject child; try { child = transform.GetChild(1).GetChild(count++).gameObject; } catch { break; } var floatingText = child.transform.GetComponent<FloatingText>(); if (floatingText) { floatingText.SetText((answer[count-1] + 1).ToString()); FloatingTextList.Add(child); } } } private void CreateQuestion() { answer = new int[StatueList.Count]; answer = Enumerable.Range(0, StatueList.Count).ToArray(); answer = answer.OrderBy(i => Guid.NewGuid()).ToArray(); } }
// Copyright (c) SimpleIdServer. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using Microsoft.Extensions.DependencyInjection; using SimpleIdServer.OAuth; using SimpleIdServer.Uma.Domains; using SimpleIdServer.Uma.Persistence; using SimpleIdServer.Uma.Persistence.InMemory; using System.Collections.Generic; namespace SimpleIdServer.Uma { public class SimpleIdServerUmaBuilder : SimpleIdServerOAuthBuilder { private readonly IServiceCollection _serviceCollection; public SimpleIdServerUmaBuilder(IServiceCollection serviceCollection) : base(serviceCollection) { _serviceCollection = serviceCollection; } public IServiceCollection ServiceCollection { get => _serviceCollection; } public SimpleIdServerUmaBuilder AddUmaResources(List<UMAResource> umaResources) { _serviceCollection.AddSingleton<IUMAResourceRepository>(new DefaultUMAResourceRepository(umaResources)); return this; } public SimpleIdServerUmaBuilder AddUMARequests(List<UMAPendingRequest> umaPendingRequests) { _serviceCollection.AddSingleton<IUMAPendingRequestRepository>(new DefaultUMAPendingRequestRepository(umaPendingRequests)); return this; } } }
using System.Collections.Generic; using System.Web.Http; using TvTube.Search.Models; using TvTube.Search.Repositories; using TvTube.Search.Services; namespace TvTube.Search.Controllers { public class TvTubeSearchController : ApiController { [HttpGet] [HttpHead] public string Ping() { return "Pong"; } [HttpGet] public IEnumerable<TvChannel> Search(string searchTerm) { return TvTubeLuceneSearchService.Search(searchTerm, ""); } [HttpGet] public IEnumerable<TvChannel> GetAllIndexes() { return TvTubeLuceneSearchService.GetAllIndexRecords(); } [HttpGet] public IHttpActionResult CreateIndex() { TvTubeLuceneSearchService.AddUpdateLuceneIndex(new TvChannelsRepository().GetAll()); return Ok(TvTubeLuceneSearchService.LuceneDir); } [HttpGet] public IHttpActionResult ClearIndex() { TvTubeLuceneSearchService.ClearLuceneIndex(); return Ok(TvTubeLuceneSearchService.LuceneDir); } [HttpGet] public IHttpActionResult RemoveIndex(int id) { TvTubeLuceneSearchService.ClearLuceneIndexRecord(id); return Ok(TvTubeLuceneSearchService.LuceneDir); } } }
using UnityEngine; using UnityEngine.UI; using Debug = UnityEngine.Debug; [RequireComponent(typeof(Slider))] public class StatSliderDisplay : MonoBehaviour { private Slider m_slider; private Text m_statText; private bool m_hasText; [SerializeField] private string statName = "Stat"; [SerializeField] private StatReference stat; [SerializeField] private CodedGameEventListener statUpdateGameEventListener; [SerializeField] private Gradient gradient; [SerializeField] private Image fill; private bool m_hasFillImage, m_hasGradient; private void Awake() { m_slider = GetComponent<Slider>(); if (stat == null || m_slider == null) { gameObject.SetActive(false); } m_statText = GetComponentInChildren<Text>(); m_hasText = m_statText != null; m_hasFillImage = fill != null; m_hasGradient = fill != null; } private void Start() { UpdateDisplay(); } private void OnDisable() { if (statUpdateGameEventListener != null) statUpdateGameEventListener.OnDisable(); } private void OnEnable() { if (statUpdateGameEventListener != null) statUpdateGameEventListener.OnEnable(UpdateDisplay); } private void UpdateDisplay() { Debug.Assert(m_slider != null, nameof(m_slider) + " != null"); Debug.Assert(stat != null, nameof(stat) + " != null"); m_slider.maxValue = stat.Max; m_slider.value = stat.Value; if (m_hasFillImage && m_hasGradient) { Debug.Assert(fill != null, nameof(fill) + " != null"); Debug.Assert(gradient != null, nameof(gradient) + " != null"); fill.color = gradient.Evaluate(m_slider.normalizedValue); } if (!m_hasText) return; Debug.Assert(m_statText != null, nameof(m_statText) + " != null"); m_statText.text = statName + ": " + stat; } }
using System.Threading.Tasks; using HReader.Core.Storage; using Nito.AsyncEx; namespace HReader.Utility { internal class MetadataRepositoryFactory { public MetadataRepositoryFactory(MetadataRepository repository) { data = new AsyncLazy<IMetadataRepository>(async () => { await repository.InitializeAsync(); return repository; }); } private readonly AsyncLazy<IMetadataRepository> data; public async Task<IMetadataRepository> GetInstance() { return await data.Task; } } }
using CDL.Tests.Configuration; using Common; using EdgeRegistry; using Microsoft.Extensions.Options; using System.Collections.Generic; using System.Threading.Tasks; using static EdgeRegistry.EdgeRegistry; namespace CDL.Tests.Services { public class EdgeRegistryService { private EdgeRegistryClient _client; private ConfigurationOptions _options; public EdgeRegistryService(IOptions<ConfigurationOptions> options, EdgeRegistryClient client) { _options = options.Value; _client = client; } public Task<Empty> AddEdges(IList<Edge> edgeItems) { var relation = new ObjectRelations(); foreach (var item in edgeItems) { relation.Relations.Add(item); } var response = _client.AddEdges(relation); return Task.FromResult(response); } public async Task<Empty> AddEdgesAsync() { var response = await _client.AddEdgesAsync(new ObjectRelations()); return Task.FromResult(response).Result; } public Task<RelationId> AddRelation(string childSchemaId, string parentSchemaId) { var schemaRelation = new AddSchemaRelation() { ParentSchemaId = parentSchemaId, ChildSchemaId = childSchemaId, }; var response = _client.AddRelation(schemaRelation); return Task.FromResult(response); } public async Task<RelationId> AddRelationAsync(string childSchemaId, string parentSchemaId) { var schemaRelation = new AddSchemaRelation() { ChildSchemaId = childSchemaId, ParentSchemaId = parentSchemaId }; var response = await _client.AddRelationAsync(schemaRelation); return Task.FromResult(response).Result; } public Task<Edge> GetEdge(string parentObjectId, string relationId) { var relationIdQuery = new RelationIdQuery() { ParentObjectId = parentObjectId, RelationId = relationId }; var response = _client.GetEdge(relationIdQuery); return Task.FromResult(response); } public async Task<Edge> GetEdgeAsync(string parentObjectId, string relationId) { var relationIdQuery = new RelationIdQuery() { ParentObjectId = parentObjectId, RelationId = relationId }; var response = await _client.GetEdgeAsync(relationIdQuery); return Task.FromResult(response).Result; } public Task<ObjectRelations> GetEdges(string objectId) { var objectIdQuery = new ObjectIdQuery() { ObjectId = objectId }; var response = _client.GetEdges(objectIdQuery); return Task.FromResult(response); } public async Task<ObjectRelations> GetEdgesAsync(string objectId) { var objectIdQuery = new ObjectIdQuery() { ObjectId = objectId }; var response = await _client.GetEdgesAsync(objectIdQuery); return Task.FromResult(response).Result; } public Task<RelationList> GetRelation(IList<string> relationIds) { var relationQuery = new RelationQuery(){}; foreach (var item in relationIds) { relationQuery.RelationId.Add(item); } var response = _client.GetRelation(relationQuery); return Task.FromResult(response); } public async Task<RelationList> GetRelationAsync(IList<string> relationIds) { var relationQuery = new RelationQuery(){}; foreach (var item in relationIds) { relationQuery.RelationId.Add(item); } var response = await _client.GetRelationAsync(relationQuery); return Task.FromResult(response).Result; } public Task<RelationList> GetSchemaRelations(string schemaIdentity) { var schemaId = new SchemaId() { SchemaId_ = schemaIdentity }; var response = _client.GetSchemaRelations(schemaId); return Task.FromResult(response); } public async Task<RelationList> GetSchemaRelationsAsync(string schemaIdentity) { var schemaId = new SchemaId() { SchemaId_ = schemaIdentity }; var response = await _client.GetSchemaRelationsAsync(schemaId); return Task.FromResult(response).Result; } public Task<SchemaRelation> GetSchemaByRelation(string relationId) { var relationIdObject = new RelationId() { RelationId_ = relationId }; var response = _client.GetSchemaByRelation(relationIdObject); return Task.FromResult(response); } public Task<Empty> Heartbeat() { var response = _client.Heartbeat(new Empty()); return Task.FromResult(response); } public async Task<Empty> HeartbeatAsync() { var response = await _client.HeartbeatAsync(new Empty()); return Task.FromResult(response).Result; } public Task<RelationTreeResponse> ResolveTree(IList<Relation> relations, Filter filter = null) { var treeQuery = new TreeQuery() {}; foreach (var item in relations) { treeQuery.Relations.Add(item); } if (filter!=null){ treeQuery.Filters=filter; } var response = _client.ResolveTree(treeQuery); return Task.FromResult(response); } public async Task<RelationTreeResponse> ResolveTreeAsync(IList<Relation> relations) { var treeQuery = new TreeQuery() {}; foreach (var item in relations) { treeQuery.Relations.Add(item); } var response = await _client.ResolveTreeAsync(treeQuery); return Task.FromResult(response).Result; } public Task<Empty> ValidateRelation(string relationId) { var validateRelationQuery = new ValidateRelationQuery() { RelationId = relationId }; var response = _client.ValidateRelation(validateRelationQuery); return Task.FromResult(response); } public async Task<Empty> ValidateRelationAsync(string relationId) { var validateRelationQuery = new ValidateRelationQuery() { RelationId = relationId }; var response = await _client.ValidateRelationAsync(validateRelationQuery); return Task.FromResult(response).Result; } } }
using System; namespace ReMi.BusinessEntities.ReleasePlan { public class ReleaseTaskAttachmentView { public Guid ExternalId { get; set; } public string Name { get; set; } public string ServerName { get; set; } public string Type { get; set; } public int Size { get; set; } } }
using Orleans; using System; using WPFDemoCore.Enums; using WPFDemoCore.Message; namespace WPFDemoCore.Interfaces { /// <summary> /// Use this interface to FetchService, don't dependency Orleans.IGrainFacotry /// </summary> public interface IServiceManager { T FetchFunction<T>(Guid key, string typeName) where T : IGrainWithGuidKey; T FetchService<T>() where T : IService; T FetchService<T>(long key) where T : IService; T FetchService<T>(ServiceKeyEnum key) where T : IService; T GetGrainObserver<T>(T observer) where T : IGrainObserver; } }
using System; using System.Collections.Generic; namespace Dx29.Data { public partial class Gene { public Gene() { Diseases = new List<Association>(); Symptoms = new List<Association>(); } public Gene(string id, string name) : this() { Id = id; Name = name; } public string Id { get; set; } public string Name { get; set; } public List<Association> Diseases { get; set; } public List<Association> Symptoms { get; set; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.Dnx.Testing.Framework { internal static class TestLogger { public static void TraceError(string message, params object[] args) { if (IsEnabled) { Console.WriteLine("Test Error: " + message, args); } } public static void TraceInformation(string message, params object[] args) { if (IsEnabled) { Console.WriteLine("Test Information: " + message, args); } } public static void TraceWarning(string message, params object[] args) { if (IsEnabled) { Console.WriteLine("Test Warning: " + message, args); } } public static bool IsEnabled { get { return Environment.GetEnvironmentVariable(TestEnvironmentNames.Trace) == "1"; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using Caterative.Brick.Balls; namespace Caterative.Brick.TheShieldBoss { public class ShieldMinionC : MonoBehaviour { Shield shield; ShieldBossFigure figure; public int health = 2; public float happyRotationPerSecond = 25; void Awake() { shield = GetComponentInChildren<Shield>(); figure = GetComponentInChildren<ShieldBossFigure>(); } void Update() { shield.transform.Rotate(0, 0, happyRotationPerSecond * Time.deltaTime); } void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.CompareTag("Ball")) { health--; figure.Hit(); if (health <= 0) { Deactivate(); } } } private void Deactivate() { transform.position = new Vector2(-10, 100); gameObject.SetActive(false); } } }
namespace Osklib { internal sealed class UnsupportedOsOnScreenKeyboardController : OnScreenKeyboardController { public override bool Close() { return false; } public override bool IsOpened() { return false; } public override void Show() { } } }
namespace XIVLauncher.Common { public enum ClientLanguage { Japanese, English, German, French } public static class ClientLanguageExtensions { public static string GetLangCode(this ClientLanguage language) { switch (language) { case ClientLanguage.Japanese: return "ja"; case ClientLanguage.English when Util.IsRegionNorthAmerica(): return "en-us"; case ClientLanguage.English: return "en-gb"; case ClientLanguage.German: return "de"; case ClientLanguage.French: return "fr"; default: return "en-gb"; } } } }
using UnityEditor; using UnityEngine; using GameplayIngredients.Editor; static class SamplePlayFromHere { [InitializeOnLoadMethod] static void SetupPlayFromHere() { PlayFromHere.OnPlayFromHere += PlayFromHere_OnPlayFromHere; } private static void PlayFromHere_OnPlayFromHere(Vector3 position, Vector3 forward) { // Get the FirstPersonCharacter prefab in Resources and instantiate it var prefab = (GameObject)Resources.Load("FirstPersonCharacter"); var player = GameObject.Instantiate(prefab); player.name = "(Play from Here) " + prefab.name; // position the character correctly, so the current POV matches the player's height var controller = player.GetComponent<GameplayIngredients.Controllers.FirstPersonController>(); player.transform.position = new Vector3(position.x, position.y - controller.PlayerHeight, position.z); // orient the player correctly var orient = forward; orient.Scale(new Vector3(1, 0, 1)); player.transform.forward = orient; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIEnginePlayerButton : MonoBehaviour { bool active; public bool IsActivated { get => active; set => Activate(value); } [SerializeField] int player; //white = 0, black = 1 [SerializeField] UIEnginePlayerButton otherButton; Image thisImage; Color[] colors; Color defaultColor; GameMngr manager; private void Start() { manager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameMngr>(); thisImage = GetComponent<Image>(); defaultColor = thisImage.color; colors = new Color[] { manager.boardCreation.whiteColor, manager.boardCreation.blackColor }; } public void ButtonPressed() { bool otherButtonActive = otherButton.IsActivated; EngineState ourState = (player == ChessBoard.white) ? EngineState.White : EngineState.Black; EngineState theirState = (player == ChessBoard.white) ? EngineState.Black : EngineState.White; IsActivated = !IsActivated; if (otherButtonActive && IsActivated) { manager.engineState = EngineState.Both; } else if (IsActivated) { manager.engineState = ourState; } else if (otherButtonActive) { manager.engineState = theirState; } else { manager.engineState = EngineState.Off; } } void Activate(bool value) { if (value) { active = value; thisImage.color = colors[player]; } else { active = value; thisImage.color = defaultColor; } } }
/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ using FairyGUI; namespace UI.Story.QuizGame { public class QuizGameBinder { [UnityEngine.RuntimeInitializeOnLoadMethod(UnityEngine.RuntimeInitializeLoadType.BeforeSceneLoad)] public static void BindAll() { UIObjectFactory.SetPackageItemExtension(View_tips_star.URL, typeof (View_tips_star)); UIObjectFactory.SetPackageItemExtension(View_tips_share.URL, typeof (View_tips_share)); UIObjectFactory.SetPackageItemExtension(View_sharing.URL, typeof (View_sharing)); UIObjectFactory.SetPackageItemExtension(View_QuizGame.URL, typeof (View_QuizGame)); UIObjectFactory.SetPackageItemExtension(View_Label1.URL, typeof (View_Label1)); UIObjectFactory.SetPackageItemExtension(View_tips.URL, typeof (View_tips)); UIObjectFactory.SetPackageItemExtension(View_freestar.URL, typeof (View_freestar)); UIObjectFactory.SetPackageItemExtension(View_loadingstar.URL, typeof (View_loadingstar)); UIObjectFactory.SetPackageItemExtension(View_play.URL, typeof (View_play)); } } }
using AutoMapper; using project.application.Common.Interfaces; using project.domain.Notifications; namespace project.application.Common.Models { /// <summary> /// Classe abstrata para padronização dos resultados dos Commands Response /// </summary> public abstract class CommandHandler : IHttpCommandResponse { protected readonly IMapper _mapper; protected readonly NotificationContext _notificationContext; protected CommandHandler(IMapper mapper, NotificationContext notificationContext) { _mapper = mapper; _notificationContext = notificationContext; } public CommandResponse BadRequest(object response, string message = null) { var commandResponse = new CommandResponse(400, message, response, false); return commandResponse; } public CommandResponse Created(object response, string message = null) { var commandResponse = new CommandResponse(201, message, response); commandResponse.Success = true; return commandResponse; } public CommandResponse InternalError(object response, string message = null) { var commandResponse = new CommandResponse(500, message, response, false); return commandResponse; } public CommandResponse NotFound(object response, string message = null) { var commandResponse = new CommandResponse(404, message, response, false); return commandResponse; } public CommandResponse Ok(object response, string message = null) { var commandResponse = new CommandResponse(200, message, response); commandResponse.Success = true; return commandResponse; } } }
using webModels = VirtoCommerce.Content.Web.Models; using coreModels = VirtoCommerce.Content.Data.Models; using Omu.ValueInjecter; namespace VirtoCommerce.Content.Web.Converters { public static class MenuLinkConverter { public static coreModels.MenuLink ToCoreModel(this webModels.MenuLink link) { var retVal = new coreModels.MenuLink(); retVal.InjectFrom(link); return retVal; } public static webModels.MenuLink ToWebModel(this coreModels.MenuLink link) { var retVal = new webModels.MenuLink(); retVal.InjectFrom(link); return retVal; } } }
namespace RollTheCredits.Common { public enum PlatformTypes { Large, Small, YouWin, Top, Middle } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Senparc.Weixin.QY.Entities { public class MpNewsArticle { public string Title { get; set; } public string ThumbMediaId { get; set; } public string Author { get; set; } public string ContentSourceUrl { get; set; } public string Content { get; set; } public string Digest { get; set; } public string ShowCoverPic { get; set; } } }
using System; namespace AudioSharp { /// <summary> /// A device for streaming audio to. Creates <see cref="AudioSharp.IStreamingAudio"/> instances. /// </summary> public interface IAudioDevice : IDisposable { /// <summary> /// Creates an IStreamingAudio to stream audio to /// </summary> /// <returns>A usable IStreamingAudio instance.</returns> /// <param name="format">The format of the PCM data</param> /// <param name="sampleRate">Sample rate in kHz (e.g. 44100)</param> IStreamingAudio CreateStreamer(SoundFormat format, int sampleRate); } }
namespace System.Diagnostics.Contracts { [Bridge.Enum(Bridge.Emit.Name)] [Bridge.External] public enum ContractFailureKind { Precondition, Postcondition, PostconditionOnException, Invariant, Assert, Assume, } }
#pragma warning disable CS1591 // Fehledes XML-Kommentar für öffentlich sichtbaren Typ oder Element namespace CenterDevice.Model.Groups { public enum GroupsFilter { AllVisibleGroupsForCurrentUser = 0, MembershipsOfCurrentUser = 1 } } #pragma warning restore CS1591 // Fehledes XML-Kommentar für öffentlich sichtbaren Typ oder Element
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectExpire : MonoBehaviour { public float secondsBeforeRemoval = 5; void Start() { // Removes this object from the game Destroy(gameObject, secondsBeforeRemoval); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text.Json; using System.Text.Json.Serialization; using NumSharp; namespace Microsoft.Quantum.Experimental { public class InstrumentConverter : JsonConverter<Instrument> { public override Instrument Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // We use the technique at // https://stackoverflow.com/questions/58074304/is-polymorphic-deserialization-possible-in-system-text-json/59744873#59744873 // to implement polymorphic deserialization, based on the property name. reader.Require(JsonTokenType.StartObject, read: false); reader.Require(JsonTokenType.PropertyName); var variant = reader.GetString(); Instrument result = variant switch { "Effects" => new EffectsInstrument { Effects = JsonSerializer.Deserialize<List<Process>>(ref reader) }, "ZMeasurement" => JsonSerializer.Deserialize<ZMeasurementInstrument>(ref reader), _ => throw new JsonException($"Enum variant {variant} not yet supported.") }; reader.Require(JsonTokenType.EndObject); return result; } public override void Write(Utf8JsonWriter writer, Instrument value, JsonSerializerOptions options) { switch (value) { case EffectsInstrument effectsInstrument: writer.WriteStartObject(); writer.WritePropertyName("Effects"); JsonSerializer.Serialize(writer, effectsInstrument.Effects); writer.WriteEndObject(); break; case ZMeasurementInstrument zInstrument: writer.WriteStartObject(); writer.WritePropertyName("ZMeasurement"); JsonSerializer.Serialize(writer, zInstrument); writer.WriteEndObject(); break; default: throw new JsonException($"Enum variant {value.GetType()} not yet supported."); } } } [JsonConverter(typeof(InstrumentConverter))] public abstract class Instrument { } public class EffectsInstrument : Instrument { [JsonPropertyName("effects")] public IList<Process> Effects { get; set; } = new List<Process>(); public override string ToString() => $"Instrument {{ Effects = {String.Join(", ", Effects.Select(effect => effect.ToString()))} }}"; } public class ZMeasurementInstrument : Instrument { [JsonPropertyName("pr_readout_error")] public double PrReadoutError { get; set; } = 0.0; public override string ToString() => $"Instrument {{ Z measurement with readout error = {PrReadoutError} }}"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NRoles.Engine.Test.Support { public interface IEquality { bool Equals(IEquality other); bool Differs(IEquality other); } [RoleTest( OtherRoles = new Type[] { typeof(Magnitude) }, CompositionType = typeof(Circle))] public abstract class Equality : IEquality, Role { public abstract bool Equals(IEquality other); public bool Differs(IEquality other) { return !Equals(other); } } public interface IMagnitude : IEquality { bool Smaller(IMagnitude other); bool Greater(IMagnitude other); bool Between(IMagnitude min, IMagnitude max); } public abstract class Magnitude : IMagnitude, Role { public abstract bool Smaller(IMagnitude other); public abstract bool Equals(IEquality other); public abstract bool Differs(IEquality other); public bool Between(IMagnitude min, IMagnitude max) { return min.Smaller(this) && this.Smaller(max); } public bool Greater(IMagnitude other) { return !Smaller(other) && this.Differs(other); } } public class Circle : Does<Equality>, Does<Magnitude> { public int Center { get; set; } public int Radius { get; set; } public double Area { get { return Math.PI * (Radius * Radius); } } public bool Equals(IEquality other) { var otherCircle = other as Circle; if (otherCircle == null) return false; return otherCircle.Center == Center && otherCircle.Radius == Radius; } public bool Smaller(IMagnitude other) { var otherCircle = other as Circle; if (otherCircle == null) return false; return Radius < otherCircle.Radius; } } }
 using System; using System.Text; using System.Text.RegularExpressions; using System.Threading; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; namespace WebAddressbookTests { [TestFixture] public class AAAAAAAAAA {/* [Test] public void Forr() { string[] s = new string[] {"I", "wanna", "rock", "!!!!!"}; for (int i = 0; i < s.Length; i++) { Console.Out.Write(s[i] + "\n"); } } [Test] public void Forreach() { string[] s = new string[] { "I", "wanna", "rock", "!!!!!" }; foreach (string element in s) { Console.Out.Write(element + "\n"); } } [Test] public void Whilee() { IWebDriver driver = null; int attempt = 0; while (driver.FindElement(By.Id("test")).Count) ==0 && attempt < 60) //счетчик { System.Threading.Thread.Sleep(1000); //ждем 1000мс и проверяем снова attempt++; } } [Test] public void Do_while() { IWebDriver driver = null; int attempt = 0; do //тело цикла исполнится сначала в любом случае { System.Threading.Thread.Sleep(1000); //ждем 1000мс и проверяем снова attempt++; } while (driver.FindElement(By.Id("test")).Count) == 0 && attempt < 60); //счетчик } */ } }
using UnityEngine; using System.Collections; #if UNITY_EDITOR using UnityEditor; #endif [ExecuteInEditMode] public abstract class OnlineTexture : MonoBehaviour { public bool textureLoaded = false; protected WWW request_; public void Start() { // When in edit mode, start downloading a texture preview. if (!Application.isPlaying) { RequestTexturePreview (); } } public void RequestTexture( string nodeID ) { textureLoaded = false; string url = GenerateRequestURL (nodeID); request_ = new WWW (url); } public void RequestTexturePreview () { RequestTexture ("0"); } #if UNITY_EDITOR // Make this update with editor. void OnEnable(){ EditorApplication.update += Update; } void OnDisable(){ EditorApplication.update -= Update; } #endif public void Update() { if (textureLoaded == false && request_ != null && request_.isDone) { string errorMessage = ""; var tempMaterial = new Material(GetComponent<MeshRenderer> ().sharedMaterial); if (ValidateDownloadedTexture (out errorMessage)) { textureLoaded = true; tempMaterial.mainTexture = request_.texture; } else { request_ = null; tempMaterial.mainTexture = Texture2D.whiteTexture; } tempMaterial.mainTexture.wrapMode = TextureWrapMode.Clamp; GetComponent<MeshRenderer> ().material = tempMaterial; } } public bool IsDownloading() { return textureLoaded == false && request_ != null && !request_.isDone; } protected abstract string GenerateRequestURL (string nodeID); public void CopyTo(OnlineTexture copy) { copy.request_ = request_; // This forces inherited component to reload the texture. copy.textureLoaded = false; InnerCopyTo (copy); } protected abstract void InnerCopyTo (OnlineTexture copy); public virtual bool ValidateDownloadedTexture( out string errorMessage ) { if (request_.error != null) { errorMessage = request_.error; return false; } else { errorMessage = ""; return true; } } }
namespace Tomataboard.Services.Photos { public class Photo { public string Service { get; set; } public string Name { get; set; } public string AuthorName { get; set; } public string PhotoPage { get; set; } public string Url { get; set; } } }
namespace IPSI.Services.Models.ViewModels.Company { using IPSI.Data.Models; using IPSI.Services.Mapping; public class CompanyViewModel : IMapFrom<Company> { public int Id { get; set; } public string Name { get; set; } public string Logo { get; set; } public string Broker { get; set; } } }
using System; using System.Windows; using NUnit.Framework; using StoryTeller.Domain; using StoryTeller.Testing.UserInterface.Exploring; using StoryTeller.UserInterface; using StoryTeller.UserInterface.Commands; using StoryTeller.UserInterface.Dialogs; using StoryTeller.UserInterface.Eventing; using StoryTeller.UserInterface.Exploring; using StoryTeller.UserInterface.Projects; using StoryTeller.UserInterface.Screens; using StructureMap; namespace StoryTeller.Testing.UserInterface.IntegrationTests { [TestFixture] public class BootstrapperTester { #region Setup/Teardown [SetUp] public void SetUp() { ProjectHistory history = DataMother.HistoryPointingToMathProject(); new ProjectPersistor().SaveHistory(history); Bootstrapper.BootstrapShell(false); shell = (Shell) ObjectFactory.GetInstance<IApplicationShell>(); ObjectFactory.Configure(x => { x.For<Window>().Use(() => { window = new Window(); window.Show(); return window; }); }); } [TearDown] public void TearDown() { if (window != null) { window.Close(); window = null; } } #endregion private Window window; private Shell shell; [Test] public void can_get_the_shell_parts() { ObjectFactory.GetInstance<IApplicationShell>().ShouldNotBeNull(); ObjectFactory.GetInstance<IScreenCollection>().ShouldNotBeNull(); } [Test] public void can_request_the_errors_screen() { DataMother.LoadMathProject(); var factory = ObjectFactory.GetInstance<IScreenFactory>(); ObjectFactory.GetInstance<GrammarErrorsSubject>().CreateScreen(factory).ShouldNotBeNull(); } [Test, Explicit] public void has_the_suite_and_test_nodes_for_the_math_project() { shell.HierarchyNode.Text.ShouldEqual("Math"); shell.HierarchyNode.ShouldNotBeNull(); new TreeNodeSpecification( @" workspacesuite:Adding test:Adding/Bad Add 1 test:Adding/Good Add 1 test:Adding/Good Add 2 workspacesuite:EmptySuite workspacesuite:Mixed suite:Mixed/SubMixed test:Mixed/SubMixed/Sub Mixed 1 test:Mixed/SubMixed/Sub Mixed 2 test:Mixed/SubMixed/SubMixedThatThrows test:Mixed/Mixed 1 workspacesuite:Multiplication test:Multiplication/Bad Multiply 1 test:Multiplication/Good Multiply 1 test:Multiplication/Good Multiply 2 test:Bad Add at Top test:Good Add at Top ") .AssertMatch(shell.HierarchyNode); } [Test] public void register_all_types_that_implement_an_IListener_interface_with_the_event_aggregator() { var listener = ObjectFactory.GetInstance<AListener>(); var aggregator = ObjectFactory.GetInstance<IEventAggregator>() as EventAggregator; aggregator.HasListener(listener).ShouldBeTrue(); } [Test] public void register_all_types_that_implement_iclosable_interface_with_the_event_aggregator() { var closeable = ObjectFactory.GetInstance<Closeable>(); var aggregator = ObjectFactory.GetInstance<IEventAggregator>() as EventAggregator; aggregator.HasListener(closeable).ShouldBeTrue(); } [Test] public void register_all_types_that_implement_the_ITestListener_interface_with_the_event_aggregator() { var stub = ObjectFactory.GetInstance<ExecutionEngineIntegratedTester.StubTestListener>(); var aggregator = ObjectFactory.GetInstance<IEventAggregator>() as EventAggregator; aggregator.HasListener(stub).ShouldBeTrue(); } [Test] public void should_have_the_test_explorer_and_fixture_explorer_registered_as_listeners() { var fixtures = ObjectFactory.GetInstance<FixtureExplorer>(); var tests = ObjectFactory.GetInstance<ITestExplorer>(); var aggregator = ObjectFactory.GetInstance<IEventAggregator>().As<EventAggregator>(); aggregator.HasListener(fixtures).ShouldBeTrue(); aggregator.HasListener(tests).ShouldBeTrue(); } [Test] public void smoke_test_the_dialog_auto_registration() { var launcher = ObjectFactory.GetInstance<IDialogLauncher>(); var command = ObjectFactory.With(new Suite("suite")).GetInstance<IAddTestCommand>(); launcher.ShouldBeOfType<DialogLauncher>().BuildDialog(command).ShouldNotBeNull(); } } public class Closeable : ICloseable { #region ICloseable Members public void AddCanCloseMessages(CloseToken token) { throw new NotImplementedException(); } public void PerformShutdown() { throw new NotImplementedException(); } #endregion } public class AListener : IListener<string> { #region IListener<string> Members public void Handle(string message) { throw new NotImplementedException(); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Base class for all interactable item that implements interface InteractableInterface /// </summary> public class BasicItem : MonoBehaviour,InteractableInterface { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public virtual bool canInteract(GameObject interactor) { return true; } public virtual void interact(GameObject interactor) { throw new System.NotImplementedException(); } }
using System; using System.Collections.Generic; using System.Text; using WFE.Models; using System.IO; using System.Reflection; namespace WFE.Lib { public class TemplateReader { private static readonly string _templateDirectory; private static readonly string _defaultTemplateDirectory; private static readonly Dictionary<string, TemplateModel> _templates; static TemplateReader() { string codeBase = Assembly.GetExecutingAssembly().CodeBase; var uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); _defaultTemplateDirectory = Path.Combine(Path.GetDirectoryName(path), "Templates"); _templateDirectory = Environment.CurrentDirectory; _templates = new Dictionary<string, TemplateModel>(); } public static TemplateModel ReadTemplate(string fileName) { string templatePath = Path.Combine(_templateDirectory, fileName); if (File.Exists(templatePath) == false) // file not in the user selected directory? { templatePath = Path.Combine(_defaultTemplateDirectory, fileName); if (File.Exists(templatePath) == false) // file not in the program directory? throw new FileNotFoundException("Template not found: " + fileName); } if (_templates.ContainsKey(fileName)) return _templates[fileName]; string content = File.ReadAllText(templatePath); var template = Serializer.Deserialize<TemplateModel>(content, Encoding.UTF8); _templates[fileName] = template; return template; } } }
using System.IO; using FileParty.Core.Interfaces; namespace FileParty.Core.Models { /// <summary> /// /// </summary> /// <typeparam name="TFilePartyModule"></typeparam> public abstract class StorageProviderConfiguration<TFilePartyModule> : IStorageProviderConfiguration where TFilePartyModule : class, IFilePartyModule, new() { public virtual char DirectorySeparationCharacter { get; } = Path.DirectorySeparatorChar; } }
#region Using Statements using System; using WaveEngine.Common.Math; using WaveEngine.Components.Gestures; using WaveEngine.Components.Graphics2D; using WaveEngine.Framework; using WaveEngine.Framework.Graphics; using WaveEngine.Framework.Physics2D; using WaveEngine.Framework.Services; #endregion namespace TiledMapProject.Entities { public class JumpButton : BaseDecorator { private Entity thumb; private Transform2D thumbTransform; private Vector2 pressedPosition; #region Properties /// <summary> /// Gets or sets a value indicating whether this instance is active. /// </summary> public bool IsActive { get { return this.entity.IsActive; } set { this.entity.IsActive = value; } } /// <summary> /// The is shooting /// </summary> public bool IsShooting; #endregion /// <summary> /// Initializes a new instance of the <see cref="JumpButton" /> class. /// </summary> /// <param name="name">The name.</param> /// <param name="area">The area.</param> public JumpButton(string name, RectangleF area) { // Touch area this.entity = new Entity(name) .AddComponent(new Transform2D() { X = area.X, Y = area.Y, Rectangle = new RectangleF(0, 0, area.Width, area.Height), }) .AddComponent(new RectangleCollider()) .AddComponent(new TouchGestures()); // Thumb this.thumb = new Entity() .AddComponent(new Transform2D() { Origin = Vector2.Center, DrawOrder = 0.1f, }) .AddComponent(new Sprite("Content/joystickThumb.wpk")) .AddComponent(new SpriteRenderer(DefaultLayers.GUI)); this.thumb.IsVisible = false; this.thumbTransform = this.thumb.FindComponent<Transform2D>(); this.entity.AddChild(this.thumb); // Touch Events var touch = this.entity.FindComponent<TouchGestures>(); touch.TouchPressed += (s, o) => { this.pressedPosition = o.GestureSample.Position; this.thumbTransform.X = this.pressedPosition.X; this.thumbTransform.Y = this.pressedPosition.Y; this.thumb.IsVisible = true; this.IsShooting = true; }; touch.TouchMoved += (s, o) => { Vector2 deltaTouch = this.pressedPosition - o.GestureSample.Position; this.thumbTransform.X = this.pressedPosition.X - deltaTouch.X; this.thumbTransform.Y = this.pressedPosition.Y - deltaTouch.Y; }; touch.TouchReleased += (s, o) => { this.thumb.IsVisible = false; this.IsShooting = false; }; } } }
using Microsoft.Azure.KeyVault.WebKey; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using SigningPortalDemo.AuthApi; using System; using System.Globalization; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.Serialization.Json; using System.Text; namespace SigningPortalDemo.Utilities { public class HttpUtil { static string KEY = Environment.GetEnvironmentVariable("APPSETTING_KEY"); static string CLIENT_ID = Environment.GetEnvironmentVariable("APPSETTING_CLIENT_ID"); static string ISS = Environment.GetEnvironmentVariable("APPSETTING_ISS"); static HttpClient httpClient = new HttpClient(); static string accessToken=null; static DateTime tokenExpire; static string clientJwt=null; private static string CreateJwt() { DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime now = DateTime.UtcNow; var claimset = new { iss = ISS, sub = CLIENT_ID, aud = "https://go.nexusgroup.com", iat = (int)now.Subtract(UnixEpoch).TotalSeconds, exp = (int)now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds }; // header var header = new { typ = "JWT", alg = JsonWebKeySignatureAlgorithm.RS256, kid = KEY }; // encoded header var headerSerialized = JsonConvert.SerializeObject(header); var headerBytes = Encoding.UTF8.GetBytes(headerSerialized); var headerEncoded = System.Convert.ToBase64String(headerBytes); // encoded claimset var claimsetSerialized = JsonConvert.SerializeObject(claimset); var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized); var claimsetEncoded = System.Convert.ToBase64String(claimsetBytes); // input var input = String.Join(".", headerEncoded, claimsetEncoded); var inputBytes = Encoding.UTF8.GetBytes(input); var signatureEncoded = KeyVaultUtil.Sign(inputBytes); // jwt return String.Join(".", headerEncoded, claimsetEncoded, signatureEncoded); } private static async System.Threading.Tasks.Task GetNewAccessTokenAsync() { HttpClient client = new HttpClient(); if (clientJwt == null) { clientJwt = CreateJwt(); } var tokenRequest = new TokenRequest() { Assertion = clientJwt }; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); String requestBody = JsonConvert.SerializeObject(tokenRequest, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); var content = new StringContent(requestBody, Encoding.UTF8, "application/json"); var response = await client.PostAsync($"{Startup.Configuration["Api:AuthApi:Url"]}", content); if (response.IsSuccessStatusCode) { string responseString = response.Content.ReadAsStringAsync().Result; var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(responseString); accessToken = tokenResponse.Access_token; tokenExpire = DateTime.UtcNow.AddSeconds(tokenResponse.Expires_in); Console.WriteLine("Get token: " + accessToken); } else { accessToken = null; Console.WriteLine("Cannot get token"); } } public static async System.Threading.Tasks.Task<HttpClient> GetAuthorizedHttpClientAsync() { if (accessToken == null || DateTime.UtcNow.AddSeconds(60).CompareTo(tokenExpire) >0 ) { // Renew Token await GetNewAccessTokenAsync(); } httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return httpClient; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ShopifySharp.Filters; using Xunit; namespace ShopifySharp.Tests { [Trait("Category", "GiftCard")] public class GiftCard_Tests : IClassFixture<GiftCard_Tests_Fixture> { public static decimal GiftCardValue = 100; private GiftCard_Tests_Fixture Fixture { get; } public GiftCard_Tests(GiftCard_Tests_Fixture fixture) { this.Fixture = fixture; } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Counts_GiftCards() { var count = await Fixture.Service.CountAsync(); Assert.True(count > 0); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Counts_GiftCards_With_A_Filter() { var enabledCount = await Fixture.Service.CountAsync(new GiftCardCountFilter { Status = "enabled" }); Assert.True(enabledCount > 0); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Lists_GiftCards() { var list = await Fixture.Service.ListAsync(); Assert.True(list.Items.Any()); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Lists_GiftCards_With_A_Filter() { var list = await Fixture.Service.ListAsync(new GiftCardListFilter() { Status = "enabled" }); Assert.True(list.Items.Any()); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Gets_GiftCards() { // Find an id var created = Fixture.Created.First(); var giftCard = await Fixture.Service.GetAsync(created.Id.Value); Assert.NotNull(giftCard); Assert.Equal(GiftCardValue, giftCard.InitialValue); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Creates_GiftCards() { var created = await Fixture.Create(GiftCardValue); Assert.NotNull(created); Assert.True(created.Id.HasValue); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Creates_GiftCards_With_Code() { var customCode = Guid.NewGuid().ToString(); var lastFour = customCode.Substring(customCode.Length - 4); var created = await Fixture.Create(GiftCardValue, customCode); Assert.NotNull(created); Assert.True(created.Id.HasValue); Assert.Equal(lastFour, created.LastCharacters); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Updates_GiftCards() { string note = "Updates_GiftCards note"; var created = await Fixture.Create(GiftCardValue); long id = created.Id.Value; created.Note = note; created.Id = null; var updated = await Fixture.Service.UpdateAsync(id, created); // Reset the id so the Fixture can properly delete this object. created.Id = id; Assert.Equal(note, updated.Note); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Disable_GiftCards() { var created = await Fixture.Create(GiftCardValue); var disabled = await Fixture.Service.DisableAsync(created.Id.Value); Assert.True(disabled.DisabledAt.HasValue); } [Fact(Skip = "Cannot run without a Shopify Plus account.")] public async Task Searches_For_GiftCards() { var customCode = Guid.NewGuid().ToString(); customCode = customCode.Substring(customCode.Length - 20); await Fixture.Create(GiftCardValue, customCode); var search = await Fixture.Service.SearchAsync(new GiftCardSearchFilter { Query = "code:" + customCode }); Assert.True(search.Items.Any()); } } public class GiftCard_Tests_Fixture : IAsyncLifetime { public GiftCardService Service => new GiftCardService(Utils.MyShopifyUrl, Utils.AccessToken); public List<GiftCard> Created { get; } = new List<GiftCard>(); public async Task InitializeAsync() { Service.SetExecutionPolicy(new SmartRetryExecutionPolicy()); // Create an giftCard. var giftCard = await Create(GiftCard_Tests.GiftCardValue); } public async Task DisposeAsync() { foreach (var obj in Created) { try { await Service.DisableAsync(obj.Id.Value); } catch (ShopifyException ex) { Console.WriteLine($"Failed to delete gift card with id {obj.Id.Value}. {ex.Message}"); } } } public async Task<GiftCard> Create(decimal value, string code = null) { var giftCardRequest = new GiftCard() { InitialValue = value }; if (!string.IsNullOrEmpty(code)) { giftCardRequest.Code = code; } if (giftCardRequest.Code != null && giftCardRequest.Code.Length > 20) { giftCardRequest.Code = giftCardRequest.Code.Substring(giftCardRequest.Code.Length - 20); } var giftCard = await Service.CreateAsync(giftCardRequest); Created.Add(giftCard); return giftCard; } } }
using Examine; using Our.Umbraco.FullTextSearch.Interfaces; using Our.Umbraco.FullTextSearch.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Http; using Umbraco.Core.Logging; using Umbraco.Core.Services; using Umbraco.Examine; using Umbraco.Web; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; namespace Our.Umbraco.FullTextSearch.Controllers { [PluginController("FullTextSearch")] public class IndexController : UmbracoAuthorizedApiController { private readonly ICacheService _cacheService; private readonly IConfig _fullTextConfig; private readonly ILogger _logger; private readonly IPublishedContentValueSetBuilder _valueSetBuilder; private readonly IExamineManager _examineManager; private readonly IContentService _contentService; private readonly IndexRebuilder _indexRebuilder; public IndexController(ICacheService cacheService, ILogger logger, IConfig fullTextConfig, IExamineManager examineManager, IndexRebuilder indexRebuilder, IPublishedContentValueSetBuilder valueSetBuilder, IContentService contentService) { _cacheService = cacheService; _fullTextConfig = fullTextConfig; _logger = logger; _valueSetBuilder = valueSetBuilder; _examineManager = examineManager; _contentService = contentService; _indexRebuilder = indexRebuilder; } [HttpPost] public bool ReindexNode(string nodeIds) { if (!_fullTextConfig.IsFullTextIndexingEnabled()) { _logger.Debug<IndexController>("FullTextIndexing is not enabled"); return false; } if (!_examineManager.TryGetIndex("ExternalIndex", out IIndex index)) { _logger.Error<IndexController>(new InvalidOperationException("No index found by name ExternalIndex")); return false; } if (nodeIds == "*") { foreach (var content in Umbraco.ContentAtRoot()) { _cacheService.AddToCache(content.Id); foreach (var descendant in content.Descendants()) { _cacheService.AddToCache(descendant.Id); } } index.CreateIndex(); _indexRebuilder.RebuildIndex("ExternalIndex"); } else { var ids = nodeIds.Split(',').Select(x => int.Parse(x)); foreach (var id in ids) { _cacheService.AddToCache(id); } index.IndexItems(_valueSetBuilder.GetValueSets(_contentService.GetByIds(ids).ToArray())); } return true; } [HttpGet] public List<CacheTask> GetCacheTasks() { return _cacheService.GetAllCacheTasks(); } [HttpPost] public bool RestartCacheTask(int taskId, int nodeId) { _cacheService.DeleteCacheTask(taskId); _cacheService.AddCacheTask(nodeId); return true; } [HttpPost] public bool DeleteCacheTask(int taskId) { _cacheService.DeleteCacheTask(taskId); return true; } } }
 using Products.Domain.Core; namespace Products.Domain.Service { public interface IJwtGenerator { string CreateToken(AppUser user); } }
using System; using Higliter2nd.Internals; using Higliter2nd.Overlay; using Overlay.NET.Common; namespace Higliter2nd { public static class Program { [STAThread] public static void Main(string[] args) { Log.Register("Console", new ConsoleLog()); Log.Debug("Start Highligter"); var controller = new OverlayController(); controller.Start(); Console.ReadLine(); } } }
using System.Collections.Generic; using FineCodeCoverage.Engine.Model; namespace FineCodeCoverage.Engine { internal interface ICoverageToolOutputManager { void SetProjectCoverageOutputFolder(List<ICoverageProject> coverageProjects); void OutputReports(string unifiedHtml, string processedReport, string unifiedXml); } }
using System; using System.Linq; using System.Threading.Tasks; using TellagoStudios.Hermes.Business.Data.Queries; using TellagoStudios.Hermes.Business.Events; using TellagoStudios.Hermes.Business.Model; namespace TellagoStudios.Hermes.RestService.Pushing { public class NewMessagePusher : IEventHandler<NewMessageEvent> { public ISubscriptionsByTopicAndTopicGroup SubscriptionsByTopicAndGroup { get; set; } public IMessageByMessageKey Repository { get; set; } public IRetryService RetryService { get; set; } public void Handle(NewMessageEvent @event) { Task.Factory.StartNew(() => Push(@event.Message), TaskCreationOptions.None); } public Type Type { get { return typeof(NewMessageEvent); } } public void Handle(object @event) { Handle((NewMessageEvent)@event); } private void Push(Message message) { var subscriptions = SubscriptionsByTopicAndGroup.Execute(message.TopicId); foreach (var subscription in subscriptions) { try { message.PushToSubscription(subscription); } catch (Exception ex) { System.Diagnostics.Trace.TraceError( string.Format(Business.Texts.ErrorPushingCallback, message.Id, subscription.Id) + "\r\n" + ex); RetryService.Add(new Retry(message, subscription)); } } } } }
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
namespace InventorShaftGenerator.Models { public class ReliefDimensions { public float MinInclusive { get; set; } public float MaxInclusive { get; set; } public float Width { get; set; } public float Width1 { get; set; } public float Width2 { get; set; } public float ReliefDepth { get; set; } public float ReliefDepth1 { get; set; } public float ReliefDepth2 { get; set; } public float Radius { get; set; } public float Radius1 { get; set; } public float[] Widthes { get; set; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DevZest.Data { [TestClass] public class ColumnsTests { [TestMethod] public void Columns_New() { { var column1 = new _Int32(); Assert.AreEqual(column1, Columns.New(column1)); } { var column1 = new _Int32(); var column2 = new _Int32(); var columnSet = Columns.New(column1, column2); Assert.AreEqual(2, columnSet.Count); Assert.IsTrue(columnSet.Contains(column1)); Assert.IsTrue(columnSet.Contains(column2)); } } [TestMethod] public void Columns_Union() { { Assert.AreEqual(Columns.Empty, Columns.Empty.Union(Columns.Empty)); } { var column1 = new _Int32(); Assert.AreEqual(column1, Columns.Empty.Union(column1)); Assert.AreEqual(column1, column1.Union(Columns.Empty)); } { var column1 = new _Int32(); Assert.AreEqual(column1, column1.Union(column1)); } { var column1 = new _Int32(); var column2 = new _Int32(); var columnSet = column1.Union(column2); Assert.AreEqual(2, columnSet.Count); Assert.IsTrue(columnSet.Contains(column1)); Assert.IsTrue(columnSet.Contains(column2)); } } [TestMethod] public void Columns_IsSubsetOf() { Assert.IsTrue(Columns.Empty.IsSubsetOf(Columns.Empty)); var column1 = new _Int32(); var column2 = new _Int32(); var column1And2 = Columns.New(column1, column2); Assert.IsTrue(column1.IsSubsetOf(column1And2)); Assert.IsTrue(column2.IsSubsetOf(column1And2)); Assert.IsTrue(column1And2.IsSubsetOf(column1And2)); } [TestMethod] public void Columns_IsProperSubsetOf() { Assert.IsTrue(Columns.Empty.IsSubsetOf(Columns.Empty)); var column1 = new _Int32(); var column2 = new _Int32(); var column1And2 = Columns.New(column1, column2); Assert.IsTrue(column1.IsProperSubsetOf(column1And2)); Assert.IsTrue(column2.IsProperSubsetOf(column1And2)); Assert.IsFalse(column1And2.IsProperSubsetOf(column1And2)); } [TestMethod] public void Columns_IsSupersetOf() { Assert.IsTrue(Columns.Empty.IsSubsetOf(Columns.Empty)); var column1 = new _Int32(); var column2 = new _Int32(); var column1And2 = Columns.New(column1, column2); Assert.IsTrue(column1And2.IsSupersetOf(column1)); Assert.IsTrue(column1And2.IsSupersetOf(column2)); Assert.IsTrue(column1And2.IsSupersetOf(column1And2)); } [TestMethod] public void Columns_IsProperSupersetOf() { Assert.IsTrue(Columns.Empty.IsSubsetOf(Columns.Empty)); var column1 = new _Int32(); var column2 = new _Int32(); var column1And2 = Columns.New(column1, column2); Assert.IsTrue(column1And2.IsProperSupersetOf(column1)); Assert.IsTrue(column1And2.IsProperSupersetOf(column2)); Assert.IsFalse(column1And2.IsProperSupersetOf(column1And2)); } [TestMethod] public void Columns_Equals() { var column1 = new _Int32(); var column2 = new _Int32(); var columns1 = Columns.Empty.Add(column1).Add(column2); var columns2 = Columns.Empty.Add(column2).Add(column1); Assert.IsTrue(columns1.Equals(columns2)); } } }
using System; using System.Threading; namespace MyDAL.Test.Common { internal class SyncState : ClassInstance<SyncState> { // public SyncState() { var seedStr = DateTime.Now.Ticks.ToString(); var seed = seedStr.Substring(seedStr.Length - 9, 9); _MockClient = new Random(Convert.ToInt32(seed)).Next(1, 100); } // internal int Start { get; set; } internal int LimitI { get; set; } internal TimeSpan Elapsed { get; set; } // internal string Result { get; set; } internal bool SuccessFlag { get; set; } // internal bool Wait { get; set; } internal SyncState WaitFlag { get; set; } internal void WaitSimple() { Thread.Sleep(1); } // private int _MockClient { get; set; } internal void MockClientSimple() { Thread.Sleep(this._MockClient); } } }
using System.Collections.Generic; namespace Journey.Domain.Entities { public class JourneyList { public JourneyList() { Trips = new List<JourneySelection>(); } public IList<JourneySelection> Trips { get; set; } public int Id { get; set; } public string Country { get; set; } public string City { get; set; } } }
using System; using Microsoft.Xna.Framework; namespace WeaponWizard { public class Timer { public Guid ID { get; set; } public GameTime StartTime { get; set; } public TimeSpan Time { get; set; } public bool DestroyAtEnd { get; set; } public Action Callback { get; set; } public Timer () { } } }
using System; using System.Collections.Generic; namespace Design_Patterns_in_CSharp.Observer { public abstract class Observer { public virtual void Notify() => Console.Error.WriteLine("Abstract Method!"); } public class Subject { private LinkedList<Observer> observers = new LinkedList<Observer>(); public void Register(Observer observer) { Console.WriteLine(observer + " is pushed!"); this.observers.AddLast(observer); } public void Unregister(Observer observer) { Console.WriteLine(observer + " is removed!"); this.observers.Remove(observer); } public void Notify() { foreach (var item in this.observers) item.Notify(); } } public class ConcreteSubject : Subject { private int subjectState; public int SubjectState { get => subjectState; set => subjectState = value; } } public class ConcreteObserver : Observer { private string name; private int state; private ConcreteSubject subject; public ConcreteObserver(string name, ConcreteSubject subject) { Console.WriteLine("ConcreteObserver " + name + " is created!"); this.name = name; this.subject = subject; } public override void Notify() { Console.WriteLine("ConcreteObserver's notify method"); Console.WriteLine(this.name, this.state); this.state = this.subject.SubjectState; } public ConcreteSubject Subject { get => subject; set => subject = value; } } }
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * 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; namespace Tizen.Pims.Calendar { internal enum CalendarError { None = Tizen.Internals.Errors.ErrorCode.None, OutOfMemory = Tizen.Internals.Errors.ErrorCode.OutOfMemory, InvalidParameter = Tizen.Internals.Errors.ErrorCode.InvalidParameter, FileNoSpace = Tizen.Internals.Errors.ErrorCode.FileNoSpaceOnDevice, PermissionDenied = Tizen.Internals.Errors.ErrorCode.PermissionDenied, NotSupported = Tizen.Internals.Errors.ErrorCode.NotSupported, NoData = Tizen.Internals.Errors.ErrorCode.NoData, DBLocked = Globals.ErrorCalendar | 0x81, ErrorDB = Globals.ErrorCalendar | 0x9F, IPCNotAvailable = Globals.ErrorCalendar | 0xB1, ErrorIPC = Globals.ErrorCalendar | 0xBF, ErrorSystem = Globals.ErrorCalendar | 0xEF, ErrorInternal = Globals.ErrorCalendar | 0x04, DBNotFound = Globals.ErrorCalendar | 0x05, }; internal static class Globals { internal const string LogTag = "Tizen.Pims.Calendar"; internal const int ErrorCalendar = -0x02000000; } internal static class CalendarErrorFactory { internal static void ThrowException(int e) { throw GetException(e); } internal static Exception GetException(int e) { Exception exp; switch ((CalendarError)e) { case CalendarError.OutOfMemory: exp = new OutOfMemoryException("Out of memory"); Log.Error(Globals.LogTag, "Out of memory"); break; case CalendarError.InvalidParameter: exp = new ArgumentException("Invalid parameter"); Log.Error(Globals.LogTag, "Invalid parameter"); break; case CalendarError.FileNoSpace: exp = new InvalidOperationException("File no space Error"); Log.Error(Globals.LogTag, "File no space Error"); break; case CalendarError.PermissionDenied: exp = new UnauthorizedAccessException("Permission denied"); Log.Error(Globals.LogTag, "Permission denied"); break; case CalendarError.NotSupported: exp = new NotSupportedException("Not supported"); Log.Error(Globals.LogTag, "Not supported"); break; case CalendarError.NoData: exp = new InvalidOperationException("No data found"); Log.Error(Globals.LogTag, "No data found"); break; case CalendarError.DBLocked: exp = new InvalidOperationException("DB locked"); Log.Error(Globals.LogTag, "DB locked"); break; case CalendarError.ErrorDB: exp = new InvalidOperationException("DB error"); Log.Error(Globals.LogTag, "DB error"); break; case CalendarError.IPCNotAvailable: exp = new InvalidOperationException("IPC not available"); Log.Error(Globals.LogTag, "IPC not available"); break; case CalendarError.ErrorIPC: exp = new InvalidOperationException("IPC error"); Log.Error(Globals.LogTag, "IPC error"); break; case CalendarError.ErrorSystem: exp = new InvalidOperationException("System error"); Log.Error(Globals.LogTag, "System error"); break; case CalendarError.ErrorInternal: exp = new InvalidOperationException("Internal error"); Log.Error(Globals.LogTag, "Internal error"); break; default: exp = new InvalidOperationException("Invalid operation"); Log.Error(Globals.LogTag, "Invalid operation"); break; } return exp; } } }
using System; using System.Data; using System.Data.SqlClient; using System.Web; using Appleseed.Configuration; using Appleseed.Settings; namespace Appleseed.DesktopModules { /// <summary> /// Database access code for the Monitoring Module /// Written by Paul Yarrow, paul@paulyarrow.com /// </summary> public class MonitoringDB { /// <summary> /// returns the total hit count for a portal /// </summary> /// <param name="portalID"></param> /// <returns></returns> public static int GetTotalPortalHits(int portalID) { SqlConnection myConnection = Config.SqlConnectionString; int totalHIts = 0; string sql = "Select count(ID) as hits " + " from rb_monitoring " + " where [PortalID] = " + portalID.ToString() + " "; return Convert.ToInt32(Helpers.DBHelper.ExecuteSQLScalar(sql)); } /// <summary> /// Return a dataset of stats for a given data range and portal /// </summary> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="reportType"></param> /// <param name="currentTabID"></param> /// <param name="includeMonitoringPage"></param> /// <param name="includeAdminUser"></param> /// <param name="includePageRequests"></param> /// <param name="includeLogon"></param> /// <param name="includeLogoff"></param> /// <param name="includeMyIPAddress"></param> /// <param name="portalID"></param> /// <returns></returns> public DataSet GetMonitoringStats(DateTime startDate, DateTime endDate, string reportType, long currentTabID, bool includeMonitoringPage, bool includeAdminUser, bool includePageRequests, bool includeLogon, bool includeLogoff, bool includeMyIPAddress, int portalID) { endDate = endDate.AddDays(1); // Firstly get the logged in users SqlConnection myConnection = Config.SqlConnectionString; SqlDataAdapter myCommand = new SqlDataAdapter("rb_GetMonitoringEntries", myConnection); myCommand.SelectCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4); parameterPortalID.Value = portalID; myCommand.SelectCommand.Parameters.Add(parameterPortalID); SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime, 8); parameterStartDate.Value = startDate; myCommand.SelectCommand.Parameters.Add(parameterStartDate); SqlParameter parameterEndDate = new SqlParameter("@EndDate", SqlDbType.DateTime, 8); parameterEndDate.Value = endDate; myCommand.SelectCommand.Parameters.Add(parameterEndDate); SqlParameter parameterReportType = new SqlParameter("@ReportType", SqlDbType.VarChar, 50); parameterReportType.Value = reportType; myCommand.SelectCommand.Parameters.Add(parameterReportType); SqlParameter parameterCurrentTabID = new SqlParameter("@CurrentTabID", SqlDbType.BigInt, 8); parameterCurrentTabID.Value = currentTabID; myCommand.SelectCommand.Parameters.Add(parameterCurrentTabID); SqlParameter parameterIncludeMoni = new SqlParameter("@IncludeMonitorPage", SqlDbType.Bit, 1); parameterIncludeMoni.Value = includeMonitoringPage; myCommand.SelectCommand.Parameters.Add(parameterIncludeMoni); SqlParameter parameterIncludeAdmin = new SqlParameter("@IncludeAdminUser", SqlDbType.Bit, 1); parameterIncludeAdmin.Value = includeAdminUser; myCommand.SelectCommand.Parameters.Add(parameterIncludeAdmin); SqlParameter parameterIncludePageRequests = new SqlParameter("@IncludePageRequests", SqlDbType.Bit, 1); parameterIncludePageRequests.Value = includePageRequests; myCommand.SelectCommand.Parameters.Add(parameterIncludePageRequests); SqlParameter parameterIncludeLogon = new SqlParameter("@IncludeLogon", SqlDbType.Bit, 1); parameterIncludeLogon.Value = includeLogon; myCommand.SelectCommand.Parameters.Add(parameterIncludeLogon); SqlParameter parameterIncludeLogoff = new SqlParameter("@IncludeLogoff", SqlDbType.Bit, 1); parameterIncludeLogoff.Value = includeLogoff; myCommand.SelectCommand.Parameters.Add(parameterIncludeLogoff); SqlParameter parameterIncludeIPAddress = new SqlParameter("@IncludeIPAddress", SqlDbType.Bit, 1); parameterIncludeIPAddress.Value = includeMyIPAddress; myCommand.SelectCommand.Parameters.Add(parameterIncludeIPAddress); SqlParameter parameterIPAddress = new SqlParameter("@IPAddress", SqlDbType.VarChar, 16); parameterIPAddress.Value = HttpContext.Current.Request.UserHostAddress; myCommand.SelectCommand.Parameters.Add(parameterIPAddress); // Create and Fill the DataSet DataSet myDataSet = new DataSet(); try { myCommand.Fill(myDataSet); } finally { myConnection.Close(); } // Return the DataSet return myDataSet; } } }
using FluentValidation; namespace Application.Groups.Command.ChangeGroupName { public class ChangeGroupNameCommandValidator : AbstractValidator<ChangeGroupNameCommand> { public ChangeGroupNameCommandValidator() { // group name RuleFor(x => x.Name) .NotEmpty() .MaximumLength(255); } } }
namespace SharpPad.InformationStuff { public enum InfoTypes { Information, Status, Warning, Error, FileIO, FileExplorerError } }
using Spine.Unity; using System.Collections; using System.Collections.Generic; using UnityEngine; public class NpcAnimator : CharacterAnimator { //public SkeletonAnimation body; //public PlayerSkeletons bodyData; //Can be replaced with skin lenght if I figure out how. private int minSkinId = 1; private int maxSkinId = 6; private Gender gender; protected override void Start() { CreateNewSkin(); base.Start(); } private void CreateNewSkin() { int id = Random.Range(minSkinId, maxSkinId); string newSkin = id < 10 ? "skin0" + id : "skin" + id; bodySkinName = PickGender() + newSkin; } private string PickGender() { Gender randomGender = (Gender)Random.Range(0, System.Enum.GetValues(typeof(Gender)).Length); switch (randomGender) { case Gender.FEMALE: return "f_"; case Gender.MALE: return "m_"; default: return "null_"; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using DG.Tweening; using Type = GamePlay.Client.View.PlayerEffectManager.Type; using Mahjong.Logic; namespace GamePlay.Client.View.SubManagers { public class EffectManager : MonoBehaviour { public Image RichiImage; public Image ChowImage; public Image PongImage; public Image KongImage; public Image BeiImage; public Image TsumoImage; public Image RongImage; private readonly IDictionary<Type, Image> dict = new Dictionary<Type, Image>(); private void Awake() { dict.Clear(); foreach (Type e in Enum.GetValues(typeof(Type))) { var fieldInfo = GetType().GetField($"{e}Image"); var image = (Image)fieldInfo.GetValue(this); dict.Add(e, image); } } public float StartAnimation(Type type) { var image = dict[type]; var sequence = DOTween.Sequence(); sequence.Append(image.DOFade(1, MahjongConstants.FadeDuration)) .Append(image.DOFade(0, MahjongConstants.FadeDuration)); return sequence.Duration(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VoiceModel.TropoModel { public class TAction { public string name { get; set; } public int attempts { get; set; } public string disposition { get; set; } public int confidence { get; set; } public string interpretation { get; set; } public string utterrance { get; set; } public string value { get; set; } public string concept { get; set; } public string xml { get; set; } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System; using System.IO; using System.Reflection; using System.Text; namespace JitProblem { class Program { static void Main(string[] args) { for (var i = 0; i < 1000; i++) { // Generate two random strings var s1 = RandomString(50); var s2 = RandomString(50); // Calculate similarity var result = CalculateSimilarity(s1, s2); // Console.WriteLine($"{s1} - {s2} = {result}"); } } private static MetadataReference[] references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }; private static int CalculateSimilarity(string s1, string s2) { // Scenario: Calculate similarity of two strings (e.g. customer names) // Algorithm should be pluggable --> read from C# text (e.g. from DB, // here from resources). // Use Roslyn to parse text var syntaxTree = CSharpSyntaxTree.ParseText(ReadMacroFromFile()); // Compile to an in-memory assembly var assembly = CompileToAssembly(syntaxTree, references); // Call comparison algorithm using Reflection var type = assembly.GetType("JitProblem.LevenshteinDistance"); return (int)type.GetMethod("Compute").Invoke(null, new[] { s1, s2 }); } private static int seed = 0; private static string RandomString(int size) { var random = new Random(++seed); var builder = new StringBuilder(); for (int i = 0; i < size; i++) { builder.Append(Convert.ToChar(random.Next(65, 65 + 26))); } return builder.ToString(); } private static string ReadMacroFromFile() { string macroText; using (var reader = File.OpenText(@"C:\Code\GitHub\htl-csharp\profiling\0010-JitProblem\LevenshteinMacro.txt")) { macroText = reader.ReadToEnd(); } return macroText; } private static Assembly CompileToAssembly(SyntaxTree macro, MetadataReference[] references) { var assemblyName = Path.GetRandomFileName(); CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { macro }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); ms.Seek(0, SeekOrigin.Begin); return Assembly.Load(ms.ToArray()); } } } }
namespace BootstrapMvc.Controls { using System; using BootstrapMvc.Core; using System.Collections.Generic; public class SelectOptGroup : ContentElement<SelectOptGroupContent>, ISelectItem, IDisableable { public bool Disabled { get; set; } public string Label { get; set; } public IEnumerable<ISelectItem> ItemsValue { get; set; } protected override SelectOptGroupContent CreateContentContext(IBootstrapContext context) { return new SelectOptGroupContent(context, this); } protected override void WriteSelfStart(System.IO.TextWriter writer) { var tb = Helper.CreateTagBuilder("optgroup"); tb.MergeAttribute("label", Label, true); if (Disabled) { tb.MergeAttribute("disabled", "disabled", true); } ApplyCss(tb); ApplyAttributes(tb); tb.WriteStartTag(writer); if (ItemsValue != null) { foreach (var item in ItemsValue) { item.Parent = this; item.WriteTo(writer); } } } protected override void WriteSelfEnd(System.IO.TextWriter writer) { writer.Write("</optgroup>"); } void IDisableable.SetDisabled(bool disabled) { Disabled = disabled; } bool IDisableable.Disabled() { return Disabled; } } }
using DataAccess.Database; using DataAccess.Repositories; using GUI_Interface.ViewModels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace GUI_Interface { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public IConfiguration Configuration { get; private set; } public IServiceProvider ServiceProvider { get; private set; } private void OnStartup(object sender, StartupEventArgs e) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); Configuration = builder.Build(); var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); ServiceProvider = serviceCollection.BuildServiceProvider(); var mainwindow = ServiceProvider.GetRequiredService<MainWindow>(); mainwindow.Show(); } private void ConfigureServices(IServiceCollection services) { services.AddSingleton<IConfiguration>(Configuration); services.AddScoped<ILegatRepository, LegatRepository>(); services.AddScoped<IDatabase, MySqlDatabase>(); services.AddScoped<LegatViewModel>(); services.AddTransient<MainWindow>(); } } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Google.Apis.Json; using Google.Apis.Testing; using Google.Apis.Util; namespace Google.Apis.Discovery { /// <summary> /// Defines the factory parameters which are used to create a v1.0 Service /// </summary> public class FactoryParameterV1_0 : BaseFactoryParameters { public FactoryParameterV1_0() {} /// <summary> /// Creates a new v1.0 factory parameter by splitting the specified service URI into ServerUrl and BasePath /// </summary> public FactoryParameterV1_0(Uri serviceUri) : base(serviceUri) {} /// <summary> /// Creates a parameter set for a v1.0 service /// </summary> /// <param name="serverUrl">The absolute URL pointing to the server on which the service resides</param> public FactoryParameterV1_0(string serverUrl) : base(serverUrl) {} /// <summary> /// Creates a parameter set for a v1.0 service /// </summary> /// <param name="serverUrl">The absolute URL pointing to the server on which the service resides</param> /// <param name="basePath">The relative path to the service on the server</param> public FactoryParameterV1_0(string serverUrl, string basePath) : base(serverUrl, basePath) {} } /// <summary> /// Defines the factory parameters which are used to create a v0.3 Service /// </summary> public class FactoryParameterV0_3 : BaseFactoryParameters { public FactoryParameterV0_3() {} /// <summary> /// Creates a new v0.3 factory parameter by splitting the specified service URI into ServerUrl and BasePath /// </summary> public FactoryParameterV0_3(Uri serviceUri) : base(serviceUri) {} /// <summary> /// Creates a parameter set for a v0.3 service /// </summary> /// <param name="serverUrl">The absolute URL pointing to the server on which the service resides</param> public FactoryParameterV0_3(string serverUrl) : base(serverUrl) {} /// <summary> /// Creates a parameter set for a v0.3 service /// </summary> /// <param name="serverUrl">The absolute URL pointing to the server on which the service resides</param> /// <param name="basePath">The relative path to the service on the server</param> public FactoryParameterV0_3(string serverUrl, string basePath) : base(serverUrl, basePath) {} } /// <summary> /// Defines the base factory parameters which are used to create a service /// </summary> public abstract class BaseFactoryParameters : IFactoryParameter { /// <summary> /// The default server URL used /// Points to the Google API repository /// </summary> public const string DefaultServerUrl = "https://www.googleapis.com"; /// <summary> /// Creates a new factory parameter for a service /// Sets the server url to the default google url /// </summary> protected BaseFactoryParameters() { ServerUrl = DefaultServerUrl; } /// <summary> /// Creates a new factory parameter by splitting the specified service URI into ServerUrl and BasePath /// </summary> protected BaseFactoryParameters(Uri serviceUri) { serviceUri.ThrowIfNull("serviceUri"); // Retrieve Scheme and Host ServerUrl = serviceUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped); ServerUrl.ThrowIfNullOrEmpty("ServerUrl"); // Retrieve the remaining right part BasePath = serviceUri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped); ServerUrl.ThrowIfNullOrEmpty("BasePath"); } /// <summary> /// Creates a new factory parameter for a service /// </summary> protected BaseFactoryParameters(string serverUrl) { serverUrl.ThrowIfNullOrEmpty("serverUrl"); ServerUrl = serverUrl; } /// <summary> /// Creates a new factory parameter for a service /// </summary> /// <param name="serverUrl">URL of this service</param> /// <param name="basePath">Base path to the service</param> protected BaseFactoryParameters(string serverUrl, string basePath) : this(serverUrl) { BasePath = basePath; } /// <summary> /// The absolute server URL /// </summary> public string ServerUrl { get; set; } /// <summary> /// The relative base path /// </summary> public string BasePath { get; set; } } /// <summary> /// A Factory used by discovery to create v1.0 Services /// </summary> internal class ServiceFactoryDiscoveryV1_0 : BaseServiceFactory { public ServiceFactoryDiscoveryV1_0(JsonDictionary discovery, FactoryParameterV1_0 param) : base(discovery, param) {} public override IService GetService() { return new ServiceV1_0((FactoryParameterV1_0) Param, Information); } } /// <summary> /// A Factory used by discovery to create v0.3 Services /// </summary> internal class ServiceFactoryDiscoveryV0_3 : BaseServiceFactory { public ServiceFactoryDiscoveryV0_3(JsonDictionary discovery, FactoryParameterV0_3 param) : base(discovery, param) {} public override IService GetService() { return new ServiceV0_3((FactoryParameterV0_3) Param, Information); } } /// <summary> /// An abstract version independent implementation of a service factory /// </summary> internal abstract class BaseServiceFactory : IServiceFactory { protected BaseServiceFactory(JsonDictionary discovery, BaseFactoryParameters param) { discovery.ThrowIfNullOrEmpty("discovery"); param.ThrowIfNull("param"); Name = discovery.GetMandatoryValue<string>("name"); if (Name.IsNullOrEmpty()) { throw new ArgumentException("No service name found in the JsonDictionary"); } Information = discovery; Param = param; } [VisibleForTestOnly] internal JsonDictionary Information { get; private set; } [VisibleForTestOnly] internal BaseFactoryParameters Param { get; private set; } [VisibleForTestOnly] internal string Name { get; private set; } #region IServiceFactory Members public abstract IService GetService(); #endregion } }
namespace Ryujinx.HLE.HOS.Services.Sdb.Pl.Types { public enum SharedFontType { JapanUsEurope = 0, SimplifiedChinese = 1, SimplifiedChineseEx = 2, TraditionalChinese = 3, Korean = 4, NintendoEx = 5, Count } }
namespace EnergyManagementScheduler.WebJob.Contracts { public class Results { public Output1 Output1 { get; set; } } }
using System.Threading.Tasks; namespace RoslynPad.UI { public interface IDialog { Task ShowAsync(); void Close(); } }
using JitEvolution.Core.Models.Queue; using JitEvolution.Core.Repositories.Queue; using Microsoft.EntityFrameworkCore; namespace JitEvolution.Data.Repositories.Queue { internal class QueueItemRepository : BaseCrudRepository<QueueItem>, IQueueItemRepository { public QueueItemRepository(JitEvolutionDbContext dbContext) : base(dbContext) { } public Task<QueueItem?> GetNextItemAsync() { var validItems = Queryable .GroupBy(x => x.ProjectId) .Where(x => !x.Any(y => y.IsActive)) .Select(x => x.Key); return Queryable .Where(x => validItems.Contains(x.ProjectId)) .OrderBy(x => x.CreatedAt) .FirstOrDefaultAsync(); } public Task<QueueItem?> GetNextItemForAsync(Guid projectId) { var validItems = Queryable .Where(x => x.ProjectId == projectId) .GroupBy(x => x.ProjectId) .Where(x => !x.Any(y => y.IsActive)) .Select(x => x.Key); return Queryable .Where(x => validItems.Contains(x.ProjectId)) .OrderBy(x => x.CreatedAt) .FirstOrDefaultAsync(); } } }
using System; using UnityEngine; using UnityEngine.Tilemaps; [Serializable] public class Painter { public TileBase tile; private const int wallTile = 1; public void DrawRectangleRoom(Vector2Int startPosition, Vector2Int endPosition, Tilemap tilemap) { if (tile != null) { for (int i = startPosition.x - wallTile; i <= endPosition.x + wallTile; i++) { for (int j = startPosition.y - wallTile; j <= endPosition.y + wallTile; j++) { tilemap.SetTile(new Vector3Int(i, j, 0), tile); } } } } }
using FlatRedBall.Glue.Errors; using FlatRedBall.Glue.SaveClasses; using System.Security.Cryptography; namespace FlatRedBall.Glue.Plugins.ExportedInterfaces.CommandInterfaces { public interface IRefreshCommands { /// <summary> /// Refreshes everything for the selected TreeNode /// </summary> void RefreshUiForSelectedElement(); void RefreshTreeNodes(); /// <summary> /// Refreshes the tree node for the selected element. /// This may add or remove tree nodes depending on whether /// the tree node is already created, and if the element's /// IsHiddenInTreeView is set to true. /// </summary> /// <param name="element">IElement to update the tree node for</param> void RefreshTreeNodeFor(IElement element); void RefreshUi(StateSaveCategory category); /// <summary> /// Refreshes the UI for the Global Content tree node /// </summary> void RefreshGlobalContent(); /// <summary> /// Refreshes all errors. /// </summary> void RefreshErrors(); void RefreshErrorsFor(IErrorReporter errorReporter); /// <summary> /// Refreshes the propertygrid so that the latest data will be shown. This should be called whenever data /// shown in the property grid has changed because the propertygrid does not automatically reflect the change. /// </summary> void RefreshPropertyGrid(); void RefreshVariables(); void RefreshSelection(); void RefreshDirectoryTreeNodes(); } }