content
stringlengths
23
1.05M
using System.Collections.Generic; using JetBrains.Annotations; using MAVN.Service.AdminAPI.Models.ActionRules; namespace MAVN.Service.AdminAPI.Models.EarnRules { /// <summary> /// Represents a earn rule creating details. /// </summary> [PublicAPI] public class EarnRuleCreateModel : EarnRuleBaseModel { /// <summary> /// A collection of earn rule conditions. /// </summary> public IReadOnlyList<ConditionCreateModel> Conditions { get; set; } /// <summary> /// A collection of earn rule contents. /// </summary> public IReadOnlyList<MobileContentCreateRequest> MobileContents { get; set; } } }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Order; namespace Xamarin.Forms.Benchmarks { [MemoryDiagnoser] [Orderer (SummaryOrderPolicy.FastestToSlowest)] public class Layouts : BaseBenchmark { const int ViewCount = 100; const int ViewSize = 10; static readonly Thickness Empty = new Thickness (0); static BoxView [] Views; [GlobalSetup] public void GlobalSetup() { Views = new BoxView [ViewCount]; for (int i = 0; i < Views.Length; i++) { Views [i] = new BoxView { WidthRequest = ViewSize, HeightRequest = ViewSize, }; } } [IterationCleanup] public void Cleanup () { foreach (var view in Views) { view.Parent = null; } } [Benchmark] public void StacksOfStacks () { var verticalStack = new StackLayout { Padding = Empty, Spacing = 0, Orientation = StackOrientation.Vertical, }; var horizontalStack = default (StackLayout); for (int i = 0; i < Views.Length; i++) { if (i % ViewSize == 0) { verticalStack.Children.Add (horizontalStack = new StackLayout { Padding = Empty, Spacing = 0, Orientation = StackOrientation.Horizontal, }); } horizontalStack.Children.Add (Views [i]); } Renderer.CreateNativeView (verticalStack); } [Benchmark] public void GridWithRowsAndColumns () { var grid = new Grid { Padding = Empty, ColumnSpacing = 0, RowSpacing = 0, }; for (int i = 0; i < ViewSize; i++) { grid.ColumnDefinitions.Add (new ColumnDefinition { Width = GridLength.Auto }); grid.RowDefinitions.Add (new RowDefinition { Height = GridLength.Auto }); } for (int i = 0; i < Views.Length; i++) { var view = Views [i]; Grid.SetColumn (view, i / ViewSize); Grid.SetRow (view, i % ViewSize); grid.Children.Add (view); } Renderer.CreateNativeView (grid); } [Benchmark] public void AbsoluteLayoutWithMath () { var layout = new AbsoluteLayout { Padding = Empty, WidthRequest = ViewSize * ViewSize, HeightRequest = ViewSize * ViewSize, }; var rect = new Rectangle (0, 0, ViewSize, ViewSize); for (int i = 0; i < Views.Length; i++) { var view = Views [i]; rect.X = i / ViewSize; rect.Y = i % ViewSize; AbsoluteLayout.SetLayoutBounds (view, rect); layout.Children.Add (view); } Renderer.CreateNativeView (layout); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.Experimental.UIElements; using UnityEditor.Experimental.UIElements.GraphView; using UnityEngine.Experimental.UIElements; using GraphProcessor; [NodeCustomEditor(typeof(CircleRadians))] public class CircleRadiansView : BaseNodeView { CircleRadians node; VisualElement listContainer; public override void Enable() { node = nodeTarget as CircleRadians; listContainer = new VisualElement(); // Create your fields using node's variables and add them to the controlsContainer controlsContainer.Add(listContainer); // TODO: find a way to get PortView from here UpdateOutputRadians(GetPortFromFieldName("outputRadians").connectionCount); } void UpdateOutputRadians(int count) { node.outputRadians = new List<float>(); listContainer.Clear(); for (int i = 0; i < count; i++) { float r = (Mathf.PI * 2 / count) * i; node.outputRadians.Add(r); listContainer.Add(new Label(r.ToString("F3"))); } } public override void OnPortConnected(PortView port) { // There is only one port on this node so it can only be the output UpdateOutputRadians(port.connectionCount); } public override void OnPortDisconnected(PortView port) { UpdateOutputRadians(port.connectionCount); } }
using ArchitectNow.DevUp16.WebDevPrecompiler.Data.Models; namespace ArchitectNow.DevUp16.WebDevPrecompiler.Data.Repositories { public interface IToDoRepository : IBaseRepository<ToDo> { } }
using Microsoft.AspNetCore.Mvc.Formatters; using System.IO; using System.Threading.Tasks; namespace grava.Controllers { /// <summary> /// Helper to enable passing text/plain for PUT method /// </summary> public class TextPlainInputFormatter : InputFormatter { private const string ContentType = "text/plain"; public TextPlainInputFormatter() { SupportedMediaTypes.Add(ContentType); } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { Microsoft.AspNetCore.Http.HttpRequest request = context.HttpContext.Request; using StreamReader reader = new StreamReader(request.Body); string content = await reader.ReadToEndAsync(); return await InputFormatterResult.SuccessAsync(content); } public override bool CanRead(InputFormatterContext context) { string contentType = context.HttpContext.Request.ContentType; return contentType.StartsWith(ContentType); } } }
// // Copyright (C) 2018 Fluendo S.A. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. // using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace XAMLator.HttpServer { /// <summary> /// Route that binds a handler for a resource based in the Http method and the path of the request. /// </summary> public class Route { static readonly Regex PathRegex = new Regex(@"\{(?<param>\S+)\}", RegexOptions.Compiled); readonly string[] paramNames; public Route(string method, string path, Func<HttpRequest, Task<HttpResponse>> action) { Method = method; Path = path; Action = action; var paramNames = new List<string>(); Regex = new Regex("^" + PathRegex.Replace(path, m => { var p = m.Groups["param"].Value; paramNames.Add(p); return String.Format(@"(?<{0}>\S+)", p); }) + "$"); this.paramNames = paramNames.ToArray(); } /// <summary> /// Gets the Http method. /// </summary> /// <value>The Http method.</value> string Method { get; set; } /// <summary> /// Gets the resource path. /// </summary> /// <value>The path.</value> string Path { get; set; } /// <summary> /// Gets the action that will handle the request. /// </summary> /// <value>The action.</value> Func<HttpRequest, Task<HttpResponse>> Action { get; set; } Regex Regex { get; set; } /// <summary> /// Checks if a request should be handled by this match. /// </summary> /// <returns><c>true</c>, if there is match, <c>false</c> otherwise.</returns> /// <param name="request">Request.</param> public bool IsMatch(HttpRequest request) { return request.HttpMethod == Method && Regex.IsMatch(request.Url.AbsolutePath); } /// <summary> /// Calls the resource handler registered for this route. /// </summary> /// <returns>The response.</returns> /// <param name="request">The request.</param> public Task<HttpResponse> Invoke(HttpRequest request) { var match = Regex.Match(request.Url.AbsolutePath); var urlParameters = paramNames.ToDictionary(k => k, k => match.Groups[k].Value); //NameValueCollection queryParameters = HttpUtility.ParseQueryString(request.Url.Query); NameValueCollection queryParameters = new NameValueCollection(); var parameters = request.Parameters as IDictionary<string, Object>; foreach (var kv in urlParameters) { parameters.Add(kv.Key, kv.Value); } foreach (String key in queryParameters.AllKeys) { parameters.Add(key, queryParameters[key]); } return Action.Invoke(request); } } }
// Copyright (c) MudBlazor 2021 // MudBlazor licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Blazored.LocalStorage; namespace MudBlazor.Docs.Services.UserPreferences { public interface IUserPreferencesService { /// <summary> /// Saves UserPreferences in local storage /// </summary> /// <param name="userPreferences">The userPreferences to save in the local storage</param> public Task SaveUserPreferences(UserPreferences userPreferences); /// <summary> /// Loads UserPreferences in local storage /// </summary> /// <returns>UserPreferences object. Null when no settings were found.</returns> public Task<UserPreferences> LoadUserPreferences(); } public class UserPreferencesService : IUserPreferencesService { private readonly ILocalStorageService _localStorage; private const string Key = "userPreferences"; public UserPreferencesService(ILocalStorageService localStorage) { _localStorage = localStorage; } public async Task SaveUserPreferences(UserPreferences userPreferences) { await _localStorage.SetItemAsync(Key, userPreferences); } public async Task<UserPreferences> LoadUserPreferences() { return await _localStorage.GetItemAsync<UserPreferences>(Key); } } }
//--------------------------------------------------------------------------- // // <copyright file="IRecyclingItemContainerGenerator.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: IRecyclingItemContainerGenerator interface // // Spec: http://wpf/sites/Arrowhead/Shared%20Documents/Specs/Item%20Container%20Recycling%20Spec.docx // //--------------------------------------------------------------------------- using System; namespace System.Windows.Controls.Primitives { /// <summary> /// Interface through which a layout element (such as a panel) marked /// as an ItemsHost communicates with the ItemContainerGenerator of its /// items owner. /// /// This interface adds the notion of recycling a container to the /// IItemContainerGenerator interface. This is used for virtualizing /// panels. /// </summary> public interface IRecyclingItemContainerGenerator : IItemContainerGenerator { /// <summary> /// Recycle generated elements. /// </summary> /// <remarks> /// Equivalent to Remove() except that the Generator retains this container in a list. /// This container will be handed back in a future call to GenerateNext() /// /// The position must refer to a previously generated item, i.e. its /// Offset must be 0. /// </remarks> void Recycle(GeneratorPosition position, int count); } }
using Microsoft.EntityFrameworkCore; using PapoDeDev.TDD.Domain.Core.Interfaces.Repository; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace PapoDeDev.TDD.Infra.Repository { public class UnitOfWork : IUnitOfWork { private readonly RepositoryContext _Context; public UnitOfWork(RepositoryContext context) { _Context = context; } public async Task<int> CommitAsync(CancellationToken cancellationToken = default) { int result = await _Context.SaveChangesAsync(); return result; } public Task RollbackAsync(CancellationToken cancellationToken = default) { _Context.ChangeTracker.Entries() .Where(e => e.Entity != null).ToList() .ForEach(e => e.State = EntityState.Detached); return Task.CompletedTask; } } }
using MySqlConnector; using System.Data; namespace Dapper.Easies.MySql { public class MySqlDbConnectionFactory : IDbConnectionFactory { private readonly string _connectionString; public MySqlDbConnectionFactory(string connectionString) { _connectionString = connectionString; } public IDbConnection Create() { return new MySqlConnection(_connectionString); } } }
using System.Collections.Generic; using System.IO; using System.Windows.Forms; namespace Fullscreenizer { /** * Config format: * | bool | default to false | If the hotkey is activated upon load. * | int | default to 0 | Bit flag for the modifier of the hotkey modifier(s). * | int | default to 0 | Bit flag for the key of the hotkey. * | bool | default to true | Scale the window when fullscreenizing. * | bool | default to true | Move the window to the top-left when fullscreenizing. * | bool | default to true | Minimize the application to tray. * | string | default to none | All following lines are read as window classes to look for. */ public class Config { private const string CONFIG_FILE = "fullscreenizer.cfg"; private bool _hotkeyActive; public bool HotkeyActive { get{ return _hotkeyActive; } set{ _hotkeyActive = value; } } private Modifier _modifierFlags; public Modifier ModifierFlags { get{ return _modifierFlags; } set{ _modifierFlags = value; } } private Keys _keyFlag; public Keys KeyFlags { get{ return _keyFlag; } set{ _keyFlag = value; } } private bool _scaleWindow; public bool ScaleWindow { get{ return _scaleWindow; } set{ _scaleWindow = value; } } private bool _moveWindow; public bool MoveWindow { get{ return _moveWindow; } set{ _moveWindow = value; } } private bool _minimizeToTray; public bool MinimizeToTray { get{ return _minimizeToTray; } set{ _minimizeToTray = value; } } private List<string> _classes = new List<string>(); public List<string> Classes { get{ return _classes; } set{ _classes = value; } } public void reset() { _hotkeyActive = false; _modifierFlags = Modifier.Ctrl; _keyFlag = Keys.Home; _scaleWindow = true; _moveWindow = true; _minimizeToTray = true; _classes.Clear(); } public bool readConfigFile() { reset(); // If the config file couldn't be found, create a default config file. if( !File.Exists(CONFIG_FILE) ) { createDefaultConfig(); } // Read the hotkey and classes from the config file. StreamReader sr = new StreamReader(new FileStream(CONFIG_FILE, FileMode.Open)); if( !readHotkeyPart(sr) ) { return false; } if( !readOptionsPart(sr) ) { return false; } readClassesPart(sr); sr.Close(); return true; } private bool readHotkeyPart( StreamReader sr ) { // One string used for all parameters. If this is null after reading a line, there was no contents to read. string line = null; // Read the active status of the hotkey. if( ((line = sr.ReadLine()) == null) || !bool.TryParse(line, out _hotkeyActive) ) { return false; } // Read the hotkey modifier flags. int tmpModifier = 0; if( ((line = sr.ReadLine()) == null) || !int.TryParse(line, out tmpModifier) ) { return false; } _modifierFlags = (Modifier)tmpModifier; // Read the hotkey key flag. int tmpKey = 0; if( ((line = sr.ReadLine()) == null) || !int.TryParse(line, out tmpKey) ) { return false; } _keyFlag = (Keys)tmpKey; // If no modifier or no key is provided, fail. if( _modifierFlags == Modifier.None || _keyFlag == 0 ) { return false; } return true; } private bool readOptionsPart( StreamReader sr ) { string line = null; // Read scale window. if( ((line = sr.ReadLine()) == null) || !bool.TryParse(line, out _scaleWindow) ) { return false; } // Read move window. if( ((line = sr.ReadLine()) == null) || !bool.TryParse(line, out _moveWindow) ) { return false; } // Read minimize to tray. if( ((line = sr.ReadLine()) == null) || !bool.TryParse(line, out _minimizeToTray) ) { return false; } return true; } private void readClassesPart( StreamReader sr ) { string line = null; while( (line = sr.ReadLine()) != null ) { // If the string is invalid, ignore it. if( string.IsNullOrWhiteSpace(line) || string.IsNullOrEmpty(line) ) { continue; } _classes.Add(line); } } public void createDefaultConfig() { reset(); // Just to be safe. StreamWriter sw = new StreamWriter(new FileStream(CONFIG_FILE, FileMode.Create)); sw.WriteLine(_hotkeyActive.ToString()); sw.WriteLine(((int)_modifierFlags).ToString()); sw.WriteLine(((int)_keyFlag).ToString()); sw.WriteLine(_scaleWindow.ToString()); sw.WriteLine(_moveWindow.ToString()); sw.WriteLine(_minimizeToTray.ToString()); sw.Close(); } public void writeConfigFile() { StreamWriter sw = new StreamWriter(new FileStream(CONFIG_FILE, FileMode.Create)); sw.WriteLine(_hotkeyActive.ToString()); sw.WriteLine(((int)_modifierFlags).ToString()); sw.WriteLine(((int)_keyFlag).ToString()); sw.WriteLine(_scaleWindow.ToString()); sw.WriteLine(_moveWindow.ToString()); sw.WriteLine(_minimizeToTray.ToString()); foreach( string curr in _classes ) { sw.WriteLine(curr); } sw.Close(); } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kodestruct.Common.Entities; using Kodestruct.Common.Section.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Common.CalculationLogger.Interfaces; namespace Kodestruct.Steel.AISC.AISC360v10.Compression { public abstract class ColumnFlexuralBuckling: SteelColumn { public ColumnFlexuralBuckling(ISteelSection Section, double L_ex, double L_ey, ICalcLog CalcLog) : base(Section,L_ex,L_ey, CalcLog) { } public double GetFlexuralElasticBucklingStressFe() { double FeMinor = GetFeSingleAxis(false); double FeMajor = GetFeSingleAxis(true); return Math.Min(FeMinor, FeMajor); } protected virtual double GetSlendernessKLr(bool IsMajorAxis) { double K; double L; double r; if (IsMajorAxis==true) { L = L_ex; r = Section.Shape.r_x; } else { L = L_ey; r = Section.Shape.r_y; } double Slenderness = L / r; return Slenderness; } private double GetFeSingleAxis(bool IsMajorAxis) { double E = Section.Material.ModulusOfElasticity; double Slenderness = GetSlendernessKLr(IsMajorAxis); double Fe; if (Slenderness == 0) { //double F_y = this.Section.Material.YieldStress; //Fe = F_y; Fe = double.PositiveInfinity; } else { Fe = GetF_e(E,Slenderness); } return Fe; } protected virtual double GetF_e(double E, double SlendernessKLr) { double Fe=0; double Slenderness = SlendernessKLr; FlexuralBucklingCriticalStressCalculator fcalc = new FlexuralBucklingCriticalStressCalculator(); Fe = fcalc.GetF_e(E, Slenderness); //if (Slenderness != 0) //{ // //(E3-4) // Fe = Math.Pow(Math.PI, 2) * E / Math.Pow(Slenderness, 2); //} //else //{ // return double.PositiveInfinity; //} return Fe; } protected virtual double GetCriticalStressFcr(double Fe, double Q=1.0) { double Fcr = 0.0; double Fy = Section.Material.YieldStress; FlexuralBucklingCriticalStressCalculator fcalc = new FlexuralBucklingCriticalStressCalculator(); return fcalc.GetCriticalStressFcr(Fe, Fy, Q); //if (Fe != double.PositiveInfinity) //{ // double stressRatio = Q * Fy / Fe; // if (stressRatio > 2.25) // { // Fcr = 0.877 * Fe; // (E3-3) if Q<1 then (E7-3) // } // else // { // Fcr = Q * Math.Pow(0.658, stressRatio) * Fy; //(E3-2) if Q<1 then (E7-2) // } //} //else //{ // Fcr = Fy; //} //return Fcr; } public double GetCriticalStressFcr_Y() { double Fcr = GetFeSingleAxis(false); return Fcr; } public double GetCriticalStressFcr_X() { double Fcr = GetFeSingleAxis(true); return Fcr; } public double GetReductionFactorQ(double Fcr) { double Qs = GetReductionFactorForUnstiffenedElementQs(); double Qa = GetReductionFactorForStiffenedElementQa(Fcr); double Q = Qs * Qa; //User Note for E7 return Q; } public virtual double GetReductionFactorForStiffenedElementQa(double Fcr) { return 1.0; } public virtual double GetReductionFactorForUnstiffenedElementQs() { return 1.0; } } }
using System.Collections.Generic; using System.IO; using System.Text; using SIL.Machine.Tokenization; using SIL.Machine.Utils; using SIL.Scripture; namespace SIL.Machine.Corpora { public abstract class UsfmTextBase : ScriptureText { private static readonly HashSet<string> NonVerseParaStyles = new HashSet<string> { "ms", "mr", "s", "sr", "r", "d", "sp", "rem", "restore", "cl", "cp" }; private static readonly HashSet<string> SpanMarkers = new HashSet<string> { "w", "jmp" }; private static readonly HashSet<string> EmbedMarkers = new HashSet<string> { "fig", "va", "vp", "pro", "rq", "fm" }; private readonly UsfmParser _parser; private readonly Encoding _encoding; private readonly bool _includeMarkers; protected UsfmTextBase(ITokenizer<string, int, string> wordTokenizer, string id, UsfmStylesheet stylesheet, Encoding encoding, ScrVers versification, bool includeMarkers) : base(wordTokenizer, id, versification) { _parser = new UsfmParser(stylesheet); _encoding = encoding; _includeMarkers = includeMarkers; } protected override IEnumerable<TextSegment> GetSegmentsInDocOrder(bool includeText = true) { string usfm = ReadUsfm(); UsfmMarker curEmbedMarker = null; UsfmMarker curSpanMarker = null; var sb = new StringBuilder(); string chapter = null, verse = null; bool sentenceStart = true; UsfmToken prevToken = null; bool isVersePara = false; foreach (UsfmToken token in _parser.Parse(usfm)) { switch (token.Type) { case UsfmTokenType.Chapter: if (chapter != null && verse != null) { string text = sb.ToString(); foreach (TextSegment seg in CreateTextSegments(includeText, chapter, verse, text, sentenceStart)) { yield return seg; } sentenceStart = true; sb.Clear(); } chapter = token.Text; verse = null; break; case UsfmTokenType.Verse: if (chapter != null && verse != null) { if (token.Text == verse) { string text = sb.ToString(); foreach (TextSegment seg in CreateTextSegments(includeText, chapter, verse, text, sentenceStart)) { yield return seg; } sentenceStart = text.HasSentenceEnding(); sb.Clear(); // ignore duplicate verse verse = null; } else if (VerseRef.AreOverlappingVersesRanges(token.Text, verse)) { // merge overlapping verse ranges in to one range verse = CorporaHelpers.MergeVerseRanges(token.Text, verse); } else { string text = sb.ToString(); foreach (TextSegment seg in CreateTextSegments(includeText, chapter, verse, text, sentenceStart)) { yield return seg; } sentenceStart = text.HasSentenceEnding(); sb.Clear(); verse = token.Text; } } else { verse = token.Text; } isVersePara = true; break; case UsfmTokenType.Paragraph: isVersePara = IsVersePara(token); break; case UsfmTokenType.Note: curEmbedMarker = token.Marker; if (chapter != null && verse != null && _includeMarkers) { if (prevToken?.Type == UsfmTokenType.Paragraph && IsVersePara(prevToken)) { sb.Append(prevToken); sb.Append(" "); } sb.Append(token); sb.Append(" "); } break; case UsfmTokenType.End: if (curEmbedMarker != null && token.Marker.Marker == curEmbedMarker.EndMarker) curEmbedMarker = null; if (curSpanMarker != null && token.Marker.Marker == curSpanMarker.EndMarker) curSpanMarker = null; if (isVersePara && chapter != null && verse != null && _includeMarkers) sb.Append(token); break; case UsfmTokenType.Character: if (SpanMarkers.Contains(token.Marker.Marker)) { curSpanMarker = token.Marker; } else if (token.Marker.Marker != "qac" && (token.Marker.TextType == UsfmTextType.Other || EmbedMarkers.Contains(token.Marker.Marker))) { curEmbedMarker = token.Marker; if (!_includeMarkers && token.Marker.Marker == "rq") sb.TrimEnd(); } if (isVersePara && chapter != null && verse != null && _includeMarkers) { if (prevToken?.Type == UsfmTokenType.Paragraph && IsVersePara(prevToken)) { sb.Append(prevToken); sb.Append(" "); } sb.Append(token); sb.Append(" "); } break; case UsfmTokenType.Text: if (isVersePara && chapter != null && verse != null && !string.IsNullOrEmpty(token.Text)) { if (_includeMarkers) { if (prevToken?.Type == UsfmTokenType.Paragraph && IsVersePara(prevToken)) { sb.Append(prevToken); sb.Append(" "); } sb.Append(token); } else if (curEmbedMarker == null) { string text = token.Text; if (curSpanMarker != null) { int index = text.IndexOf("|"); if (index >= 0) text = text.Substring(0, index); } if (prevToken?.Type == UsfmTokenType.End && (sb.Length == 0 || char.IsWhiteSpace(sb[sb.Length - 1]))) { text = text.TrimStart(); } sb.Append(text); } } break; } prevToken = token; } if (chapter != null && verse != null) { foreach (TextSegment seg in CreateTextSegments(includeText, chapter, verse, sb.ToString(), sentenceStart)) { yield return seg; } } } protected abstract IStreamContainer CreateStreamContainer(); private string ReadUsfm() { using (IStreamContainer streamContainer = CreateStreamContainer()) using (var reader = new StreamReader(streamContainer.OpenStream(), _encoding)) { return reader.ReadToEnd(); } } private static bool IsVersePara(UsfmToken paraToken) { string style = paraToken.Marker.Marker; if (NonVerseParaStyles.Contains(style)) return false; if (IsNumberedStyle("ms", style)) return false; if (IsNumberedStyle("s", style)) return false; return true; } private static bool IsNumberedStyle(string stylePrefix, string style) { return style.StartsWith(stylePrefix) && int.TryParse(style.Substring(stylePrefix.Length), out _); } } }
/* * Copyright (C) 2016-2020. Autumn Beauchesne. All rights reserved. * Author: Autumn Beauchesne * Date: 3 Apr 2017 * * File: Stats.cs * Purpose: Definition of relevant stats structures. */ using UnityEngine; namespace BeauRoutine.Internal { /// <summary> /// State of a Routine. /// </summary> public struct RoutineStats { public Routine Handle; public MonoBehaviour Host; public string State; public RoutinePhase Phase; public float TimeScale; public int Priority; public string Name; public string Function; public int StackDepth; public RoutineStats[] Nested; } /// <summary> /// Current status of a Routine. /// </summary> static public class RoutineState { public const string Running = "Running"; public const string Disposing = "Disposing"; public const string WaitTime = "Wait (Seconds)"; public const string WaitUnity = "Wait (Unity)"; public const string WaitFixedUpdate = "Wait (FixedUpdate)"; public const string WaitEndOfFrame = "Wait (EndOfFrame)"; public const string WaitLateUpdate = "Wait (LateUpdate)"; public const string WaitUpdate = "Wait (Update)"; public const string WaitThinkUpdate = "Wait (ThinkUpdate)"; public const string WaitCustomUpdate = "Wait (CustomUpdate)"; public const string WaitRealtimeUpdate = "Wait (RealtimeUpdate)"; public const string Locked = "Locked"; public const string Paused = "Paused"; } /// <summary> /// State of the BeauRoutine engine. /// </summary> public struct GlobalStats { public int Running; public int Max; public int Capacity; public float AvgMillisecs; public RoutineStats[] MaxSnapshot; } }
using Newtonsoft.Json; using RaiBlocks.Converters; using RaiBlocks.Interfaces; using RaiBlocks.ValueObjects; using System; namespace RaiBlocks.Results { public class AccountInformationResult : IActionResultWithError { [JsonProperty("frontier")] public string Frontier { get; set; } [JsonProperty("open_block")] public RaiBlock OpenBlock { get; set; } [JsonProperty("representative_block")] public RaiBlock RepresentativeBlock { get; set; } [JsonConverter(typeof(StringToRawConverter))] [JsonProperty("balance")] public RaiUnits.RaiRaw Balance { get; set; } [JsonConverter(typeof(TimeStampToDateConverter))] [JsonProperty("modified_timestamp")] public DateTime ModifiedTimestamp { get; set; } [JsonProperty("block_count")] public int BlockCount { get; set; } [JsonProperty("representative")] public RaiAddress Representative { get; set; } [JsonProperty("weight")] public string Weight { get; set; } [JsonConverter(typeof(StringToRawConverter))] [JsonProperty("pending")] public RaiUnits.RaiRaw Pending { get; set; } [JsonProperty("error")] public string Error { get; set; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Python.Runtime; using QuantConnect.Util; namespace QuantConnect.Tests.Common.Util { [TestFixture] public class PythonUtilTests { [Test] public void ConvertToSymbolsTest() { var expected = new List<Symbol> { Symbol.Create("AIG", SecurityType.Equity, Market.USA), Symbol.Create("BAC", SecurityType.Equity, Market.USA), Symbol.Create("IBM", SecurityType.Equity, Market.USA), Symbol.Create("GOOG", SecurityType.Equity, Market.USA) }; using (Py.GIL()) { // Test Python String var test1 = PythonUtil.ConvertToSymbols(new PyString("AIG")); Assert.IsTrue(typeof(List<Symbol>) == test1.GetType()); Assert.AreEqual(expected.FirstOrDefault(), test1.FirstOrDefault()); // Test Python List of Strings var list = (new List<string> {"AIG", "BAC", "IBM", "GOOG"}).ToPyList(); var test2 = PythonUtil.ConvertToSymbols(list); Assert.IsTrue(typeof(List<Symbol>) == test2.GetType()); Assert.IsTrue(test2.SequenceEqual(expected)); // Test Python Symbol var test3 = PythonUtil.ConvertToSymbols(expected.FirstOrDefault().ToPython()); Assert.IsTrue(typeof(List<Symbol>) == test3.GetType()); Assert.AreEqual(expected.FirstOrDefault(), test3.FirstOrDefault()); // Test Python List of Symbols var test4 = PythonUtil.ConvertToSymbols(expected.ToPyList()); Assert.IsTrue(typeof(List<Symbol>) == test4.GetType()); Assert.IsTrue(test4.SequenceEqual(expected)); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeshCreate : MonoBehaviour { public Vector3[] Vertices; public int[] Triangles; Mesh mesh; private void Start() { mesh = new Mesh(); GetComponent<MeshFilter>().mesh = mesh; } public void CreateMesh() { mesh.vertices = Vertices; mesh.triangles = Triangles; mesh.RecalculateNormals(); } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using AngleSharp.Dom; using Novinichka.Services.Helpers; namespace Novinichka.Services.NewsSources.Sources { public class CpdpBg : BaseSource { private const string Url = "index.php"; private const string UrlPaginationFragment = "?p=news_view&aid="; private const int CountOfNews = 5; private const int StartNews = 1; private const int EndNews = 2000; public override string BaseUrl { get; set; } = "https://www.cpdp.bg/"; public override IEnumerable<NewsModel> GetRecentNews() => GetNewsUrls($"{this.BaseUrl}{Url}{UrlPaginationFragment}") .Select(this.GetNews) .Where(x => x != null) .Take(CountOfNews) .ToList(); public override IEnumerable<NewsModel> GetAllNews() { for (var i = StartNews; i <= EndNews; i++) { var counter = 1; NewsModel news; try { news = this.GetNews($"{BaseUrl}{Url}{UrlPaginationFragment}{i}"); } catch (Exception e) { Console.WriteLine(e.Message); continue; } if (news is not null) { Console.WriteLine($"{counter++} => {news.OriginalUrl}"); yield return news; } } } private IEnumerable<string> GetNewsUrls(string url) { var webClient = new WebClient(); var html = webClient.DownloadString(url); var document = this.Parser .ParseDocument(html); var a = document .QuerySelectorAll("div.news-content h6 a") .Select(x => $"{this.BaseUrl}{x?.Attributes["href"]?.Value}") .ToList(); return document .QuerySelectorAll("div.news-content h6 a") .Select(x => $"{this.BaseUrl}{x?.Attributes["href"]?.Value}") .ToList(); } protected override NewsModel ParseDocument(IDocument document, string url) { var newsTitle = document .QuerySelector("div.center-part h1") ?.InnerHtml .Trim(); if (string.IsNullOrWhiteSpace(newsTitle) || newsTitle == "Новини") { return null; } var createdOnAsString = document .QuerySelector("div.date") ?.InnerHtml; if (createdOnAsString is null) { return null; } var createdOn = DateTime.ParseExact(createdOnAsString, "dd.MM.yyyy", CultureInfo.InvariantCulture); var content = document.QuerySelector(".center-part"); var imageElement = document?.QuerySelector("div.titleImage img"); var originalSourceId = newsTitle.Replace(' ','-').ToLower(); content.RemoveChildNodes(imageElement); content.RemoveGivenTag("img"); content.RemoveElement("div.path"); content.RemoveElement("h1"); content.RemoveElement("div.date"); string image = null; if (imageElement is not null) { image = this.BaseUrl.Remove(this.BaseUrl.Length - 1, 1) + imageElement?.GetAttribute("src"); } return new NewsModel(newsTitle, content?.InnerHtml.Trim(), createdOn, image, url, originalSourceId); } } }
using System; using System.Collections.Generic; using System.Text; namespace ChatCore.Interfaces { public interface IChatResourceData { public string Uri { get; } public bool IsAnimated { get; } public string Type { get; } } }
using static TACTLib.Core.Product.Tank.ManifestCryptoHandler; using static TACTLib.Core.Product.Tank.ContentManifestFile; namespace TACTLib.Core.Product.Tank.CMF { [ManifestCryptoAttribute(AutoDetectVersion = true, Product = TACTProduct.Overwatch)] public class ProCMF_54255 : ICMFEncryptionProc { public byte[] Key(CMFHeader header, int length) { byte[] buffer = new byte[length]; uint kidx = Keytable[header.m_buildVersion & 511]; for (int i = 0; i != length; ++i) { buffer[i] = Keytable[SignedMod(kidx, 512)]; switch (SignedMod(kidx, 3)) { case 0: kidx += 103; break; case 1: kidx = (uint)SignedMod(4 * kidx, header.m_buildVersion); break; case 2: --kidx; break; } } return buffer; } public byte[] IV(CMFHeader header, byte[] digest, int length) { byte[] buffer = new byte[length]; uint kidx = (uint) (2 * digest[5]); for (int i = 0; i != length; ++i) { buffer[i] = Keytable[SignedMod(kidx, 512)]; kidx = header.m_buildVersion - kidx; buffer[i] ^= digest[SignedMod(i + kidx, SHA1_DIGESTSIZE)]; } return buffer; } private static readonly byte[] Keytable = { 0x1D, 0x02, 0xFF, 0xF4, 0x74, 0x36, 0xA3, 0xCB, 0x39, 0x11, 0x04, 0xDD, 0xA1, 0xFD, 0xA6, 0xD6, 0x5B, 0xBB, 0x45, 0x69, 0x5F, 0x3E, 0xBA, 0x2A, 0xC9, 0xAF, 0xF6, 0x34, 0x1A, 0x78, 0xA1, 0x36, 0x8D, 0xBE, 0xEE, 0x94, 0xE0, 0x49, 0xCC, 0x3C, 0xD3, 0xAD, 0x0F, 0x1F, 0x9D, 0x41, 0x28, 0xD5, 0xD4, 0xB6, 0x09, 0x53, 0xDD, 0xC5, 0xE1, 0x04, 0x53, 0x8D, 0x13, 0xBD, 0xBB, 0x2E, 0x56, 0xE0, 0x67, 0xE1, 0x26, 0x1C, 0xEC, 0x90, 0x12, 0x40, 0x2E, 0xAD, 0x45, 0x52, 0x98, 0xC4, 0x91, 0x9B, 0xF7, 0xA1, 0x9E, 0x8A, 0x8F, 0x7D, 0x83, 0x78, 0xED, 0x45, 0x02, 0xCF, 0x94, 0xF9, 0x7F, 0xC1, 0xC2, 0x41, 0x14, 0x52, 0x10, 0xB0, 0x0F, 0xA9, 0x49, 0xE1, 0xE3, 0xFD, 0xE3, 0xFC, 0xE4, 0x49, 0x55, 0x64, 0xD8, 0x83, 0xEE, 0xD1, 0x03, 0x7B, 0x8C, 0x32, 0xFE, 0x21, 0xB9, 0xCE, 0xF7, 0xEC, 0x72, 0x67, 0x25, 0xD5, 0x51, 0x70, 0x26, 0xBA, 0x9D, 0x85, 0x30, 0x14, 0xE6, 0xC7, 0x57, 0x15, 0xDA, 0x2A, 0xEA, 0xD7, 0x55, 0xDC, 0xAB, 0xB7, 0x50, 0xAD, 0xD9, 0x2B, 0xFD, 0x3E, 0xF3, 0xAC, 0xB8, 0xBD, 0x2F, 0xB4, 0xA6, 0xC9, 0x4A, 0x7D, 0x63, 0x4F, 0x70, 0xA0, 0xC1, 0x64, 0x85, 0x18, 0x71, 0x99, 0x89, 0xDE, 0x97, 0x87, 0xA3, 0x09, 0x66, 0xA2, 0xF1, 0x76, 0x22, 0x95, 0x03, 0xBC, 0x09, 0xBB, 0xFE, 0x72, 0x61, 0x85, 0x0C, 0x97, 0x55, 0xD3, 0x07, 0x3A, 0x5C, 0x57, 0xB6, 0xD1, 0xE0, 0xEF, 0x76, 0x3D, 0x74, 0x18, 0xBA, 0x37, 0x94, 0x03, 0xCE, 0x97, 0xDE, 0xEB, 0xB9, 0x34, 0x90, 0x2A, 0x13, 0x11, 0xE0, 0xC8, 0x7C, 0x5D, 0xF7, 0xBE, 0xB2, 0x22, 0x7E, 0xBA, 0x08, 0xB2, 0xF7, 0xEC, 0x9B, 0x2E, 0x01, 0xBC, 0x56, 0xA7, 0x84, 0x52, 0x34, 0x06, 0xC6, 0x73, 0x2B, 0xF0, 0x5B, 0xB5, 0xEB, 0xC1, 0x43, 0x5E, 0x8F, 0xB4, 0x0E, 0x06, 0x4D, 0x9C, 0x42, 0xE4, 0x87, 0x0F, 0x8B, 0x7C, 0x8E, 0x8F, 0xCD, 0xA6, 0x98, 0xBD, 0x85, 0xD8, 0x92, 0xB4, 0x90, 0x1C, 0x95, 0xE0, 0x4B, 0x87, 0xC6, 0xE6, 0x8C, 0xD1, 0x0B, 0xB7, 0x86, 0x33, 0x31, 0xD4, 0x30, 0x91, 0x06, 0xC6, 0xA2, 0x9E, 0x06, 0xD3, 0xE5, 0x4D, 0x66, 0x51, 0x71, 0xDF, 0x21, 0x20, 0x90, 0x2C, 0x76, 0xDA, 0x71, 0x50, 0xFD, 0x71, 0xA0, 0x44, 0x4E, 0xAB, 0x3B, 0x93, 0x72, 0xA1, 0x4F, 0xF5, 0xB1, 0xEF, 0x78, 0x63, 0x1D, 0x13, 0xBA, 0x76, 0x03, 0x42, 0x67, 0x2C, 0x32, 0xB9, 0xFB, 0x06, 0x9B, 0x50, 0x26, 0x21, 0xF6, 0x9A, 0xC9, 0x0A, 0x9A, 0x30, 0xCA, 0x0A, 0x5D, 0x1E, 0x8F, 0x58, 0x29, 0x81, 0x2E, 0x60, 0xD0, 0xF5, 0x65, 0x55, 0xE6, 0xDC, 0x74, 0x56, 0x8B, 0x81, 0x45, 0x37, 0x0F, 0x0D, 0x6B, 0xDF, 0x15, 0xDF, 0xD7, 0x38, 0x71, 0xD2, 0x16, 0xC1, 0x40, 0x2D, 0xCD, 0xB7, 0x1B, 0x7C, 0xBB, 0x5B, 0x50, 0x1B, 0xE9, 0xE0, 0xE3, 0xF2, 0xED, 0x25, 0xB4, 0x18, 0x03, 0xF3, 0x93, 0x70, 0x8F, 0x06, 0x72, 0x82, 0xA5, 0xE8, 0x63, 0x9C, 0x6E, 0x1D, 0x87, 0x3D, 0x1F, 0x05, 0xBD, 0x72, 0x98, 0x47, 0xD3, 0x55, 0xB2, 0xDC, 0xFC, 0xF7, 0x20, 0x65, 0x66, 0xC3, 0xD2, 0x11, 0x8C, 0xD8, 0x51, 0xDC, 0x35, 0xA9, 0xFA, 0x6D, 0x42, 0xF1, 0xCB, 0xE6, 0x90, 0x68, 0x4B, 0xA0, 0xCB, 0xA8, 0x2B, 0x18, 0x09, 0x4F, 0xF4, 0x2E, 0x3A, 0xB3, 0x60, 0xCF, 0xB7, 0xF1, 0x0F, 0x99, 0xE5, 0x08, 0x65, 0x69, 0x5D, 0x81, 0xD1, 0x49, 0x87, 0x52, 0xFD, 0x7E, 0x98, 0xC7, 0x54, 0x33, 0x52, 0xA4, 0xF7, 0x8D, 0xDF, 0x0A, 0x29, 0xFC, 0x90, 0xC4, 0x82, 0x73, 0xB4, 0xCA, 0xD4, 0x05, 0xC3, 0x78 }; } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using BenchmarkDotNet.Attributes; using NodaTime.Calendars; namespace NodaTime.Benchmarks.NodaTimeTests { public class UtcZonedDateTimeBenchmarks { private static readonly LocalDateTime SampleLocal = new LocalDateTime(2009, 12, 26, 10, 8, 30); private static readonly ZonedDateTime Sample = DateTimeZone.Utc.AtStrictly(SampleLocal); [Benchmark] public void Construction() { DateTimeZone.Utc.AtStrictly(SampleLocal); } [Benchmark] public int Year() => Sample.Year; [Benchmark] public int Month() => Sample.Month; [Benchmark] public int DayOfMonth() => Sample.Day; [Benchmark] public IsoDayOfWeek DayOfWeek() => Sample.DayOfWeek; [Benchmark] public int DayOfYear() => Sample.DayOfYear; [Benchmark] public int Hour() => Sample.Hour; [Benchmark] public int Minute() => Sample.Minute; [Benchmark] public int Second() => Sample.Second; [Benchmark] public int Millisecond() => Sample.Millisecond; [Benchmark] public long TickOfDay() => Sample.TickOfDay; [Benchmark] public int TickOfSecond() => Sample.TickOfSecond; [Benchmark] public int ClockHourOfHalfDay() => Sample.ClockHourOfHalfDay; [Benchmark] public Era Era() => Sample.Era; [Benchmark] public int YearOfEra() => Sample.YearOfEra; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace brovador.GBEmulator { public class GPU { public const int SCREEN_PIXELS_WIDTH = 160; public const int SCREEN_PIXELS_HEIGHT = 144; const int HORIZONAL_BLANK_CYCLES = 204; const int VERTICAL_BLANK_CYCLES = 456; const int SCANLINE_OAM_CYCLES = 80; const int SCANLINE_VRAM_CYCLES = 172; const int TOTAL_TILES = 512; enum GPUMode { HBlank, VBlank, OAMRead, VRAMRead } public enum SpriteSize { Size8x8, Size8x16 } MMU mmu; //FF40(LCDC) public int LCDC_BGTileMap { get { return (mmu.Read(0xFF40) & 0x08) == 0 ? 0 : 1; } } public int LCDC_WindowTileMap { get { return (mmu.Read(0xFF40) & 0x40) == 0 ? 0 : 1; } } public int LCDC_BGWindowTileData { get { return (mmu.Read(0xFF40) & 0x10) == 0 ? 0 : 1; } } public bool LCDC_WindowDisplay { get { return (mmu.Read(0xFF40) & 0x20) == 0 ? false : true; } } public bool LCDC_SpriteDisplay { get { return (mmu.Read(0xFF40) & 0x02) == 0 ? false : true; } } public bool LCDC_BGWindowDisplay { get { return (mmu.Read(0xFF40) & 0x01) == 0 ? false : true; } } public SpriteSize LCDC_SpriteSize { get { return (SpriteSize)(mmu.Read(0xFF40) & 0x04); } } //FF41(STAT) bool STAT_InterruptLYCEnabled { get { return (mmu.Read((ushort)0xFF41) & 0x40) != 0; }} bool STAT_InterruptOAMEnabled { get { return (mmu.Read((ushort)0xFF41) & 0x20) != 0; }} bool STAT_InterruptVBlankEnabled { get { return (mmu.Read((ushort)0xFF41) & 0x10) != 0; }} bool STAT_InterruptHBlankEnabled { get { return (mmu.Read((ushort)0xFF41) & 0x08) != 0; }} bool STAT_CoincidenceFlag { get { return (mmu.Read((ushort)0xFF41) & 0x04) != 0; } set { var data = mmu.Read((ushort)0xFF41); mmu.Write((ushort)0xFF41, (byte)((data & ~0x04) | (value ? 0x04 : 0x00))); } } GPUMode STAT_Mode { get { return (GPUMode)(mmu.Read((ushort)0xFF41) & 0x03); } set { mmu.Write(0xFF41, (byte)((mmu.Read(0xFF41) & ~0x03) + (byte)value)); CheckLCDInterrupts(); } } //FF42(SCY) byte SCY { get { return mmu.Read(0xFF42); } } //FF43(SCX) byte SCX { get { return mmu.Read(0xFF43); } } //FF44(LY) byte LY { get { return mmu.Read(0xFF44); } set { mmu.Write(0xFF44, value, true); STAT_CoincidenceFlag = (value == this.LYC); if (STAT_CoincidenceFlag && STAT_InterruptLYCEnabled) { mmu.SetInterrupt(MMU.InterruptType.LCDCStatus); } } } //FF45(LYC) byte LYC { get { return mmu.Read(0xFF45); } } //FF46(DMA) byte DMA { get { return mmu.Read(0xFF46); } } //FF47(BGP) byte BGP { get { return mmu.Read(0xFF47); } } //FF48(OBP0) byte OBP0 { get { return mmu.Read(0xFF48); } } //FF49(OBP1) byte OBP1 { get { return mmu.Read(0xFF49); } } //FF4A(WY) byte WY { get { return mmu.Read(0xFF4A); } } //FF4B(WX) byte WX { get { return mmu.Read(0xFF4B); } } uint clock; Color[] buffer; public Texture2D screenTexture { get; private set; } public GPU(MMU mmu) { this.mmu = mmu; this.mmu.OnMemoryWritten += (MMU m, ushort addr) => { if (addr >= 0x8000 && addr <= 0x97FF) { UpdateTile(addr); } else if (addr == 0xFF46) { OAMTransfer(); } }; STAT_Mode = GPUMode.HBlank; LY = 0; clock = 0; buffer = new Color[SCREEN_PIXELS_WIDTH * SCREEN_PIXELS_HEIGHT]; screenTexture = new Texture2D(SCREEN_PIXELS_WIDTH, SCREEN_PIXELS_HEIGHT, TextureFormat.ARGB32, false); screenTexture.filterMode = FilterMode.Point; } public void Step(uint opCycles) { clock += opCycles; switch (STAT_Mode) { //OAM Read case GPUMode.OAMRead: if (clock >= SCANLINE_OAM_CYCLES) { clock -= SCANLINE_OAM_CYCLES; STAT_Mode = GPUMode.VRAMRead; } break; //VRAM Read case GPUMode.VRAMRead: if (clock >= SCANLINE_VRAM_CYCLES) { clock -= SCANLINE_VRAM_CYCLES; STAT_Mode = GPUMode.HBlank; DrawScanline(); } break; //HBlank case GPUMode.HBlank: if (clock >= HORIZONAL_BLANK_CYCLES) { clock -= HORIZONAL_BLANK_CYCLES; LY++; if (LY == (SCREEN_PIXELS_HEIGHT - 1)) { STAT_Mode = GPUMode.VBlank; mmu.SetInterrupt(MMU.InterruptType.VBlank); DrawScreen(); } else { STAT_Mode = GPUMode.OAMRead; } } break; //VBlank case GPUMode.VBlank: if (clock >= VERTICAL_BLANK_CYCLES) { clock -= VERTICAL_BLANK_CYCLES; LY++; if (LY > 153) { STAT_Mode = GPUMode.OAMRead; LY = 0; } } break; } } void CheckLCDInterrupts() { bool setInterrupt = false; setInterrupt = setInterrupt || (STAT_Mode == GPUMode.HBlank && STAT_InterruptHBlankEnabled); setInterrupt = setInterrupt || (STAT_Mode == GPUMode.VBlank && STAT_InterruptVBlankEnabled); setInterrupt = setInterrupt || (STAT_Mode == GPUMode.OAMRead && STAT_InterruptOAMEnabled); if (setInterrupt) { mmu.SetInterrupt(MMU.InterruptType.LCDCStatus); } } void DrawScanline() { //VRAM size is 32x32 tiles, 1 byte per tile byte ly = LY; var lineY = ly + SCY; var lineX = SCX; var bufferY = (SCREEN_PIXELS_WIDTH * SCREEN_PIXELS_HEIGHT - (ly * SCREEN_PIXELS_WIDTH)) - SCREEN_PIXELS_WIDTH; if (LCDC_BGWindowDisplay) { var tileMapAddressOffset = LCDC_BGTileMap == 0 ? 0x9800 : 0x9C00; var tileMapX = 0; var tileMapY = 0; var tileX = 0; var tileY = 0; var nTile = 0; int[] tile = null; for (int i = 0; i < SCREEN_PIXELS_WIDTH; i++) { if (i == 0 || (lineX & 7) == 0) { tileMapY = (int)((lineY >> 3) & 31); tileMapX = (int)((lineX >> 3) & 31); nTile = mmu.Read((ushort)(tileMapAddressOffset + (tileMapY << 5) + tileMapX)); if (LCDC_BGWindowTileData == 0) { if (nTile > 127) { nTile -= 0x100; } nTile = 256 + nTile; } if (!tiles.ContainsKey((uint)(nTile))) { continue; } tile = tiles[(uint)nTile]; } if (tile == null) { continue; } tileY = (int)(lineY & 7); tileX = (int)(lineX & 7); buffer[bufferY + i] = ColorForPalette(BGP, tile[(tileY << 3) + tileX]); lineX++; } } if (LCDC_SpriteDisplay) { var oamAddress = 0xFE00; int xPosition = 0; int yPosition = 0; byte n = 0; byte flags = 0; byte palette = 0; bool xFlip = false; bool yFlip = false; int priority = 0; int spriteRow = 0; int pixelColor = 0; for (int i = 0; i < 40; i++) { yPosition = mmu.Read((ushort)(oamAddress + i * 4)) - 16; xPosition = mmu.Read((ushort)(oamAddress + i * 4 + 1)) - 8; n = mmu.Read((ushort)(oamAddress + i * 4 + 2)); flags = mmu.Read((ushort)(oamAddress + i * 4 + 3)); var maxSprites = LCDC_SpriteSize == SpriteSize.Size8x8 ? 1 : 2; for (int j = 0; j < maxSprites; j++) { n = (byte)(n + j); yPosition = yPosition + 8 * j; if (!tiles.ContainsKey((uint)n)) { continue; } if (ly >= yPosition && yPosition + 8 > ly) { palette = (flags & 0x10) == 0 ? OBP0 : OBP1; xFlip = (flags & 0x20) == 0 ? false : true; yFlip = (flags & 0x40) == 0 ? false : true; priority = (flags & 0x80) == 0 ? 0 : 1; spriteRow = (ly - yPosition); if (yFlip) { spriteRow = 7 - spriteRow; } for (int x = 0; x < 8; x++) { var xCoordSprite = xFlip ? 7 - x : x; var xCoordBuffer = bufferY + xPosition + x; pixelColor = tiles[(uint)n][spriteRow * 8 + xCoordSprite]; if (((xPosition + xCoordSprite) >= 0) && ((xPosition + xCoordSprite) < SCREEN_PIXELS_WIDTH) && pixelColor != 0 && (priority == 0 || buffer[xCoordBuffer] == colors[0])) { buffer[xCoordBuffer] = ColorForPalette(palette, pixelColor); } } } } } } var wx = WX - 7; var wy = WY; lineY = ly; lineX = 0; if (LCDC_WindowDisplay && ly >= wy) { var tileMapAddressOffset = LCDC_WindowTileMap == 0 ? 0x9800 : 0x9C00; var tileMapX = 0; var tileMapY = 0; var tileX = 0; var tileY = 0; var nTile = 0; int[] tile = null; for (int i = wx; i < SCREEN_PIXELS_WIDTH; i++) { if (((i - wx) & 7) == 0) { tileMapY = (int)(((ly - wy) >> 3) & 31); tileMapX = (int)(((i - wx) >> 3) & 31); nTile = mmu.Read((ushort)(tileMapAddressOffset + (tileMapY << 5) + tileMapX)); if (LCDC_BGWindowTileData == 0) { if (nTile > 127) { nTile -= 0x100; } nTile = 256 + nTile; } if (!tiles.ContainsKey((uint)(nTile))) { continue; } tile = tiles[(uint)nTile]; } if (tile == null) { continue; } tileY = (int)(lineY & 7); tileX = (int)(lineX & 7); buffer[bufferY + i] = ColorForPalette(BGP, tile[(tileY << 3) + tileX]); lineX++; } } } void DrawScreen() { screenTexture.SetPixels(0, 0, SCREEN_PIXELS_WIDTH, SCREEN_PIXELS_HEIGHT, buffer); screenTexture.Apply(); } Color[] colors = { new Color(224.0f / 255.0f, 248.0f / 255.0f, 208.0f / 255.0f), new Color(136.0f / 255.0f, 192.0f / 255.0f, 112.0f / 255.0f), new Color(52.0f / 255.0f, 104.0f / 255.0f, 86.0f / 255.0f), new Color(8.0f / 255.0f, 24.0f / 255.0f, 32.0f / 255.0f) }; Color ColorForPalette(byte palette, int colorIdx) { return colors[((palette & (0x03 << (colorIdx * 2))) >> (colorIdx * 2))]; } Dictionary<uint, int[]> tiles = new Dictionary<uint, int[]>(); void UpdateTile(uint addr) { var n = (addr - 0x8000) / 16; var tileBaseAddress = 0x8000 + n * 16; var tileRow = (addr - tileBaseAddress) / 2; var tileRowAddr = tileBaseAddress + tileRow * 2; if (!tiles.ContainsKey(n)) { tiles[n] = new int[8 * 8]; } byte b1 = mmu.Read((ushort)(tileRowAddr)); byte b2 = mmu.Read((ushort)(tileRowAddr + 1)); int[] tile = tiles[n]; tile[tileRow * 8] = (int)((b1 & 0x80) >> 7) + (int)((b2 & 0x80) >> 6); tile[tileRow * 8 + 1] = (int)((b1 & 0x40) >> 6) + (int)((b2 & 0x40) >> 5); tile[tileRow * 8 + 2] = (int)((b1 & 0x20) >> 5) + (int)((b2 & 0x20) >> 4); tile[tileRow * 8 + 3] = (int)((b1 & 0x10) >> 4) + (int)((b2 & 0x10) >> 3); tile[tileRow * 8 + 4] = (int)((b1 & 0x08) >> 3) + (int)((b2 & 0x08) >> 2); tile[tileRow * 8 + 5] = (int)((b1 & 0x04) >> 2) + (int)((b2 & 0x04) >> 1); tile[tileRow * 8 + 6] = (int)((b1 & 0x02) >> 1) + (int)((b2 & 0x02)); tile[tileRow * 8 + 7] = (int)((b1 & 0x01)) + (int)((b2 & 0x01) << 1); } void OAMTransfer() { var addr = (ushort)(DMA << 8); for (int i = 0; i < 40 * 4; i++) { mmu.Write((ushort)(0xFE00 + i), mmu.Read((ushort)(addr + i))); } } } }
namespace Tabular { public partial class TabularMainForm : DevExpress.XtraEditors.XtraForm { public TabularMainForm() { InitializeComponent(); var x = new TableForm { MdiParent = this }; x.Show(); } } }
/* Mixins */ /* bg shortcodes */ .bg-gradient1 span, .bg-gradient1:before { background: #fa7e29; background: linear-gradient(180deg, #fa7e29 0%, #F6682F 80%, #F6682F 100%); } .bg-gradient2 span, .bg-gradient2:before { background: #39C2C9; background: linear-gradient(180deg, #39C2C9 0%, #3FC8C9 80%, #3FC8C9 100%); } .pop-onhover.bg-gradient3 span, .pop-onhover.bg-gradient3:before { background: #B9AEF0; background: linear-gradient(180deg, #B9AEF0 0%, #ADA1EB 80%, #ADA1EB 100%); } .bg-gradient4 span { background: #F6682F; background: linear-gradient(180deg, #F6682F 0%, #F6682F 80%, #F6682F 100%); } /* General */ .wrapper { margin: 4% auto; text-align: center; } h3 { color: #666a73; font-weight: 300; letter-spacing: 0.06em; } a { text-decoration: none; } a:hover, a:focus, a:active { text-decoration: none; } /* fancy Button */ .fancy-button { display: inline-block; margin: 20px; font-family: 'Heebo', Helvetica, Arial, sans-serif; font-weight: 500; font-size: 16px; letter-spacing: 0.07em; text-transform: uppercase; line-height: 24px; color: #ffffff; position: relative; } .fancy-button.bg-gradient1 { text-shadow: 0px 0px 1px #BF4C28; } .fancy-button.bg-gradient2 { text-shadow: 0px 0px 1px #227270; } .fancy-button.bg-gradient3 { text-shadow: 0 0 1px #546082; } .fancy-button:before { content: ''; display: inline-block; height: 40px; position: absolute; bottom: -1px; left: 10px; right: 10px; z-index: -1; border-radius: 2em; -webkit-filter: blur(14px) brightness(0.9); filter: blur(14px) brightness(0.9); -webkit-transform-style: preserve-3d; transform-style: preserve-3d; transition: all 0.3s ease-out; } .fancy-button i { margin-top: -2px; font-size: 1.265em; vertical-align: middle; } .fancy-button span { display: inline-block; padding: 16px 20px; border-radius: 50em; position: relative; z-index: 2; will-change: transform, filter; -webkit-transform-style: preserve-3d; transform-style: preserve-3d; transition: all 0.3s ease-out; } .fancy-button:focus { color: #ffffff; } .fancy-button:hover { color: #ffffff; } .fancy-button:hover span { -webkit-filter: brightness(0.9) contrast(1.2); filter: brightness(0.9) contrast(1.2); -webkit-transform: scale(0.96); transform: scale(0.96); } .fancy-button:hover:before { bottom: 3px; -webkit-filter: blur(6px) brightness(0.8); filter: blur(6px) brightness(0.8); } .fancy-button:active span { -webkit-filter: brightness(0.75) contrast(1.7); filter: brightness(0.75) contrast(1.7); } .fancy-button.pop-onhover span { border-radius: 4px; } .fancy-button.pop-onhover:before { opacity: 0; bottom: 10px; } .fancy-button.pop-onhover:hover:before { bottom: -7px; opacity: 1; -webkit-filter: blur(16px); filter: blur(16px); } .fancy-button.pop-onhover:hover span { -webkit-transform: scale(1); transform: scale(1); } .fancy-button.pop-onhover:hover:active span { -webkit-filter: brightness(1) contrast(1); filter: brightness(1) contrast(1); -webkit-transform: scale(1); transform: scale(1); transition: all 0.2s ease-out; } .fancy-button.pop-onhover:hover:active:before { bottom: 0; -webkit-filter: blur(5px) brightness(0.85); filter: blur(5px) brightness(0.85); transition: all 0.2s ease-out; } .pop-onhover.bg-gradient3 span:hover { background: #B9AEF0; background: linear-gradient(120deg, #B9AEF0 0%, #ADA1EB 80%, #ADA1EB 100%); } .bg-gradient4:before { bottom: 2px; opacity: 0.6; transition: all 0.3s ease-out; } .bg-gradient4 { transition: all 1s ease; } .bg-gradient4 span { outline: 0px solid transparent; } .bg-gradient4:hover span { background: #FC3D7C; background: linear-gradient(-25deg, #FC3D7C 0%, #F76A34 80%, #F76A34 100%); } .bg-gradient4:focus span, .bg-gradient4:active span { background: #FC3D7C; background: linear-gradient(25deg, #FC3D7C 0%, #F76A34 80%, #F76A34 100%); } .bg-gradient4:focus span { box-shadow: 0 0 9px #00FFF8; } .bg-gradient4:active span { -webkit-filter: brightness(0.85) contrast(1.3); filter: brightness(0.85) contrast(1.3); } .bg-gradient4 span { text-transform: capitalize; }
namespace Litium.Accelerator.Constants { internal static class MegaMenuPageFieldNameConstants { public const string MegaMenuCategory = "MegaMenuCategory"; public const string MegaMenuPage = "MegaMenuPage"; public const string MegaMenuShowContent = "MegaMenuShowContent"; public const string MegaMenuShowSubCategories = "MegaMenuShowSubCategories"; public const string MegaMenuColumn = "MegaMenuColumn"; public const string MegaMenuColumnHeader = "MegaMenuColumnHeader"; public const string MegaMenuCategories = "MegaMenuCategories"; public const string MegaMenuPages = "MegaMenuPages"; public const string MegaMenuFilters = "MegaMenuFilters"; public const string MegaMenuEditor = "MegaMenuEditor"; public const string MegaMenuAdditionalLink = "MegaMenuAdditionalLink"; public const string MegaMenuLinkToCategory = "MegaMenuLinkToCategory"; public const string MegaMenuLinkToPage = "MegaMenuLinkToPage"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MinotaurEnabler : MonoBehaviour { [SerializeField] public GameObject Minotaur; // Start is called before the first frame update void Start() { } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.transform.root.gameObject.CompareTag("Player")) { Minotaur.GetComponent<SpriteRenderer>().enabled = true; Minotaur.GetComponent<Animator>().enabled = true; Minotaur.GetComponent<BoxCollider2D>().enabled = true; Minotaur.transform.Find("Body_Container/Body").gameObject.GetComponent<SpriteRenderer>().enabled = true; Minotaur.transform.Find("Minotaur_Expression").gameObject.GetComponent<Animator>().enabled = true; Minotaur.transform.Find("Minotaur_Expression/1").gameObject.GetComponent<SpriteRenderer>().enabled = true; Minotaur.transform.Find("Minotaur_Expression/2").gameObject.GetComponent<SpriteRenderer>().enabled = true; Minotaur.transform.Find("Minotaur_Expression/3").gameObject.GetComponent<SpriteRenderer>().enabled = true; Destroy(this.gameObject); } } }
using System.Threading.Tasks; namespace ExamQuestions.Tests.Events { public interface IMailManager { Task SimulateMail(NewEmailEventArgs args); } }
using Domain.Events.Readers; using Domain.ValueObjects; using Framework; using System; using System.Collections.Generic; using System.Text; namespace Domain { public class BookReader : AggregateRoot<BookReaderGuid> { public Guid BookReaderId { get; set; } public Name200 Name { get; set; } public BookReader() { } public BookReader(string name) { Apply(new ReaderCreated() { BookReaderId = Guid.NewGuid(), Name = name }); } public void SetId() { this.Id = this.BookReaderId; } protected override void ValidateStatus() { ; } protected override void When(object @event) { switch(@event) { case Domain.Events.Readers.ReaderCreated e: Id = new BookReaderGuid(e.BookReaderId); ; BookReaderId = Id.Value; Name = Name200.FromString(e.Name); break; } } } }
namespace Bridge { public abstract class StrategyClassA : DegreeOfFreedom { } }
using iHRS.Domain.Models; namespace iHRS.Infrastructure.EntityConfigurations { internal class MessageTypeConfiguration : BaseEnumerationConfiguration<MessageType> { public override string TableName => "MessageTypes"; public override string PrimaryKeyColumnName => "MessageTypeId"; } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace InHouse.Application.Common.Exceptions { [ExcludeFromCodeCoverage] public class InHouseNotFoundException : Exception { /// <summary> /// Initializes a new instance of the <see cref="NotFoundException"/> class. /// </summary> /// <param name="message">The message<see cref="string"/>.</param> public InHouseNotFoundException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="NotFoundException"/> class. /// </summary> /// <param name="message">The message<see cref="string"/>.</param> /// <param name="innerException">The innerException<see cref="Exception"/>.</param> public InHouseNotFoundException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="NotFoundException"/> class. /// </summary> /// <param name="name">The name<see cref="string"/>.</param> /// <param name="key">The key<see cref="object"/>.</param> public InHouseNotFoundException(string name, object key) : base($"Entity \"{name}\" ({key}) was not found.") { } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace Service.DwhExternalBalances.DataBase.DesignTime { public class ContextFactory: IDesignTimeDbContextFactory<DwhContext> { public ContextFactory() { } public DwhContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<DwhContext>(); optionsBuilder.UseSqlServer(); //optionsBuilder.UseNpgsql(connString); return new DwhContext(optionsBuilder.Options); } } }
using LINGYUN.Abp.IM.Contract; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; namespace LINGYUN.Abp.MessageService.Chat { public interface IUserChatFriendRepository : IBasicRepository<UserChatFriend, long> { Task<bool> IsFriendAsync( Guid userId, Guid frientId, CancellationToken cancellationToken = default); Task<bool> IsAddedAsync( Guid userId, Guid frientId, CancellationToken cancellationToken = default); Task<UserChatFriend> FindByUserFriendIdAsync( Guid userId, Guid friendId, CancellationToken cancellationToken = default); Task<List<UserFriend>> GetAllMembersAsync( Guid userId, string sorting = nameof(UserChatFriend.RemarkName), CancellationToken cancellationToken = default); Task<int> GetMembersCountAsync( Guid userId, string filter = "", CancellationToken cancellationToken = default); Task<List<UserFriend>> GetMembersAsync( Guid userId, string filter = "", string sorting = nameof(UserChatFriend.UserId), int skipCount = 0, int maxResultCount = 10, CancellationToken cancellationToken = default); Task<List<UserFriend>> GetLastContactMembersAsync( Guid userId, int skipCount = 0, int maxResultCount = 10, CancellationToken cancellationToken = default); Task<UserFriend> GetMemberAsync( Guid userId, Guid friendId, CancellationToken cancellationToken = default); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GPS : MonoBehaviour{ public static GPS Instance {set; get;} public float latitude; public float longitude; public float heading; private float timeUpdate; public float myx; public float myy; public float myz; public float objx; public float objy; public float objz; private void Start(){ timeUpdate = Time.fixedTime + 0.5f; Instance = this; DontDestroyOnLoad(gameObject); StartCoroutine(StartLocationService()); } private IEnumerator StartLocationService(){ if(!Input.location.isEnabledByUser){ UnityEngine.Debug.Log("GPS services not currently enabled"); yield break; } Input.compass.enabled = true; Input.location.Start(); int timeToOut = 30; while(Input.location.status == LocationServiceStatus.Initializing && timeToOut > 0){ yield return new WaitForSeconds(1); timeToOut--; } if(timeToOut<=0){ UnityEngine.Debug.Log("GPS Initializing Timed Out"); yield break; } if(Input.location.status == LocationServiceStatus.Failed){ UnityEngine.Debug.Log("Unable to ascertain location"); yield break; } yield break; } private void FixedUpdate(){ if(Time.fixedTime >= timeUpdate){ latitude = Input.location.lastData.latitude; longitude = Input.location.lastData.longitude; heading = Input.compass.trueHeading; myx = Input.acceleration.x; myy = Input.acceleration.y; myz = Input.acceleration.z; timeUpdate = Time.fixedTime + 0.5f; } } }
using Symbolica.Abstraction; namespace Symbolica.Representation.Functions; internal sealed class FunnelShiftLeft : IFunction { public FunnelShiftLeft(FunctionId id, IParameters parameters) { Id = id; Parameters = parameters; } public FunctionId Id { get; } public IParameters Parameters { get; } public void Call(IState state, ICaller caller, IArguments arguments) { var high = arguments.Get(0); var low = arguments.Get(1); var shift = arguments.Get(2); var size = state.Space.CreateConstant(shift.Size, (uint) shift.Size); var offset = shift.UnsignedRemainder(size); var result = high.ShiftLeft(offset) .Or(low.LogicalShiftRight(size.Subtract(offset))); state.Stack.SetVariable(caller.Id, result); } }
namespace Tzkt.Sync.Protocols.Proto12 { class StateCommit : Proto1.StateCommit { public StateCommit(ProtocolHandler protocol) : base(protocol) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Prefabs : MonoBehaviour { public GameObject[] FieldPrefabs; public GameObject[] ForestPrefabs; public GameObject[] FarmPrefabs; public GameObject[] HillPrefabs; public GameObject[] TownPrefabs; public GameObject[] CityPrefabs; public GameObject[] SolarFarmPrefabs; public GameObject[] WindFarmPrefabs; public GameObject[] WindFarmOnHillsPrefabs; public GameObject[] CoalPlantPrefabs; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public GameObject GetInstanceOf(ZoneKind zone, ZoneKind land) { var arr = GetInstanceOfAux(zone, land); var rand = Random.Range(0, arr.Length); return Instantiate(arr[rand]); } GameObject[] GetInstanceOfAux(ZoneKind zone, ZoneKind land) { switch (zone) { case ZoneKind.Village: break; case ZoneKind.Town: return TownPrefabs; case ZoneKind.City: return CityPrefabs; case ZoneKind.Forest: return ForestPrefabs; case ZoneKind.Field: return FieldPrefabs; case ZoneKind.Hills: return HillPrefabs; case ZoneKind.Farm: return FarmPrefabs; case ZoneKind.SolarFarm: case ZoneKind.SolarFarmLevel2: case ZoneKind.SolarFarmLevel3: return SolarFarmPrefabs; case ZoneKind.WindFarm: case ZoneKind.WindFarmLevel2: case ZoneKind.WindFarmLevel3: return land == ZoneKind.Hills ? WindFarmOnHillsPrefabs : WindFarmPrefabs; case ZoneKind.Geothermal: break; case ZoneKind.Dam: break; case ZoneKind.Battery: break; case ZoneKind.CityCoating: break; case ZoneKind.CitySolar: break; case ZoneKind.CoalPlant: case ZoneKind.GasPlant: case ZoneKind.OilPlant: return CoalPlantPrefabs; default: break; } Debug.LogWarning(zone + " prefab not found"); return ForestPrefabs; //return null; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Wanderer.GameFramework { public class LoadDataTableEventArgs :GameEventArgs<LoadDataTableEventArgs> { private bool _success; public bool Success{ get { return _success; } } private IDataTable _data; public IDataTable Data{ get{ return _data; } } private string _message; public string Message{get{ return _message; }} public LoadDataTableEventArgs Set(bool success,string message,IDataTable data) { _success=success; _message = message; _data=data; return this; } } }
namespace Glimpse.Core.Tab.Assist { public interface ITabObjectItem { ITabStyleValue Value(object value); } }
namespace Treasure.Build.CentralBuildOutput.Tests; using Microsoft.Build.Utilities.ProjectCreation; internal static class ProjectCreatorTemplatesExtensions { public static ProjectCreator DirectoryBuildProps( this ProjectCreatorTemplates _, string testRootPath, string assemblyPath, string centralBuidOutputPath = "$(MSBuildThisFileDirectory)", Action<ProjectCreator>? projectFunction = null) { ProjectCreator result = ProjectCreator.Create() .Property("CentralBuildOutputPath", centralBuidOutputPath); if (projectFunction is not null) { projectFunction(result); } result.Import(Path.Combine(assemblyPath, @"Sdk\Sdk.props")) .Import(Path.Combine(assemblyPath, @"Sdk\Sdk.targets")) .Save(Path.Combine(testRootPath, "Directory.Build.props")); return result; } }
using GezginTurizm.Business.Abstract; using GezginTurizm.DataAccess.Abstract; using GezginTurizm.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GezginTurizm.Business.Concrete { public class WorkerWithVehicleManager : IWorkerWithVehicleService { private readonly IWorkerWithVehicleDal _workerWithVehicleDal; public WorkerWithVehicleManager(IWorkerWithVehicleDal workerWithVehicleDal) { _workerWithVehicleDal = workerWithVehicleDal; } public void Add(WorkerWithVehicle entity) { _workerWithVehicleDal.Add(entity); } public void Delete(WorkerWithVehicle entity) { _workerWithVehicleDal.Delete(entity); } public List<WorkerWithVehicle> GetAll() { return _workerWithVehicleDal.GetAll(); } public WorkerWithVehicle GetById(int id) { return _workerWithVehicleDal.Get(x => x.WorkerId == id); } public int CountUnreadNotification() { return _workerWithVehicleDal.CountUnreadNotification(); } public void Update(WorkerWithVehicle entity) { _workerWithVehicleDal.Update(entity); } public void ChangeReadStatus(int id) { _workerWithVehicleDal.ChangeReadStatus(id); } public void SendMail() { _workerWithVehicleDal.SendEmail(); } } }
using System; using System.Collections.Generic; using System.Text; namespace CCPP.Cryptocurrency.Common.Utils { public static class Extensions { /// <summary> /// 根据GUID获取16位的唯一字符串 /// </summary> /// <param name=\"guid\"></param> /// <returns></returns> public static string GuidTo22String(this Guid guid, int length = 22) { var data = guid.ToString().Replace("-", ""); string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); string encoded = base64.Replace("/", "").Replace("+", ""); return encoded.Substring(0, length); } public static string GuidTo64String(this Guid guid) { var data = guid.ToString().Replace("-", ""); var newData = Guid.NewGuid().ToString().Replace("-", ""); return data + newData; } /// <summary> /// 截断指定小数 /// </summary> /// <param name="data"></param> /// <param name="scale">小数位长度</param> /// <returns></returns> public static decimal DataTruncated(this decimal data, int scale) { var strData = data.ToString(scale); return decimal.Parse(strData); } /// <summary> /// decimal保留指定位数小数 /// </summary> /// <param name="num">原始数量</param> /// <param name="scale">保留小数位数</param> /// <returns>截取指定小数位数后的数量字符串</returns> public static string ToString(this decimal num, int scale) { string numToString = num.ToString(); int index = numToString.IndexOf("."); int length = numToString.Length; if (index != -1) { if (scale == 0) { return numToString.Substring(0, index); } return string.Format("{0}.{1}", numToString.Substring(0, index), numToString.Substring(index + 1, Math.Min(length - index - 1, scale))); } else { return num.ToString($"f{scale}"); } } public static string ConvertToHex(this byte[] data) { return BitConverter.ToString(data, 0).Replace("-", ""); } public static string ConvertStringToHex(this string data) { StringBuilder sbHex = new StringBuilder(); foreach (char chr in data) { sbHex.Append(String.Format("{0:X2}", Convert.ToInt32(chr))); } return sbHex.ToString(); } } }
using SharpNeat.EvolutionAlgorithm; using Xunit; namespace SharpNeat.Neat.ComplexityRegulation.Tests; public class RelativeComplexityRegulationStrategyTests { #region Test Methods [Fact] public void TestInitialisation() { var strategy = new RelativeComplexityRegulationStrategy(10, 10.0); var eaStats = new EvolutionAlgorithmStatistics(); var popStats = new PopulationStatistics(); // The strategy should initialise to, and remain in, Complexifying mode. for(int i=0; i < 100; i++) { eaStats.Generation = i; ComplexityRegulationMode mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Complexifying, mode); } } [Fact] public void TestTransitionToSimplifying() { var strategy = new RelativeComplexityRegulationStrategy(10, 10.0); var eaStats = new EvolutionAlgorithmStatistics(); var popStats = new PopulationStatistics(); ComplexityRegulationMode mode; // The strategy should initialise to, and remain in, Complexifying mode // while mean population complexity is below the threshold. for(int i=0; i < 11; i++) { eaStats.Generation = i; popStats.MeanComplexity = i; popStats.MeanComplexityHistory.Enqueue(i); mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Complexifying, mode); } // The strategy should switch to simplifying mode when mean complexity // rises above the threshold. eaStats.Generation = 11; popStats.MeanComplexity = 10.01; popStats.MeanComplexityHistory.Enqueue(10.01); mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Simplifying, mode); } [Fact] public void TestTransitionToComplexifying() { var strategy = new RelativeComplexityRegulationStrategy(10, 10.0); var eaStats = new EvolutionAlgorithmStatistics(); var popStats = new PopulationStatistics(); ComplexityRegulationMode mode; // Cause an immediate switch to into simplifying mode. int generation = 0; eaStats.Generation = generation++; popStats.MeanComplexity = 11.0; popStats.MeanComplexityHistory.Enqueue(11.0); mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Simplifying, mode); // Reset the buffer that the moving average is calculated from; // This allows us to change the mean to below the threshold and for the // moving average to start rising immediately; that would ordinarily cause // an immediate switch back to complexifying mode, but that is prevented by // {minSimplifcationGenerations} being set to 10. popStats.MeanComplexityHistory.Clear(); for(int i=0; i < 10; i++) { eaStats.Generation = generation++; popStats.MeanComplexity = 2.0; popStats.MeanComplexityHistory.Enqueue(2.0); mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Simplifying, mode); } // Now that {minSimplifcationGenerations} have passed, the strategy should switch // back to complexifying mode. eaStats.Generation = generation++; popStats.MeanComplexity = 2.0; popStats.MeanComplexityHistory.Enqueue(2.0); mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Complexifying, mode); // The threshold should have been set relative to the popStats.MeanComplexity (to 12). eaStats.Generation = generation++; popStats.MeanComplexity = 11.9; popStats.MeanComplexityHistory.Enqueue(11.9); mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Complexifying, mode); eaStats.Generation = generation++; popStats.MeanComplexity = 12.01; popStats.MeanComplexityHistory.Enqueue(12.01); mode = strategy.UpdateMode(eaStats, popStats); Assert.Equal(ComplexityRegulationMode.Simplifying, mode); } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using TheBookStore.DataTransferObjects; using TheBookStore.Models; namespace TheBookStore.Infrastructure { public static class Extensions { public static string AsString(this IEnumerable<BookAuthorsDto> authors) { var list = String.Empty; for (int i = 0; i < authors.Count(); i++) { list += authors.ElementAt(i).FullName; if (i < authors.Count() - 1) { list += " and "; } } return list; } public static string Flatten(this BookDto book) { var flatBook = new { Id = book.Id, Title = book.Title.Escaped(), Authors = book.Authors.AsString().Escaped() }; return string.Format("{0},{1},{2}", flatBook.Id, flatBook.Title, flatBook.Authors); } static char[] _specialChars = new char[] { ',', '\n', '\r', '"' }; private static string Escaped(this object o) { if (o == null) { return ""; } string field = o.ToString(); if (field.IndexOfAny(_specialChars) != -1) { return String.Format("\"{0}\"", field.Replace("\"", "\"\"")); } else return field; } } }
using System.IO; namespace XFiler; public sealed class FileViewModel : FileEntityViewModel { public FileInfo FileInfo => (FileInfo)Info; public long Size => FileInfo.Length; public FileViewModel(IIconLoader iconLoader, IClipboardService clipboardService, IFileTypeResolver fileTypeResolver) : base(iconLoader, clipboardService, fileTypeResolver) { } }
namespace _01SchoolClasses.Interfaces { interface ICommentable { void AddTextBlock(string text); string DisplayTextBlock(); } }
// ClassicalSharp copyright 2014-2016 UnknownShadow200 | Licensed under MIT using System; using OpenTK; namespace ClassicalSharp { /// <summary> Stores various properties about the blocks in Minecraft Classic. </summary> public partial class BlockInfo { public SoundType[] DigSounds = new SoundType[BlocksCount]; public SoundType[] StepSounds = new SoundType[BlocksCount]; int curSoundBlock = (int)Block.Stone; public void InitSounds() { SetSound( 1, SoundType.Stone ); SetSound( 1, SoundType.Grass ); SetSound( 1, SoundType.Gravel ); SetSound( 1, SoundType.Stone ); SetSound( 1, SoundType.Wood ); SetSound( 1, SoundType.Grass, SoundType.None ); SetSound( 1, SoundType.Stone ); SetSound( 4, SoundType.None ); SetSound( 1, SoundType.Sand ); SetSound( 1, SoundType.Gravel ); SetSound( 3, SoundType.Stone ); SetSound( 1, SoundType.Wood ); SetSound( 2, SoundType.Grass ); SetSound( 1, SoundType.Glass, SoundType.Stone ); SetSound( 16, SoundType.Cloth ); SetSound( 4, SoundType.Grass, SoundType.None ); SetSound( 5, SoundType.Stone ); SetSound( 1, SoundType.Grass ); SetSound( 1, SoundType.Wood ); SetSound( 3, SoundType.Stone ); SetSound( 1, SoundType.Cloth ); SetSound( 1, SoundType.Stone ); SetSound( 1, SoundType.Snow ); SetSound( 1, SoundType.Wood ); SetSound( 5, SoundType.Cloth ); SetSound( 4, SoundType.Stone ); SetSound( 1, SoundType.Wood ); SetSound( 1, SoundType.Stone ); curSoundBlock = (int)Block.Fire; SetSound( 1, SoundType.Wood, SoundType.None ); } void SetSound( int count, SoundType type ) { SetSound( count, type, type ); } void SetSound( int count, SoundType digType, SoundType stepType ) { for( int i = 0; i < count; i++ ) { StepSounds[i + curSoundBlock] = stepType; DigSounds[i + curSoundBlock] = digType; } curSoundBlock += count; } } public enum SoundType : byte { None, Wood, Gravel, Grass, Stone, Metal, Glass, Cloth, Sand, Snow, } }
//<snippet1> using System; public class Application { public static void Main() { // Create some DateTime objects. DateTime one = DateTime.UtcNow; DateTime two = DateTime.Now; DateTime three = one; // Compare the DateTime objects and display the results. bool result = one.Equals(two); Console.WriteLine("The result of comparing DateTime object one and two is: {0}.", result); result = one.Equals(three); Console.WriteLine("The result of comparing DateTime object one and three is: {0}.", result); } } // This code example displays the following: // // The result of comparing DateTime object one and two is: False. // The result of comparing DateTime object one and three is: True. //</snippet1>
namespace TeamTaskboard.Web.ViewModels.Team { using AutoMapper; using TeamTaskboard.Models; using TeamTaskboard.Web.Infrastructure.Mappings; public class TeamMemberViewModel : IMapFrom<TaskboardUser>, ICustomMappings { public string UserName { get; set; } public string Email { get; set; } public int ReportedTasksCount { get; set; } public int ProcessedTasksCount { get; set; } public void CreateMappings(IConfiguration configuration) { configuration.CreateMap<TaskboardUser, TeamMemberViewModel>() .ForMember(dest => dest.ProcessedTasksCount, opt => opt.MapFrom(src => src.ProcessedTasks.Count)); configuration.CreateMap<TaskboardUser, TeamMemberViewModel>() .ForMember(dest => dest.ReportedTasksCount, opt => opt.MapFrom(src => src.ReportertedTasks.Count)); } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace AdventOfCode2020 { public class Day07 { public class Bag : IEquatable<Bag> { readonly string color; Dictionary<Bag, int> subBags = new Dictionary<Bag, int>(); public string Color => color; public Bag(string color) { this.color = color; } public static Bag Parse(string line) { var split = Regex.Split(line, @"contain"); var result = new Bag(split[0].Substring(0, split[0].Length - " bags".Length).Trim()); if (!split[1].Contains("no other bags")) { var bags = split[1].Split(","); foreach (var bagStr in bags) { var match = Regex.Match(bagStr, @"(\d+) (.*)bags?"); if (!match.Success) { Console.WriteLine($"bagStr={bagStr}"); } var count = int.Parse(match.Groups[1].Value); var bag = new Bag(match.Groups[2].Value.Trim()); result.subBags.Add(bag, count); } } return result; } public bool Contains(string otherColor, HashSet<Bag> bags) { if (color.Equals(otherColor)) return true; if (subBags.ContainsKey(new Bag(otherColor))) return true; foreach (var kv in subBags) { if (bags.TryGetValue(kv.Key, out var bag)) { if (bag.Contains(otherColor, bags)) { return true; } } } return false; } public int Count(HashSet<Bag> bags) { int count = 1; foreach (var bag in subBags) { if (bags.TryGetValue(bag.Key, out var subBag)) { count += bag.Value * subBag.Count(bags); } } return count; } public override string ToString() { var result = new StringBuilder(); result.Append($"{color}"); if (subBags.Count > 0) { result.Append("("); bool isFirst = true; foreach (var kv in subBags) { if (!isFirst) result.Append(","); isFirst = false; result.Append(kv.Key); result.Append($": {kv.Value}"); } result.Append($")"); } return result.ToString(); } public override bool Equals(object obj) { return Equals(obj as Bag); } public bool Equals(Bag other) { return other != null && color == other.color; } public override int GetHashCode() { return HashCode.Combine(color); } public static bool operator ==(Bag left, Bag right) { return EqualityComparer<Bag>.Default.Equals(left, right); } public static bool operator !=(Bag left, Bag right) { return !(left == right); } } private static HashSet<Bag> Parse(IEnumerable<string> input) { var result = new HashSet<Bag>(); foreach (var line in input) { result.Add(Bag.Parse(line)); } return result; } [Test] public void Part1_Example1() { string input = @"light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags."; var bags = Parse(Common.GetLines(input)); var count = 0; var nonShinyBags = bags.Where(x => !x.Color.Equals("shiny gold")).ToHashSet(); foreach (var bag in nonShinyBags) { if (bag.Contains("shiny gold", nonShinyBags)) { count++; } Console.WriteLine(bag); } Assert.AreEqual(4, count); } [Test] public void Part1() { var bags = Parse(Common.DayInput(nameof(Day07))); var count = 0; var nonShinyBags = bags.Where(x => !x.Color.Equals("shiny gold")).ToHashSet(); foreach (var bag in nonShinyBags) { if (bag.Contains("shiny gold", nonShinyBags)) { count++; } Console.WriteLine(bag); } Assert.AreEqual(124, count); } [Test] public void Part2_Example1() { string input = @"light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags."; var bags = Parse(Common.GetLines(input)); int count = -1; if (bags.TryGetValue(new Bag("shiny gold"), out var shinyGold)) { count = shinyGold.Count(bags); } Assert.AreEqual(32, count - 1); } [Test] public void Part2_Example2() { string input = @"shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags."; var bags = Parse(Common.GetLines(input)); int count = -1; if (bags.TryGetValue(new Bag("shiny gold"), out var shinyGold)) { count = shinyGold.Count(bags); } Assert.AreEqual(126, count - 1); } [Test] public void Part2() { var bags = Parse(Common.DayInput(nameof(Day07))); int count = -1; if (bags.TryGetValue(new Bag("shiny gold"), out var shinyGold)) { count = shinyGold.Count(bags); } Assert.AreEqual(34862, count - 1); } } }
using MultiWatcher.Interfaces; using OeBrowser.Interfaces; using OeBrowser.Utils; using System.Collections; using System.Collections.Generic; namespace MultiWatcher.Utils { public class LoggerManager : ILogger, ILogWriter, IEnumerable<ILogger> { private List<ILogger> loggers = new List<ILogger>(); public void AddLogger(ILogger logger) { loggers.Add(logger); } public void WriteLog(string message) { foreach (ILogger logger in loggers) { logger.WriteLog(message); } } public IEnumerator<ILogger> GetEnumerator() { return loggers.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return loggers.GetEnumerator(); } public void RemoveLogger(ILogger logger) { if (logger == null) return; loggers.Remove(logger); } public void Clear() { loggers.RemoveAll((l) => !(l is SimpleLogger)); } } }
using System.Threading.Tasks; namespace Common { public interface IInterface1 { string Name { get; } Task<int> GetAsync(); } }
using Detached.Mappers.EntityFramework; using Detached.Mappers.Model; using Detached.Mappers.Samples.RestApi.Models; using Detached.Mappers.Samples.RestApi.Services; using Detached.Mappers.Samples.RestApi.Stores; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Detached.Mappers.Samples.RestApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(); services.AddDbContext<MainDbContext>(cfg => { cfg.UseSqlServer(Configuration.GetConnectionString("MainDb")); cfg.UseDetached(); }); services.AddScoped<InvoiceService>(); services.AddScoped<InvoiceStore>(); services.Configure<MapperOptions>(m => { m.Configure<User>().IsEntity(); }); } public class User { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MainDbContext mainDb) { if (mainDb.Database.EnsureCreated()) { Seed(mainDb); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } void Seed(MainDbContext db) { db.InvoiceTypes.Add(new InvoiceType { Name = "Taxed" }); db.Customers.Add(new Customer { DocumentNumber = "123", FirstName = "sample", LastName = "customer", Email = "samplecustomer@example.com" }); db.StockUnits.Add(new StockUnit { Name = "Potato", Quantity = 10 }); db.StockUnits.Add(new StockUnit { Name = "Tomato", Quantity = 8 }); db.SaveChanges(); } } }
using System.Collections.Generic; using System.Linq; using I3dShapes.Model; namespace I3dShapes.Tools.Extensions { /// <summary> /// Extensions by <see cref="ShapeFile"/>. /// </summary> public static class ShapeFileExtensions { /// <summary> /// Read all <see cref="Shape"/>. /// </summary> /// <param name="shapeFile"><inheritdoc cref="ShapeFile"/></param> /// <returns>Collection <see cref="Shape"/>.</returns> public static IEnumerable<Shape> ReadShapes(this ShapeFile shapeFile) { return shapeFile.ReadKnowTypes(ShapeType.Shape) .OfType<Shape>(); } /// <summary> /// Read all <see cref="Spline"/>. /// </summary> /// <param name="shapeFile"><inheritdoc cref="ShapeFile"/></param> /// <returns>Collection <see cref="Spline"/>.</returns> public static IEnumerable<Spline> ReadSplines(this ShapeFile shapeFile) { return shapeFile.ReadKnowTypes(ShapeType.Spline) .OfType<Spline>(); } /// <summary> /// Read all <see cref="NavMesh"/>. /// </summary> /// <param name="shapeFile"><inheritdoc cref="ShapeFile"/></param> /// <returns>Collection <see cref="NavMesh"/>.</returns> public static IEnumerable<NavMesh> ReadNavMesh(this ShapeFile shapeFile) { return shapeFile.ReadKnowTypes(ShapeType.NavMesh) .OfType<NavMesh>(); } } }
using System; using System.IO; using System.Diagnostics; using System.Threading; using NetcoreDbgTest; using NetcoreDbgTest.MI; using NetcoreDbgTest.Script; using Xunit; namespace NetcoreDbgTest.Script { class Context { static bool IsStoppedEvent(MIOutOfBandRecord record) { if (record.Type != MIOutOfBandRecordType.Async) { return false; } var asyncRecord = (MIAsyncRecord)record; if (asyncRecord.Class != MIAsyncRecordClass.Exec || asyncRecord.Output.Class != MIAsyncOutputClass.Stopped) { return false; } return true; } public static void WasBreakpointHit(Breakpoint breakpoint) { var bp = (LineBreakpoint)breakpoint; Func<MIOutOfBandRecord, bool> filter = (record) => { if (!IsStoppedEvent(record)) { return false; } var output = ((MIAsyncRecord)record).Output; var reason = (MIConst)output["reason"]; if (reason.CString != "breakpoint-hit") { return false; } var frame = (MITuple)(output["frame"]); var fileName = (MIConst)(frame["file"]); var numLine = (MIConst)(frame["line"]); if (fileName.CString == bp.FileName && numLine.CString == bp.NumLine.ToString()) { return true; } return false; }; if (!MIDebugger.IsEventReceived(filter)) throw new NetcoreDbgTestCore.ResultNotSuccessException(); } public static void EnableBreakpoint(string bpName) { Breakpoint bp = DebuggeeInfo.Breakpoints[bpName]; Assert.Equal(BreakpointType.Line, bp.Type); var lbp = (LineBreakpoint)bp; Assert.Equal(MIResultClass.Done, MIDebugger.Request("-break-insert -f " + lbp.FileName + ":" + lbp.NumLine).Class); } public static void DebuggerExit() { Assert.Equal(MIResultClass.Exit, Context.MIDebugger.Request("-gdb-exit").Class); } public static void Continue() { Assert.Equal(MIResultClass.Running, MIDebugger.Request("-exec-continue").Class); } public static MIDebugger MIDebugger = new MIDebugger(); public static Process testProcess; } } namespace MITestTarget { class Program { static void Main(string[] args) { Label.Checkpoint("init", "bp_setup", () => { Context.testProcess = new Process(); Context.testProcess.StartInfo.UseShellExecute = false; Context.testProcess.StartInfo.FileName = DebuggeeInfo.CorerunPath; Context.testProcess.StartInfo.Arguments = DebuggeeInfo.TargetAssemblyPath; Context.testProcess.StartInfo.CreateNoWindow = true; Assert.True(Context.testProcess.Start()); Assert.Equal(MIResultClass.Done, Context.MIDebugger.Request("-target-attach " + Context.testProcess.Id.ToString()).Class); }); // wait some time, control process should attach and setup breakpoints Thread.Sleep(3000); Label.Checkpoint("bp_setup", "bp_test", () => { Context.EnableBreakpoint("bp"); Context.EnableBreakpoint("bp2"); }); int i = 10000; i++; Label.Breakpoint("bp"); Label.Checkpoint("bp_test", "finish", () => { Context.WasBreakpointHit(DebuggeeInfo.Breakpoints["bp"]); Context.Continue(); }); // wait some time after process detached Thread.Sleep(i); Label.Breakpoint("bp2"); Label.Checkpoint("finish", "", () => { Context.WasBreakpointHit(DebuggeeInfo.Breakpoints["bp2"]); Assert.Equal(MIResultClass.Done, Context.MIDebugger.Request("-thread-info").Class); Assert.Equal(MIResultClass.Done, Context.MIDebugger.Request("-target-detach").Class); Assert.Equal(MIResultClass.Error, Context.MIDebugger.Request("-thread-info").Class); Assert.False(Context.testProcess.HasExited); Context.testProcess.Kill(); while (!Context.testProcess.HasExited) {}; // killed by SIGKILL Assert.NotEqual(0, Context.testProcess.ExitCode); Context.DebuggerExit(); }); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.CommandLine.Rendering.Views; using FluentAssertions; using Xunit; namespace System.CommandLine.Rendering.Tests.Views { public class RowDefinitionTests { [Fact] public void Star_sized_row_definition_negative_weight_throws() { Action createNegativeWeight = () => RowDefinition.Star(-1); createNegativeWeight.Should().Throw<ArgumentException>(); } [Fact] public void Star_sized_row_definition_can_be_zero() { var rowDefinition = RowDefinition.Star(0); rowDefinition.Value.Should().Be(0); rowDefinition.SizeMode.Should().Be(SizeMode.Star); } [Fact] public void Can_create_star_sized_row_definition() { var rowDefinition = RowDefinition.Star(1); rowDefinition.Value.Should().Be(1.0); rowDefinition.SizeMode.Should().Be(SizeMode.Star); } [Fact] public void Fixed_sized_row_definition_negative_weight_throws() { Action createNegativeWeight = () => RowDefinition.Fixed(-1); createNegativeWeight.Should().Throw<ArgumentException>(); } [Fact] public void Fixed_sized_row_definition_can_be_zero() { var rowDefinition = RowDefinition.Fixed(0); rowDefinition.Value.Should().Be(0); rowDefinition.SizeMode.Should().Be(SizeMode.Fixed); } [Fact] public void Can_create_fixed_sized_row_definition() { var rowDefinition = RowDefinition.Fixed(1); rowDefinition.Value.Should().Be(1.0); rowDefinition.SizeMode.Should().Be(SizeMode.Fixed); } [Fact] public void Can_create_size_to_content_row_definition() { var rowDefinition = RowDefinition.SizeToContent(); rowDefinition.Value.Should().Be(0.0); rowDefinition.SizeMode.Should().Be(SizeMode.SizeToContent); } } }
using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace kmd.Core.Extensions.Converters { public class BooleanToGridLengthConverter : IValueConverter { public GridLength FalseSize { get; set; } = new GridLength(0); public GridLength TrueSize { get; set; } = new GridLength(1, GridUnitType.Star); public object Convert(object value, Type targetType, object parameter, string language) { if (value is bool boolvalue && boolvalue) return TrueSize; return FalseSize; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace CK.CodeGen { /// <summary> /// A named scope is a generic named piece of source code that can be enclosed /// in another <see cref="Parent"/> named scope. /// It generalizes <see cref="ITypeScope"/> that defines a Type (class, struct, enum, etc.) /// a <see cref="INamespaceScope"/> that defines a namespace or a <see cref="IFunctionScope"/> /// for functions or methods. /// </summary> public interface INamedScope { /// <summary> /// Gets the root workspace. /// </summary> ICodeWorkspace Workspace { get; } /// <summary> /// The parent code scope. /// This is null for a root <see cref="INamespaceScope"/>. /// </summary> INamedScope? Parent { get; } /// <summary> /// The name of this scope: it is the leaf of the <see cref="FullName"/>. /// It is never null but can be empty for a global <see cref="INamespaceScope"/>. /// </summary> string Name { get; } /// <summary> /// The full name of this scope starts with the full name of this <see cref="Parent"/> scope. /// It is never null but can be empty for a global <see cref="INamespaceScope"/>. /// </summary> string FullName { get; } /// <summary> /// Collects the whole code into a string collector, optionally closing the /// scope with a trailing '}' or leaving it opened. /// </summary> /// <param name="collector">The string collector to write to.</param> /// <param name="closeScope">True to close the scope.</param> void Build( Action<string> collector, bool closeScope ); /// <summary> /// Collects the whole code into a <see cref="StringBuilder"/>, optionally closing the /// scope with a trailing '}' or leaving it opened. /// </summary> /// <param name="b">The string builder to write to.</param> /// <param name="closeScope">True to close the scope before returning the builder.</param> /// <returns>The string builder.</returns> StringBuilder Build( StringBuilder b, bool closeScope ); /// <summary> /// Gets a memory associated to this scope. /// It can contain any data that need to be associated to this scope. /// </summary> IDictionary<object, object?> Memory { get; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using NetHacksPack.Data.Linq.EF; using System.Linq; namespace Microsoft.Extensions.DependencyInjection { public static class EntityFrameworkExtensions { public static IServiceCollection AddQueryableAsRepository<TDbContext>(this IServiceCollection services) where TDbContext : DbContext { return services .AddScoped(typeof(IQueryable<>), typeof(EfQuery<>)); } } }
public class RedoButton : TaskbarButton { public void Redo() { ActionStack.instance.RedoAction(); } protected override bool ShouldShowButton() { return ActionStack.instance.redoStackSize > 0; } }
using System; using Xunit; namespace csharp_learning { // https://www.diffchecker.com/IA1sqZ60 class MyClassA : IDisposable { public bool IsDisMethodCalled { get; private set; } public MyClassA() { IsDisMethodCalled = false; } public void Dispose() { // do nothing IsDisMethodCalled = true; } } public class UnitTest46 { private MyClassA myClassA = new MyClassA(); [Fact] public void UseDisposableResourceInUsing() { using (myClassA) { Assert.False(myClassA.IsDisMethodCalled); } Assert.True(myClassA.IsDisMethodCalled); } [Fact] public void UseDisposableResourceInTryCatchFinally() { try { Assert.False(myClassA.IsDisMethodCalled); } finally { if (myClassA != null) { myClassA.Dispose(); } } Assert.True(myClassA.IsDisMethodCalled); } } }
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace KSoft.Test { [TestClass] public class EnumFlagsTest : BaseTestClass { enum FlagsEnumSansAttribute { Flag0 = 1<<0, Flag1 = 1<<1, Flag2 = 1<<2, Flag3 = 1<<3, }; [TestMethod] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Enum_FlagsSansAttributeTest() { try { FlagsEnumSansAttribute e = FlagsEnumSansAttribute.Flag0; // The below statement should throw a TypeInitializationException EnumFlags.Add(ref e, FlagsEnumSansAttribute.Flag2); Assert.Fail("EnumFlags didn't fail on an Enum without a Flags attribute!"); } catch (System.Exception ex) { Assert.IsInstanceOfType(ex.InnerException, typeof(System.NotSupportedException)); } } [System.Flags] enum FlagsEnum { Flag0 = 1<<0, Flag1 = 1<<1, Flag2 = 1<<2, Flag3 = 1<<3, }; [TestMethod] public void Enum_FlagsAddTest() { ////////////////////////////////////////////////////////////////////////// // Test by-ref const FlagsEnum kExpectedResult1 = FlagsEnum.Flag0 | FlagsEnum.Flag2; FlagsEnum e1 = FlagsEnum.Flag0; EnumFlags.Add(ref e1, FlagsEnum.Flag2); Assert.AreEqual(kExpectedResult1, e1); ////////////////////////////////////////////////////////////////////////// // Test by-value const FlagsEnum kExpectedResult2 = kExpectedResult1 | FlagsEnum.Flag3; FlagsEnum e2 = EnumFlags.Add(e1, FlagsEnum.Flag3); Assert.AreEqual(kExpectedResult2, e2); } [TestMethod] public void Enum_FlagsRemoveTest() { ////////////////////////////////////////////////////////////////////////// // Test by-ref const FlagsEnum kExpectedResult1 = FlagsEnum.Flag0; FlagsEnum e1 = FlagsEnum.Flag0 | FlagsEnum.Flag2; EnumFlags.Remove(ref e1, FlagsEnum.Flag2); Assert.AreEqual(kExpectedResult1, e1); ////////////////////////////////////////////////////////////////////////// // Test by-value const FlagsEnum kExpectedResult2 = 0; FlagsEnum e2 = EnumFlags.Remove(e1, FlagsEnum.Flag0); Assert.AreEqual(kExpectedResult2, e2); } [TestMethod] public void Enum_FlagsModifyTest() { ////////////////////////////////////////////////////////////////////////// // Test by-ref const FlagsEnum kExpectedResult1 = FlagsEnum.Flag0 | FlagsEnum.Flag2; FlagsEnum e1 = FlagsEnum.Flag0; EnumFlags.Modify(true, ref e1, FlagsEnum.Flag2); Assert.AreEqual(kExpectedResult1, e1); ////////////////////////////////////////////////////////////////////////// // Test by-value const FlagsEnum kExpectedResult2 = FlagsEnum.Flag2; FlagsEnum e2 = EnumFlags.Modify(false, e1, FlagsEnum.Flag0); Assert.AreEqual(kExpectedResult2, e2); } [TestMethod] public void Enum_FlagsTest() { FlagsEnum e = FlagsEnum.Flag0 | FlagsEnum.Flag2; Assert.IsTrue(EnumFlags.Test(e, FlagsEnum.Flag2)); Assert.IsTrue(EnumFlags.Test(e, FlagsEnum.Flag0 | FlagsEnum.Flag2)); } }; }
using System; using System.Collections.Generic; using System.Text; namespace ZDevTools.ServiceCore { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public sealed class ServiceOrderAttribute : Attribute { // This is a positional argument public ServiceOrderAttribute(int order) { this.Order = order; } /// <summary> /// 值越小越靠前 /// </summary> public int Order { get; } } }
using Microsoft.AspNetCore.Mvc; namespace app { public partial class ToDoController { [HttpPut] [Route("{index}")] public IActionResult UpdateItem(int index, [FromBody] string newItem) { if (index >= 0 && index < items.Count) { items[index] = newItem; return Ok(); } return BadRequest("Invalid index"); } } }
// // RepeatItem.cs // // Author: // Roman Lacko (backup.rlacko@gmail.com) // // Copyright (c) 2010 - 2014 Roman Lacko // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Collections.Generic; namespace SharpTAL { public class RepeatItem : ITalesIterator { private int _position; public RepeatItem(IEnumerable sequence) { _position = -1; var c = sequence as ICollection; if (c != null) length = c.Count; else { var s = sequence as string; if (s != null) length = s.Length; else length = 0; } } #region ITalesIterator implementation public void next(bool isLast) { _position++; end = isLast; } public int length { get; protected set; } public int index { get { return _position; } } public int number { get { return _position + 1; } } public bool even { get { return index % 2 == 0; } } public bool odd { get { return index % 2 == 1; } } public bool start { get { return index == 0; } } public bool end { get; protected set; } public string letter { get { string result = ""; int nextCol = _position; if (nextCol == 0) return "a"; while (nextCol > 0) { int tmp = nextCol; nextCol = tmp / 26; int thisCol = tmp % 26; result = ((char)(('a') + thisCol)) + result; } return result; } } public string Letter { get { return letter.ToUpper(); } } public string roman { get { var romanNumeralList = new Dictionary<string, int> { { "m", 1000 } ,{ "cm", 900 } ,{ "d", 500 } ,{ "cd", 400 } ,{ "c", 100 } ,{ "xc", 90 } ,{ "l", 50 } ,{ "xl", 40 } ,{ "x", 10 } ,{ "ix", 9 } ,{ "v", 5 } ,{ "iv", 4 } ,{ "i", 1 } }; if (_position > 3999) return " "; int num = _position + 1; string result = ""; foreach (KeyValuePair<string, int> kv in romanNumeralList) { while (num >= kv.Value) { result += kv.Key; num -= kv.Value; } } return result; } } public string Roman { get { return roman.ToUpper(); } } #endregion } }
using McMaster.Extensions.CommandLineUtils; namespace Appy.Tool.OnePassword.Cli { public class CommandLineApplicationFactory : ICommandLineApplicationFactory { public CommandLineApplication Create(string name, string fullName) { return new CommandLineApplication { Name = name, FullName = fullName}; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace Clean.Architecture.Wpf.ViewModels; internal class DelegateCmd : ICommand { #pragma warning disable CS0067 public event EventHandler? CanExecuteChanged; #pragma warning restore CS0067 public bool CanExecute(object? parameter) { if(CanExecutedHandler != null) return CanExecutedHandler.Invoke(parameter); else return true; } public void Execute(object? parameter) { ExecuteHandler?.Invoke(parameter); } public Action<object?>? ExecuteHandler { get; set; } public Func<object?, bool>? CanExecutedHandler { get; set; } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 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.Linq; using AuthorizeNet; using AuthorizeNet.APICore; using Hotcakes.Commerce.BusinessRules; using Hotcakes.Commerce.BusinessRules.OrderTasks; using Hotcakes.Commerce.Catalog; using Hotcakes.Commerce.Orders; using Hotcakes.Payment; using Hotcakes.Payment.Gateways; using Microsoft.VisualStudio.TestTools.UnitTesting; using Order = Hotcakes.Commerce.Orders.Order; namespace Hotcakes.Commerce.Tests.Workflow { /// <summary> /// Summary description for WorkflowTest /// </summary> [TestClass] public class WorkflowTest : BaseTest { /// <summary> /// Gets or sets the test context which provides /// information about and functionality for the current test run. /// </summary> public TestContext TestContext { get; set; } [TestMethod] public void Workflow_CreateRecurringSubscriptions() { var app = CreateHccAppInMemory(); // Configure Authorize ARB var gateId = new Hotcakes.Payment.RecurringGateways.AuthorizeNet().Id; app.CurrentStore.Settings.PaymentReccuringGateway = gateId; app.CurrentStore.Settings.PaymentSettingsSet(gateId, new AuthorizeNetSettings { MerchantLoginId = "77pmw32Vh7LS", TransactionKey = "73629XQgg28GW2tp", DeveloperMode = true, DebugMode = true, TestMode = true }); app.UpdateCurrentStore(); // Create sample subscription var prod1 = new Product { Sku = "001", ProductName = "Subscription1", SitePrice = 10m, IsRecurring = true, RecurringInterval = 10, RecurringIntervalType = RecurringIntervalType.Days }; app.CatalogServices.Products.Create(prod1); // Add subscription to cart var o = new Order {StoreId = app.CurrentStore.Id, OrderNumber = DateTime.Now.ToString("yyMMddHHmmss")}; o.Items.Add(prod1.ConvertToLineItem(app)); app.CalculateOrderAndSave(o); // Add card info var payManager = new OrderPaymentManager(o, app); payManager.RecurringSubscriptionAddCardInfo(new CardData { CardHolderName = "Test Card", CardNumber = "4111111111111111", ExpirationMonth = 1, ExpirationYear = 2020 }); o.BillingAddress.FirstName = "John"; o.BillingAddress.LastName = "Joe"; o.UserEmail = "john.joe@test.com"; // Run workflow task var c = new OrderTaskContext(app.CurrentRequestContext); c.UserId = app.CurrentCustomerId; c.Order = o; c.Inputs.SetProperty("hcc", "CardSecurityCode", "999"); var task = new CreateRecurringSubscriptions(); var taskResult = task.Execute(c); // Check result --------------------- Assert.IsTrue(taskResult); var trans = app.OrderServices.Transactions.FindAllPaged(1, 100); Assert.AreEqual(2, trans.Count); var tInfo = trans.FirstOrDefault(t => t.Action == ActionType.RecurringSubscriptionInfo); var tCreateSub = trans.FirstOrDefault(t => t.Action == ActionType.RecurringSubscriptionCreate); Assert.IsNotNull(tInfo); Assert.AreEqual("4111111111111111", tInfo.CreditCard.CardNumber); Assert.AreEqual(2020, tInfo.CreditCard.ExpirationYear); Assert.IsNotNull(tCreateSub); Assert.AreEqual(10m, tCreateSub.Amount); Assert.AreNotEqual("", tCreateSub.RefNum1); Assert.AreEqual(tInfo.IdAsString, tCreateSub.LinkedToTransaction); var subGatewey = new SubscriptionGateway2("77pmw32Vh7LS", "73629XQgg28GW2tp", ServiceMode.Test); var resSub = subGatewey.GetSubscriptionById(Convert.ToInt32(tCreateSub.RefNum1)); Assert.IsNotNull(resSub); Assert.AreEqual("John", resSub.firstName); Assert.AreEqual("Joe", resSub.lastName); Assert.AreEqual(10, resSub.amount); Assert.AreEqual(ARBSubscriptionStatusEnum.active, resSub.status); Assert.IsTrue(resSub.invoice.Contains(tCreateSub.OrderNumber)); } #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test // [TestInitialize()] // public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { } // #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace VisualRust.Cargo { [StructLayout(LayoutKind.Sequential)] struct RawDependencyError { public Utf8String Path; public Utf8String Expected; public Utf8String Got; } [StructLayout(LayoutKind.Sequential)] struct RawDependencyErrorArray { public IntPtr Buffer; public int Length; public EntryMismatchError[] ToArray() { if (Buffer == IntPtr.Zero) return null; var buffer = new EntryMismatchError[Length]; for (int i = 0; i < Length; i++) { unsafe { RawDependencyError* current = ((RawDependencyError*)Buffer) + i; buffer[i] = new EntryMismatchError(*current); } } return buffer; } } }
using System; namespace SafeRapidPdf.Attributes { [AttributeUsage(AttributeTargets.Property)] public sealed class ParameterTypeAttribute : Attribute { public ParameterTypeAttribute( bool required, bool inheritable = false, string version = "", bool obsolete = false) { Required = required; Inheritable = inheritable; Version = version; Obsolete = obsolete; } /// <summary> /// Required or Optional /// </summary> public bool Required { get; } /// <summary> /// Inheritable attribute /// </summary> public bool Inheritable { get; } /// <summary> /// PDF version from which this parameter is allowed /// </summary> public string Version { get; } /// <summary> /// Was this parameter obsoleted? /// </summary> public bool Obsolete { get; } } }
using System.Collections.Generic; namespace Kevsoft.Battleship.Game { public interface IReadOnlyBattleshipGame { ISet<(char x, int y)> Cells { get; } ISet<(char x, int y)> Hits { get; } ISet<(char x, int y)> Misses { get; } bool IsComplete { get; } } }
namespace Domain.Entities.Speech { using System; using System.Collections.Generic; using System.Linq; using ResultText; using Speaker; public class Speech : IEntity { private const long MinDataSize = 1024; [Obsolete("Only for reflection", true)] public Speech() { } protected internal Speech( string name, byte[] data, Speaker author) { SetName(name); SetData(data); SetAuthor(author); } public IList<ResultText> RecognitionResults { get; } = new List<ResultText>(); public string Name { get; protected set; } public byte[] AudioFile { get; protected set; } public int AudioFormat { get; protected set; } public int? Duration { get; protected set; } public int? BitRate { get; protected set; } public int? TotalChannels { get; protected set; } public decimal? Size { get; protected set; } public int? SamplingRate { get; protected set; } public int? BitDepth { get; protected set; } public DateTime? RecordingDate { get; protected set; } public Speaker Author { get; protected set; } public int AuthorId { get; protected set; } public int Id { get; set; } protected internal void SetName(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); Name = name; } protected internal void SetData(byte[] data) { if (data == null) throw new ArgumentNullException(nameof(data)); if (data.Length < MinDataSize) throw new InvalidOperationException("Too small data."); AudioFile = data; } protected internal void SetAuthor(Speaker author) { Author = author ?? throw new ArgumentNullException(nameof(author)); } protected internal void AddRecognitionResult(ResultText resultText) { if (resultText == null) throw new ArgumentNullException(nameof(resultText)); if (RecognitionResults.Any(x => x.Id == resultText.Id)) RecognitionResults.Remove(RecognitionResults.SingleOrDefault(x => x.Id == resultText.Id)); RecognitionResults.Add(resultText); } } }
using Godot; namespace GodotUtilities { public static class PackedSceneExtension { public static T InstanceOrNull<T>(this PackedScene scene) where T : class { var node = scene.Instance(); if (node is T t) { return t; } node.QueueFree(); GD.PushWarning($"Could not instance PackedScene {scene} as {typeof(T).Name}"); return null; } } }
using Atlas.Extensions; using NUnit.Framework; using System; namespace Atlas.Core.Test { [Category("Core")] public class TestCore : TestBase { [OneTimeSetUp] public void BaseSetup() { Initialize("Core"); } [Test, Description("DecimalToString")] [Ignore("todo: fix")] public void DecimalToString() { decimal d = 123456.1234M; string text = d.Formatted(); Assert.AreEqual("123,456.1234", text); } [Test] public void TestBookmarkUri() { BookmarkUri uri = BookmarkUri.Parse("atlas://type/v3.1/id"); Assert.AreEqual("atlas", uri.Prefix); Assert.AreEqual("type", uri.Type); Assert.AreEqual(new Version(3, 1), uri.Version); Assert.AreEqual("id", uri.Id); } } }
using Rabbit.WeiXin.MP.Messages.Response; using System; using System.Xml.Linq; namespace Rabbit.WeiXin.MP.Serialization.Providers.Response { internal sealed class NewsMessageFormatter : XmlMessageFormatterBase<ResponseMessageNews> { #region Overrides of XmlMessageFormatterBase<ResponseMessageNews> public override ResponseMessageNews Deserialize(XContainer container) { throw new NotImplementedException(); } public override string Serialize(ResponseMessageNews graph) { return SerializeAction(graph, builder => { builder.AppendFormat("<ArticleCount>{0}</ArticleCount>", graph.ArticleCount); builder.Append("<Articles>"); if (graph.Articles != null) foreach (var article in graph.Articles) { builder.AppendFormat("<item>"); builder.AppendFormat("<Title><![CDATA[{0}]]></Title>", article.Title); builder.AppendFormat("<Description><![CDATA[{0}]]></Description>", article.Description); builder.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl>", article.PicUrl); builder.AppendFormat("<Url><![CDATA[{0}]]></Url>", article.Url); builder.AppendFormat("</item>"); } builder.Append("</Articles>"); }); } #endregion Overrides of XmlMessageFormatterBase<ResponseMessageNews> } }
using MDG.ScriptableObjects.Items; using System; using UnityEngine; using UnityEngine.UI; namespace MDG.Invader.Monobehaviours.UserInterface { // Shop behaviour, should I reuse build menu and menu slot?? [RequireComponent(typeof(Button))] public class MenuSlot : MonoBehaviour { public event Action<MenuSlot> OnSlotClicked; Button button; public ShopItem ShopItem { private set; get; } // Should handle togglign of too. public bool Selected { set; get; } #pragma warning disable 649 [SerializeField] Image thumbnail; [SerializeField] Text costText; #pragma warning restore 649 public void SetItem(ShopItem shopItem) { thumbnail.sprite = shopItem.Thumbnail; costText.text = shopItem.Cost.ToString(); ShopItem = shopItem; } // Start is called before the first frame update void Start() { button = GetComponent<Button>(); button.onClick.AddListener(OnButtonClicked); } void OnButtonClicked() { Selected = true; OnSlotClicked?.Invoke(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DynamicPropertiesNet35 { public class MyProperties2 { public MyProperties2() { _keys = new List<string>(); _valuesObject = new List<object>(); _valuesInt = new List<int>(); _valuesString = new List<string>(); } private List<string> _keys; private List<object> _valuesObject; private List<int> _valuesInt; private List<string> _valuesString; private Dictionary<Type, Dictionary<string, object>> _typesDic = new Dictionary<Type, Dictionary<string, object>>(); public void Add<T>(string key, T value) { _keys.Add(key); var x = new { key = key, value = value }; _valuesObject.Add(x); var y = new KeyValuePair<string, T>(key, value); _valuesObject.Add(y); List<KeyValuePair<string, T>> myList = new List<KeyValuePair<string, T>>(); myList.Add(new KeyValuePair<string, T>(key, value)); Type t = typeof(T); if (!_typesDic.Keys.Contains(t)) { _typesDic[t] = new Dictionary<string, object>(); } _typesDic[t].Add(key, value); } public T Get<T>(string key) { Type t = typeof(T); if (!_typesDic.Keys.Contains(t)) { return default(T); } if (!_typesDic[typeof(T)].Keys.Contains(key)) { return default(T); } //T retVal = _typesDic[typeof(T)][key] as T; return (T)_typesDic[typeof(T)][key]; } } }
namespace Sitecore.Foundation.CommerceServer.Models { using Infrastructure.Constants; using Sitecore.Data.Items; /// <summary> /// CommercePromotion class /// </summary> public class Catalog : SitecoreItemBase { /// <summary> /// Initializes a new instance of the <see cref="Catalog"/> class. /// </summary> /// <param name="item">The item.</param> public Catalog(Item item) { this.InnerItem = item; } /// <summary> /// Gets the Name of the item /// </summary> /// <value> /// The name. /// </value> public string Name { get { return this.InnerItem.Name; } } /// <summary> /// The Title of the Create Wish List Page /// </summary> /// <returns>The title.</returns> public string Title() { return this.InnerItem[StorefrontConstants.ItemFields.Title]; } /// <summary> /// Label for the Wish List Name field /// </summary> /// <returns>The name title.</returns> public string NameTitle() { return this.InnerItem["Name Title"]; } } }
using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Application.Services; namespace Volo.CmsKit.Public.Ratings; public interface IRatingPublicAppService : IApplicationService { Task<RatingDto> CreateAsync(string entityType, string entityId, CreateUpdateRatingInput input); Task DeleteAsync(string entityType, string entityId); Task<List<RatingWithStarCountDto>> GetGroupedStarCountsAsync(string entityType, string entityId); }
using Api.Controllers; using Microsoft.AspNetCore.TestHost; using System.Security.Claims; using System.Threading.Tasks; using Xunit; namespace FunctionalTests { [Collection("server")] public class foo_controller_should { private readonly HostFixture _fixture; public foo_controller_should(HostFixture fixture) { _fixture = fixture; } [Fact] [ResetDatabase] public async Task add_new_foo_item() { var foo = new Foo() { Bar = "the var value" }; var response = await _fixture.Server .CreateHttpApiRequest<FooController>(f => f.PostFoo(foo),new { version = "1" }) .WithIdentity(new Claim[] { new Claim("CustomClaim","the value") }) .PostAsync(); response.EnsureSuccessStatusCode(); } } }
namespace MadXchange.Exchange.Domain.Types { public enum XchangeHttpOperation { Unknown = 0, GetInstrument = 1, GetInstrumentList = 2, GetOrderBookL2 = 3, GetOrderBook = 4, GetMargin = 5, GetMarginList = 6, GetOrder = 7, GetOrderList = 8, GetPosition = 9, GetPositionList = 10, GetLeverage = 11, PostLeverage = 12, PostPlaceOrder = 13, PostUpdateOrder = 14, PostCancelAllOrder = 15, PostCancelOrder = 16, GetWalletFund = 17, GetWalletWithdraw = 18, } public class EndPointParameter { } }
using FluentAssertions; using Toggl.Core.UI.ViewModels.Reports; using Xunit; namespace Toggl.Core.Tests.UI.ViewModels.Reports { public sealed class ReportElementBaseTests { private class MockElement : ReportElementBase { public MockElement(bool isLoading) : base(isLoading) { } public override bool Equals(IReportElement other) => other is MockElement; } public sealed class TheIsLoadingProperty { [Theory, LogIfTooSlow] [InlineData(true)] [InlineData(false)] public void IsSetFromTheConstructorProvidedValue(bool isLoading) { var mockElement = new MockElement(isLoading); mockElement.IsLoading.Should().Be(isLoading); } } } }
using Data.Entities.Identity; using Data.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; namespace Data.Entities { public class Team : IBaseEntity, ICreatedOn { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public int? ParentId { get; set; } public int? TenantId { get; set; } public DateTime CreatedOn { get; set; } // Navigation properties public Team ParentTeam { get; set; } public Tenant Tenant { get; set; } public ICollection<Team> ChildTeams { get; set; } public ICollection<Ticket> Tickets { get; set; } public ICollection<TicketProcess> TicketProcesses { get; set; } public ICollection<User> Users { get; set; } } public class TeamConfiguration : IEntityTypeConfiguration<Team> { public void Configure(EntityTypeBuilder<Team> builder) { builder.Property(p => p.Name).IsRequired().HasMaxLength(50); builder.Property(p => p.Description).IsRequired().HasMaxLength(100); builder.HasOne(p => p.ParentTeam) .WithMany(p => p.ChildTeams) .HasForeignKey(p => p.ParentId); builder.HasOne(p => p.Tenant) .WithMany(p => p.Teams) .HasForeignKey(p => p.TenantId); } } }
namespace SignInWithoutSpecifyingTenant { public abstract class SignInWithoutSpecifyingTenantApplicationTestBase : SignInWithoutSpecifyingTenantTestBase<SignInWithoutSpecifyingTenantApplicationTestModule> { } }
namespace Lykke.Cqrs.Middleware { internal class CommandInterceptionCommonContext { public object Command { get; set; } public object HandlerObject { get; internal set; } public IEventPublisher EventPublisher { get; set; } } }
using System; using EfEagerLoad.Common; namespace EfEagerLoad.IncludeStrategies { public class PredicateIncludeStrategy : IncludeStrategy { private readonly Predicate<EagerLoadContext> _strategy; public PredicateIncludeStrategy(Predicate<EagerLoadContext> strategy) { Guard.IsNotNull(nameof(strategy), strategy); _strategy = strategy; } public PredicateIncludeStrategy(Predicate<string> strategy) { Guard.IsNotNull(nameof(strategy), strategy); _strategy = (context) => strategy(context.CurrentIncludePath); } public override bool ShouldIncludeCurrentNavigation(EagerLoadContext context) { return _strategy(context); } } }
using System; using System.Collections.Generic; using System.Text; namespace Szlem.SharedKernel { public struct Nothing : IEquatable<Nothing>, IComparable<Nothing>, IComparable { public static readonly Nothing Value = new Nothing(); public int CompareTo(Nothing other) => 0; public int CompareTo(object obj) => 0; public override bool Equals(object obj) => obj is Nothing; public bool Equals(Nothing other) => true; public override int GetHashCode() => 0; #pragma warning disable IDE0060 // Remove unused parameter public static bool operator ==(Nothing left, Nothing right) => true; public static bool operator !=(Nothing left, Nothing right) => false; #pragma warning restore IDE0060 // Remove unused parameter } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using OMSAPI.DataContext; using OMSAPI.Interfaces; using OMSAPI.Models; namespace OMSAPI.Services { class AddressService : IAddress { private OMSDbContext _context; public AddressService(OMSDbContext context) { _context = context; } public void Delete(Address address) { if (address == null) throw new ArgumentNullException(nameof(address)); _context.Addresses.Remove(address); } public Address Get(int addressId) { return _context.Addresses.Find(addressId); } public IEnumerable<Address> GetAll() { return _context.Addresses.ToList(); } public IEnumerable<Address> GetAllForCustomer(int customerId) { return _context.Addresses.Where(addr => addr.CustomerId == customerId); } public void Create(Address address) { if(address == null) throw new ArgumentNullException(nameof(address)); _context.Addresses.Add(address); } public void Update(Address address) { _context.Entry(address).State = EntityState.Modified; } public bool SaveChanges() { return _context.SaveChanges() >= 0; } } }
// PropertyExpression.cs // Script#/Core/Compiler // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Diagnostics; namespace ScriptSharp.ScriptModel { internal sealed class PropertyExpression : Expression { private PropertySymbol _property; private Expression _objectReference; public PropertyExpression(Expression objectReference, PropertySymbol property, bool getter) : base((getter ? ExpressionType.PropertyGet : ExpressionType.PropertySet), property.AssociatedType, SymbolFilter.Public | SymbolFilter.InstanceMembers) { _property = property; _objectReference = objectReference; } public Expression ObjectReference { get { return _objectReference; } } public PropertySymbol Property { get { return _property; } } public override bool RequiresThisContext { get { return _objectReference.RequiresThisContext; } } } }
using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeActions; namespace RoslynTestKit.CodeActionLocators { public class ByIndexCodeActionSelector: ICodeActionSelector { private readonly int _index; public ByIndexCodeActionSelector(int index) { _index = index; } public CodeAction Find(IReadOnlyList<CodeAction> actions) { if (_index > actions.Count - 1) { return null; } return actions[_index]; } public override string ToString() { return $"with index {_index}"; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; namespace Deo.LaserVg { internal interface IPart { XElement ToXml(); } }
using Flurl.Http; using Infrastructure.EntityFramwork; using Infrastructure.Logging; using System; namespace Infrastructure.Services { public class AirQualityServiceClient : IAirQualityServiceClient { private readonly ILog log; public AirQualityServiceClient(ILog log) { this.log = log; } public Forecast Get() { try { return "https://api.tfl.gov.uk/AirQuality".GetJsonAsync<Forecast>().Result; } catch(Exception ex) { log.Log(LogLevel.Error, ex.Message); throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using SimpleApp.API.Models; using SimpleApp.API.Repositories; namespace SimpleApp.API.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : ControllerBase { private readonly ProductsRepository _repository; public ProductsController(ProductsRepository repository) { _repository = repository; } [HttpGet] public ActionResult<List<Product>> Get([FromQuery] bool discontinuedOnly = false) { List<Product> products = null; if (discontinuedOnly) { products = _repository.GetDiscontinuedProducts(); } else { products = _repository.GetProducts(); } return products; } [HttpGet("{id}")] [ProducesResponseType(200)] [ProducesResponseType(404)] public ActionResult<Product> GetById(int id) { if (!_repository.TryGetProduct(id, out var product)) { return NotFound(); } return product; } [HttpPost] [ProducesResponseType(201)] [ProducesResponseType(400)] public async Task<ActionResult<Product>> CreateAsync(Product product) { await _repository.AddProductAsync(product); return CreatedAtAction(nameof(GetById), new { id = product.Id }, product); } } }
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System; using System.Collections.Generic; using System.Threading.Tasks; using EdFi.LoadTools.SmokeTest; using log4net; namespace EdFi.LoadTools { public class SmokeTestApplicationNoBlocks : ISmokeTestApplication { private readonly IEnumerable<ITestGenerator> _testGenerators; public SmokeTestApplicationNoBlocks(IEnumerable<ITestGenerator> testGenerators) { _testGenerators = testGenerators; } protected ILog Log => LogManager.GetLogger(GetType().Name); public async Task<int> Run() { var hasFail = false; foreach (var testGenerator in _testGenerators) { var tests = testGenerator.GenerateTests(); foreach (var test in tests) { var result = false; try { result = await test.PerformTest().ConfigureAwait(false); } catch (Exception ex) { Log.Error(ex); } if (!result) { hasFail = true; } } } return hasFail ? 1 : 0; } } }
using System; using System.Collections.Generic; using System.Text; namespace AoC.Y2019.Days { internal enum ShuffleAction { Deal, Cut, New } }
using System.Threading; using System.Threading.Tasks; namespace VASPSuite.EtherGate { public interface IBlockchainOperation { BlockchainOperationId Id { get; } Task<BlockchainOperationState> GetCurrentStateAsync(); Task WaitForExecutionAsync( CancellationToken cancellationToken = default); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public static class ActionMaster { public enum Action { Tidy, Reset, EndTurn, EndGame }; public static Action NextAction ( List<int> rollsOrig ) { List<int> rolls = new List<int>( rollsOrig ); Action nextAction = Action.EndTurn; int roll = rolls[ rolls.Count - 1 ]; // pad strikes so we can rolls.Count frames correctly for ( int i = 0; i < rolls.Count && i < 18; i += 2 ) { if ( rolls[ i ] == 10 ) { // Strike rolls.Insert (i, 0); // Insert virtual 0 after strike } } if ( rolls.Count >= 21 ) { nextAction = Action.EndGame; } else if ( rolls.Count >= 19 && roll == 10 ) { // Handle last-frame special cases nextAction = Action.Reset; } else if ( rolls.Count == 20 ) { if ( rolls[ 18 ] == 10 && rolls[ 19 ] < 10 ) { // Roll 21 awarded nextAction = Action.Tidy; } else if ( rolls[ 18 ] + rolls[ 19 ] == 10 ) { // Spare, extra roll nextAction = Action.Reset; } else { nextAction = Action.EndGame; } } else if ( rolls.Count % 2 != 0 && roll != 10 ) { // First bowl of frame & not strike nextAction = Action.Tidy; } return nextAction; } public static int CountFrames ( List<int> rolls ) { int frames = 0; for ( int i = 0; i < rolls.Count; i += 2 ) { if ( rolls[ i ] == 10 ) {// Strike i--; } frames++; } return frames > 10 ? 10 : frames; } }
using System.Collections.Generic; using Newtonsoft.Json; namespace LinqToTweetsZip { public class Geo { [JsonProperty("type")] public string Type { get; private set; } [JsonProperty("coordinates")] public IReadOnlyList<double> Coordinates { get; private set; } } }
// Copyright (c) 2017 Trevor Redfern // // This software is released under the MIT License. // https://opensource.org/licenses/MIT namespace Tests.Characters.SpecialAbilities.BloodlinePowers { using Xunit; using SilverNeedle.Characters.SpecialAbilities.BloodlinePowers; public class FatedTests { [Fact] public void GainBonusOnDependingOnLevel() { var sorcerer = CharacterTestTemplates.Sorcerer(); var fated = new Fated(); sorcerer.Add(fated); sorcerer.SetLevel(3); Assert.Equal(1, fated.Bonus); sorcerer.SetLevel(7); Assert.Equal(2, fated.Bonus); sorcerer.SetLevel(11); Assert.Equal(3, fated.Bonus); sorcerer.SetLevel(19); Assert.Equal(5, fated.Bonus); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "ItemState", menuName = "Items/Item State")] public class ItemStateSO : ScriptableObject { /// <summary> /// Name of this state (if needed) /// </summary> [Tooltip("Name of this state (if needed)")] [SerializeField] string stateName = null; /// <summary> /// Name of this state (if needed) /// </summary> /// <value></value> public string StateName { get { return stateName; } } }