content
stringlengths
23
1.05M
using SeriousGameToolbox.I2D.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SeriousGameToolbox.I2D.Controls { public class ButtonControl : Control { private GUIContent guiContent = GUIContent.none; public GUIContent GuiContent { get { return guiContent; } set { if (value != null) { guiContent = value; } } } public ButtonControl(Area area) : base(area) { } protected override void DrawControl() { base.DrawControl(); if (Style == null) { throw new NullReferenceException("The style for the control " + Name + " is missing."); } if (GuiContent == null) { throw new NullReferenceException("The GuiContent for the control " + Name + " is missing."); } if (GUI.Button(Dimensions, GuiContent, Style)) { BubbleEvent(new ControlClickedEvent(this, 0)); } } } }
 namespace LionFire.Coroutines { // public interface ICoroutineHostProvider // { // CoroutineHost GetCoroutineHost(object owner = null); // } public interface IHasCoroutineHost { CoroutineHost CoroutineHost { get; } } }
using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using YukihiraKitchen.Domain; namespace YukihiraKitchen.Application.Recipes { public class RecipeIngredientValidator: AbstractValidator<RecipeIngredientParam> { public RecipeIngredientValidator() { RuleFor(x => x.IngredientName).NotEmpty(); RuleFor(x => x.IngredientName).NotNull(); RuleFor(x => x.Quantity).NotEmpty(); RuleFor(x => x.Quantity).NotNull(); RuleFor(x => x.Measurement).NotEmpty(); RuleFor(x => x.Measurement).NotNull(); } } }
using SkiaSharp; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Sample.SampleViews { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AnimationPage : ContentPage { private SkiaSharp.Elements.Rectangle _rectangle; private SKPoint _startLocation; public AnimationPage() { InitializeComponent(); AddRectangle(); Play(); } private void Play() { new Animation((value) => { canvas.SuspendLayout(); _rectangle.Transformation = SKMatrix.MakeRotationDegrees(360 * (float)value); _rectangle.Location = new SKPoint(_startLocation.X + (100 * (float)value), _startLocation.Y + (100 * (float)value)); canvas.ResumeLayout(true); }) .Commit(this, "Anim", length: 2000, easing: Easing.SpringOut); } private void AddRectangle() { _startLocation = new SKPoint(70, 70); _rectangle = new SkiaSharp.Elements.Rectangle(SKRect.Create(_startLocation, new SKSize(200, 200))) { FillColor = SKColors.SpringGreen }; canvas.Elements.Add(_rectangle); } private void Canvas_Touch(object sender, SkiaSharp.Views.Forms.SKTouchEventArgs e) { if(e.ActionType == SkiaSharp.Views.Forms.SKTouchAction.Pressed) { Play(); } } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class statusbar : MonoBehaviour { private RectTransform rect; private Vector3 position; // Use this for initialization void Start () { rect = this.GetComponent<RectTransform>(); position = rect.position; } // Update is called once per frame void Update () { } public void Change(float percent) { rect.localScale = new Vector3 (percent * 6, 3, 3); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class PedestrianLoader : MonoBehaviour { Dictionary<int, List<PedestrianPosition>> pedestrianPositions = new Dictionary<int, List<PedestrianPosition>>(); PlaybackControl pc; GameObject parent; [SerializeField] private PedestrianSystem pedestrianSystem = null; float internalTotalTime = 0.0f; public List<Pedestrian> pedestrians = new List<Pedestrian>(); public int[] population; public string pedestrianPrefab = "Pedestrian_simple"; private void Awake() { pc = GameObject.Find("PlaybackControl").GetComponent<PlaybackControl>(); parent = GameObject.Find("SimulationObjects"); } public void Clear() { pedestrianPositions.Clear(); pedestrians.Clear(); internalTotalTime = 0.0f; } /// <summary> /// Adds a position to the internal dictionary of positions belonging to pedestrians. /// </summary> /// <param name="position"></param> public void addPedestrianPosition(PedestrianPosition position) { List<PedestrianPosition> currentPosList; if (pedestrianPositions.TryGetValue(position.getID(), out currentPosList)) { currentPosList.Add(position); } else { currentPosList = new List<PedestrianPosition>(); currentPosList.Add(position); pedestrianPositions.Add(position.getID(), currentPosList); } if (position.getTime() > internalTotalTime) internalTotalTime = position.getTime(); } //public IEnumerator createPedestrians() { // foreach (var pedestrianEntry in pedestrianPositions) { // GameObject pedestrian = (GameObject)Instantiate(Resources.Load(pedestrianPrefab)); // pedestrian.transform.parent = parent.transform; // pedestrian.transform.localScale = Vector3.one; // pedestrian.transform.localRotation = Quaternion.Euler(0, 0, 0); // Pedestrian pedComponent = pedestrian.GetComponent<Pedestrian>(); // pedComponent.setPositions(pedestrianEntry.Value); // pedComponent.setID(pedestrianEntry.Key); // pedestrians.Add(pedComponent); // yield return null; // } // pc.total_time = internalTotalTime; //} public IEnumerator createPedestrians() { foreach (var pedestrianEntry in pedestrianPositions) { PedestrianEntity entity = new PedestrianEntity(pedestrianEntry.Key, pedestrianEntry.Value); pedestrianSystem.AddPedestrianEntity(entity); } yield return null; pc.total_time = internalTotalTime; } }
namespace Fabric.Authorization.Domain.Services { public interface IEventContextResolverService { string Username { get; } string ClientId { get; } string Subject { get; } string RemoteIpAddress { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Drawing; using WinForms.Common.Tests; using Xunit; namespace System.Windows.Forms.Tests { public class DataGridTests { [Fact] public void DataGrid_Ctor_Default() { var dataGrid = new SubDataGrid(); Assert.True(dataGrid.AllowNavigation); Assert.True(dataGrid.AllowSorting); Assert.Equal(SystemColors.Window, dataGrid.AlternatingBackColor); Assert.Equal(SystemColors.Window, dataGrid.BackColor); Assert.Equal(SystemColors.AppWorkspace, dataGrid.BackgroundColor); Assert.Null(dataGrid.BackgroundImage); Assert.Equal(ImageLayout.Tile, dataGrid.BackgroundImageLayout); Assert.Equal(BorderStyle.Fixed3D, dataGrid.BorderStyle); Assert.Equal(new Rectangle(0, 0, 130, 80), dataGrid.Bounds); Assert.Equal(80, dataGrid.Bottom); Assert.Equal(SystemColors.ActiveCaption, dataGrid.CaptionBackColor); Assert.Equal(Control.DefaultFont.Name, dataGrid.CaptionFont.Name); Assert.Equal(FontStyle.Bold, dataGrid.CaptionFont.Style); Assert.Equal(SystemColors.ActiveCaptionText, dataGrid.CaptionForeColor); Assert.Empty(dataGrid.CaptionText); Assert.True(dataGrid.CaptionVisible); Assert.Equal(new Rectangle(0, 0, 130, 80), dataGrid.ClientRectangle); Assert.Equal(new Size(130, 80), dataGrid.ClientSize); Assert.True(dataGrid.ColumnHeadersVisible); Assert.Equal(0, dataGrid.CurrentCell.RowNumber); Assert.Equal(0, dataGrid.CurrentCell.ColumnNumber); Assert.Equal(-1, dataGrid.CurrentRowIndex); Assert.Same(Cursors.Default, dataGrid.Cursor); Assert.Empty(dataGrid.DataMember); Assert.Null(dataGrid.DataSource); Assert.Equal(new Rectangle(0, 0, 130, 80), dataGrid.DisplayRectangle); Assert.Equal(Size.Empty, dataGrid.DefaultMaximumSize); Assert.Equal(Size.Empty, dataGrid.DefaultMinimumSize); Assert.Equal(Padding.Empty, dataGrid.DefaultPadding); Assert.Equal(new Size(130, 80), dataGrid.DefaultSize); Assert.Equal(0, dataGrid.FirstVisibleColumn); Assert.False(dataGrid.FlatMode); Assert.Equal(SystemColors.WindowText, dataGrid.ForeColor); Assert.Equal(SystemColors.Control, dataGrid.GridLineColor); Assert.Equal(DataGridLineStyle.Solid, dataGrid.GridLineStyle); Assert.Equal(SystemColors.Control, dataGrid.HeaderBackColor); Assert.Same(Control.DefaultFont, dataGrid.HeaderFont); Assert.Equal(SystemColors.ControlText, dataGrid.HeaderForeColor); Assert.Equal(SystemColors.ControlText, dataGrid.HeaderForeColor); Assert.Equal(80, dataGrid.Height); Assert.NotNull(dataGrid.HorizScrollBar); Assert.Same(dataGrid.HorizScrollBar, dataGrid.HorizScrollBar); Assert.Equal(0, dataGrid.Left); Assert.Equal(SystemColors.HotTrack, dataGrid.LinkColor); Assert.Equal(SystemColors.HotTrack, dataGrid.LinkHoverColor); Assert.Null(dataGrid.ListManager); Assert.Equal(Point.Empty, dataGrid.Location); Assert.Equal(new Padding(3, 3, 3, 3), dataGrid.Margin); Assert.Equal(Size.Empty, dataGrid.MaximumSize); Assert.Equal(Size.Empty, dataGrid.MinimumSize); Assert.Equal(Padding.Empty, dataGrid.Padding); Assert.Equal(SystemColors.Control, dataGrid.ParentRowsBackColor); Assert.Equal(SystemColors.WindowText, dataGrid.ParentRowsForeColor); Assert.Equal(DataGridParentRowsLabelStyle.Both, dataGrid.ParentRowsLabelStyle); Assert.True(dataGrid.ParentRowsVisible); Assert.Equal(75, dataGrid.PreferredColumnWidth); Assert.Equal(Control.DefaultFont.Height + 3, dataGrid.PreferredRowHeight); Assert.Equal(new Size(130, 80), dataGrid.PreferredSize); Assert.False(dataGrid.ReadOnly); Assert.True(dataGrid.RowHeadersVisible); Assert.Equal(35, dataGrid.RowHeaderWidth); Assert.Equal(SystemColors.ActiveCaption, dataGrid.SelectionBackColor); Assert.Equal(SystemColors.ActiveCaptionText, dataGrid.SelectionForeColor); Assert.Null(dataGrid.Site); Assert.Equal(new Size(130, 80), dataGrid.Size); Assert.Empty(dataGrid.TableStyles); Assert.Same(dataGrid.TableStyles, dataGrid.TableStyles); Assert.Empty(dataGrid.Text); Assert.Equal(0, dataGrid.Top); Assert.NotNull(dataGrid.VertScrollBar); Assert.Same(dataGrid.VertScrollBar, dataGrid.VertScrollBar); Assert.Equal(0, dataGrid.VisibleColumnCount); Assert.Equal(0, dataGrid.VisibleRowCount); Assert.Equal(130, dataGrid.Width); } [Fact] public void DataGrid_ColumnStartedEditing_ValidControl_Success() { var dataGrid = new DataGrid(); var control = new Control(); dataGrid.ColumnStartedEditing(control); } [Fact] public void DataGrid_ColumnStartedEditing_NullControl_Nop() { var dataGrid = new DataGrid(); dataGrid.ColumnStartedEditing(null); } private class SubDataGridTableStyle : DataGridTableStyle { public SubDataGridTableStyle() : base() { } public SubDataGridTableStyle(bool isDefaultTableStyle) : base(isDefaultTableStyle) { } public SubDataGridTableStyle(CurrencyManager listManager) : base(listManager) { } public new bool CanRaiseEvents => base.CanRaiseEvents; public new bool DesignMode => base.DesignMode; public new EventHandlerList Events => base.Events; } private class SubDataGrid : DataGrid { public new Size DefaultMaximumSize => base.DefaultMaximumSize; public new Size DefaultMinimumSize => base.DefaultMinimumSize; public new Padding DefaultPadding => base.DefaultPadding; public new Size DefaultSize => base.DefaultSize; public new ScrollBar HorizScrollBar => base.HorizScrollBar; public new ScrollBar VertScrollBar => base.VertScrollBar; } } }
using EvidenceCapture.Model.Base; using EvidenceCapture.Properties; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace EvidenceCapture.Model { class OperateControlModel : ModelBase { internal enum CaptureKind { Desktop, ActiveWindow, WebCamera } #region Fields private List<int> levels = new List<int>(); private WebCamManager webcam; #endregion #region Properties public ObservableCollection<SnapTreeItem> SnapShotTreeSource { get; set; } /// <summary>現在のグループ名</summary> public string CurrentGroup { get; set; } /// <summary> /// /// </summary> public string OutputRoot { get { return ApplicationSettings.Instance.OutputDir; } set { ApplicationSettings.Instance.OutputDir = value; RefreshTree(); } } public bool AutoResize { get; internal set; } #endregion public OperateControlModel() { SnapShotTreeSource = new ObservableCollection<SnapTreeItem>(); LevelInit(); RefreshTree(); } internal SnapTreeItem AddCapture(OperateControlModel.CaptureKind kind) { SnapTreeItem newNode = null; Bitmap bmp = null; switch (kind) { case CaptureKind.ActiveWindow: bmp = SnapHelper.GetAppCapture(); break; case CaptureKind.Desktop: bmp = SnapHelper.GetDisplayCapture(); break; case CaptureKind.WebCamera: bmp = GetCameraCapture(); break; } var outDir = Path.Combine( ApplicationSettings.Instance.OutputDir, CurrentGroup); if (!Directory.Exists(outDir)) Directory.CreateDirectory(outDir); if (SnapShotTreeSource.ToList().Count(x => x.Name == CurrentGroup) == 0) { SnapShotTreeSource.Add(new SnapTreeItem() { NodeFileType = SnapTreeItem.FileType.Folder, Name = CurrentGroup, IsExpanded = false, Children = new ObservableCollection<SnapTreeItem>() }); } var parentNode = SnapShotTreeSource.ToList().Find(x => x.Name == CurrentGroup); var lastNo = 1; if (parentNode.Children.Count > 0) { var lastFileName = Path.GetFileNameWithoutExtension( parentNode.Children.Last().Name); lastNo = int.Parse(lastFileName) + 1; } var newName = string.Format("{0:D3}.{1}", lastNo, ApplicationSettings.Instance.ImageFormat); parentNode.IsExpanded = true; newNode = new SnapTreeItem() { NodeFileType = SnapTreeItem.FileType.File, Name = newName, IsExpanded = false, Parent = parentNode }; parentNode.Children.Add(newNode); var outputpath = Path.Combine(outDir, newName); if (AutoResize) { var ins = ApplicationSettings.Instance; bmp = ImageHelper.Resize(bmp, ins.DefaultWidth, ins.DefaultHeight); } bmp.Save(outputpath); bmp.Dispose(); logger.Info(LogMessage.ISuccess, nameof(AddCapture)); return newNode; } private Bitmap GetCameraCapture() { if (webcam != null && webcam.IsRunning) return webcam.GetCapture(); throw new Exception(LogMessage.ECameraNotFound); } /// <summary>指定したノードを一覧から削除する</summary> /// <param name="selectedNode">対象ノード</param> /// <returns>削除対象の前、または親ノード</returns> internal SnapTreeItem RemoveTree(SnapTreeItem selectedNode) { SnapTreeItem nextNode = null; if (selectedNode.NodeFileType == SnapTreeItem.FileType.File) { var pnode = selectedNode.Parent; int findex = pnode.Children.IndexOf(selectedNode) - 1; var removeTarget = Path.Combine(OutputRoot, selectedNode.Parent.Name, selectedNode.Name); selectedNode.Parent.Children.Remove(selectedNode); if (File.Exists(removeTarget)) File.Delete(removeTarget); // 移動先ノード取得 if (findex >= 0) nextNode = pnode.Children[findex]; else nextNode = pnode; } else { int pindex = SnapShotTreeSource.IndexOf(selectedNode) - 1; var removeTarget = Path.Combine(OutputRoot, selectedNode.Name); SnapShotTreeSource.Remove(selectedNode); if (Directory.Exists(removeTarget)) Directory.Delete(removeTarget, true); UpdateLatestLevel(); // 移動先ノード取得 if (pindex >= 0) nextNode = SnapShotTreeSource[pindex]; } return nextNode; } private void UpdateLatestLevel() { if (SnapShotTreeSource.Count > 0) { var lastnode = SnapShotTreeSource.Last(); var matche = Regex.Matches(lastnode.Name, "[0-9+]"); levels.Clear(); foreach (var m in matche) { int newV = int.Parse(m.ToString()); levels.Add(newV); } levels.Reverse(); LevelToGroupName(); } else { LevelInit(); } } private void LevelInit() { var matche = Regex.Matches(ApplicationSettings.Instance.GroupPattern, "\\[n\\]"); levels.Clear(); foreach (var i in Enumerable.Range(0, matche.Count)) { levels.Add(1); } LevelToGroupName(); SnapShotTreeSource.Add(new SnapTreeItem() { NodeFileType = SnapTreeItem.FileType.Folder, Name = CurrentGroup, IsExpanded = true, Children = new ObservableCollection<SnapTreeItem>() }); } private void LevelToGroupName() { CurrentGroup = CommonUtility.GetGroupNameByLevels(levels); } /// <summary>ツリーにグループノードを追加する</summary> /// <param name="level">対象レベル(0から)</param> /// <returns>追加グループのノード</returns> internal SnapTreeItem AddGroupNode(int level = 0) { levels = CommonUtility.GetLevelsByStr(CurrentGroup); if (level > 0) { // 下位レベルをリセット foreach (int index in Enumerable.Range(0, level)) levels[index] = 1; } while (true) { levels[level]++; LevelToGroupName(); if (SnapShotTreeSource.ToList().Count(x => x.Name == CurrentGroup) == 0) break; } var newItem = new SnapTreeItem() { NodeFileType = SnapTreeItem.FileType.Folder, Name = CurrentGroup, IsExpanded = true, Children = new ObservableCollection<SnapTreeItem>() }; SnapShotTreeSource.Add(newItem); var sorted = SnapShotTreeSource.ToList(); sorted.Sort(); SnapShotTreeSource.Clear(); sorted.ForEach(x => SnapShotTreeSource.Add(x)); return newItem; } internal void Rename(SnapTreeItem oldNode, string newGroupName) { var sourcePath = Path.Combine(OutputRoot, oldNode.Name); var destPath = Path.Combine(OutputRoot, newGroupName); if (Directory.Exists(sourcePath)) { Directory.Move(sourcePath, destPath); } oldNode.Name = newGroupName; var sorted = SnapShotTreeSource.ToList(); sorted.Sort(); SnapShotTreeSource.Clear(); sorted.ForEach(x => SnapShotTreeSource.Add(x)); } private void RefreshTree() { SnapShotTreeSource.Clear(); if (Directory.Exists(OutputRoot)) { string matchestr = ApplicationSettings.Instance.GroupPattern; matchestr = matchestr.Replace("[n]", "[0-9]+"); var re = new Regex(matchestr); var fre = new Regex("[0-9]{3}.[png|jpg|bmp]"); var searchTargetDirs = Directory.EnumerateDirectories(OutputRoot); foreach (var parentDir in searchTargetDirs) { if (re.IsMatch(parentDir)) { var parentName = Path.GetFileName(parentDir); var parentNode = new SnapTreeItem() { NodeFileType = SnapTreeItem.FileType.Folder, Name = parentName, IsExpanded = false, Children = new ObservableCollection<SnapTreeItem>() }; SnapShotTreeSource.Add(parentNode); var searchTargetFiles = Directory.EnumerateFiles(parentDir); foreach (var file in searchTargetFiles) { var fileName = Path.GetFileName(file); if (fre.IsMatch(file)) { parentNode.Children.Add( new SnapTreeItem() { NodeFileType = SnapTreeItem.FileType.File, Name = fileName, IsExpanded = false, Parent = parentNode }); } } } } var sorted = SnapShotTreeSource.ToList(); sorted.Sort(); SnapShotTreeSource.Clear(); sorted.ForEach(x => SnapShotTreeSource.Add(x)); } } internal void CreateCamera() { webcam = new WebCamManager(); var targetDevice = ApplicationSettings.Instance.DefaultCamDevice; var dcs = webcam.GetDevices(); var deviceName = dcs.ToList().Find(x => x == targetDevice); if (deviceName != null) { webcam.SetDevice(deviceName); webcam.Start(); } else { throw new Exception(LogMessage.ECameraNotFound); } } internal void DisposeCamera() { if (webcam != null) { webcam.Dispose(); } } } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace GFT_ClubHouse__Management.Libs.ExtensionsMethods { public static class ModelStateExtension { public static List<string> ListErrors(this ModelStateDictionary modelstate) { return modelstate .Values.SelectMany(v => v.Errors) .Select(v => v.ErrorMessage + " " + v.Exception).ToList(); } } }
using System.Collections.Generic; using WePay.Shared; namespace WePay.Risk.Common { /// <summary> /// All possible Normalized Address Statuses currently supported by WePay /// </summary> public static class NormalizedAddressStatuses { /// <summary> /// Indices for Values property for iteration /// </summary> public enum ValuesIndices : int { UserConfirmed, UserDenied, UserDidNotReview } /// <summary> /// User reviewed and confirmed normalized address as correct /// </summary> public const string UserConfirmed = "user_confirmed"; /// <summary> /// User reviewed and indicated normalized address is not correct /// </summary> public const string UserDenied = "user_denied"; /// <summary> /// User was not shown the normalized address and asked to confirm or deny /// </summary> public const string UserDidNotReview = "user_did_not_review"; /// <summary> /// Holds all values for iteration /// </summary> public static readonly List<string> Values = new List<string>(); static NormalizedAddressStatuses() { WePayValues.FillValuesList(typeof(NormalizedAddressStatuses), Values); } } }
using System.Threading.Tasks; using Noise.RemoteServer.Protocol; namespace Noise.RemoteClient.Interfaces { interface IAlbumProvider { Task<AlbumListResponse> GetAlbumList( long artistId ); Task<AlbumListResponse> GetFavoriteAlbums(); Task<AlbumUpdateResponse> UpdateAlbumRatings( AlbumInfo album ); } }
using System; using System.Collections.Generic; using Autodesk.DesignScript.Runtime; namespace DynaShape.Goals { [IsVisibleInDynamoLibrary(false)] public class AngleGoal : Goal { public float TargetAngle = 0f; public AngleGoal(Triple A, Triple B, Triple C, float targetAngle, float weight = 1f) { Weight = weight; TargetAngle = targetAngle; StartingPositions = new[] { A, B, C }; Moves = new Triple[3]; Moves[1] = Triple.Zero; Weights = new float[3]; } public AngleGoal(Triple A, Triple B, Triple C, float weight = 1000f) { Weight = weight; StartingPositions = new[] { A, B, C }; Moves = new Triple[3]; Moves[1] = Triple.Zero; Triple BA = A - B; Triple BC = C - B; TargetAngle = (float)Math.Acos(BA.Dot(BC) / (BA.Length * BC.Length)); } public override void Compute(List<Node> allNodes) { Triple A = allNodes[NodeIndices[0]].Position; Triple B = allNodes[NodeIndices[1]].Position; Triple C = allNodes[NodeIndices[2]].Position; Triple BA = A - B; Triple BC = C - B; Triple m = (BA + BC).Normalise(); Triple N = BA.Cross(BC); if (N.IsAlmostZero()) N = Triple.BasisX; Triple mA = m.Rotate(Triple.Zero, N, -0.5f * TargetAngle); Triple mB = m.Rotate(Triple.Zero, N, +0.5f * TargetAngle); Moves[0] = B + m * mA.Dot(BA) - A; Moves[2] = B + m * mB.Dot(BC) - C; Weights[0] = Weights[1] = Weights[2] = Weight; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ExceptionLogger.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // </copyright> // <summary> // Defines the ExceptionLogger type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Sample.PolicyRecordingBot.FrontEnd.Http { using System.Threading; using System.Threading.Tasks; using System.Web.Http.ExceptionHandling; using Microsoft.Graph.Communications.Common.Telemetry; /// <summary> /// The exception logger. /// </summary> public class ExceptionLogger : IExceptionLogger { private IGraphLogger logger; /// <summary> /// Initializes a new instance of the <see cref="ExceptionLogger"/> class. /// </summary> /// <param name="logger">Graph logger.</param> public ExceptionLogger(IGraphLogger logger) { this.logger = logger; } /// <inheritdoc /> public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken) { this.logger.Error(context.Exception, "Exception processing HTTP request."); return Task.CompletedTask; } } }
//----------------------------------------------------------------------- // <copyright file="ISupportNavigation.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Interface that defines template that Navigatgor </summary> //----------------------------------------------------------------------- using System; namespace Csla.Xaml { /// <summary> /// Interface that defines template that Navigatgor /// control can understand. This interface should be /// implemented by controls that would rely on Navigator /// object to show them. /// </summary> public interface ISupportNavigation { /// <summary> /// This method is called by Navigatgor in order /// to pass parameters from a bookmark into /// the shown control /// </summary> /// <param name="parameters"> /// Parameters passed as string. Is is up to control /// to parse them /// </param> void SetParameters(string parameters); /// <summary> /// Get the title of the control /// </summary> string Title { get; } /// <summary> /// This event should be raised after the control is populated with data /// </summary> event EventHandler LoadCompleted; /// <summary> /// If set to false, bookamrk will be created as part of navigation. /// If set to true, bokmakr will be created when LoadCompleted /// event is raised by the control /// </summary> bool CreateBookmarkAfterLoadCompleted { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ErrorInfo : MonoBehaviour { public MidiInput midiinput; public GameObject error; // Use this for initialization void Start () { midiinput = this.GetComponent<MidiInput>(); error = GameObject.Find("error"); error.SetActive(false); } // Update is called once per frame void Update () { if(midiinput.pitch==0&&midiinput.volume==0) { error.SetActive(true); } if(midiinput.pitch!=0&&midiinput.volume!=0){ error.SetActive(false); } } }
using Zorbit.Features.Observatory.Core.Model; namespace Zorbit.Features.Observatory.Core.Indexing { public interface IIndexerTaskFactory { IIndexerTask CreateTask(IndexType indexType); } }
using System.Reflection; using System; using UnityEngine; public static class DebugHelper { //for debuging: public static string PrintGameMessage(GameMessage msg){ string output = ""; Type type = typeof(GameMessage); PropertyInfo[] properties = type.GetProperties(); /* if (properties.Length > 0) output+="Properties: "; */ foreach (PropertyInfo property in properties) { object val = property.GetValue(msg, null); if (val == null) continue; output += property.Name + "="; output += val + "; "; } FieldInfo[] fields = type.GetFields(); /* if (fields.Length > 0) output+="Fields: "; */ foreach (FieldInfo field in fields) { object val = field.GetValue(msg); ///var castedVec3 = val as Vector3;|| (val == Vector3.zero) if (val == null) continue; output += field.Name + "="; output += field.GetValue(msg) + "; "; } return output; } }
using CaptivePortalAssistant.Helpers; using CaptivePortalAssistant.Models; using CaptivePortalAssistant.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Windows.System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Navigation; namespace CaptivePortalAssistant.Views { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class WebViewPage : Page { private readonly DispatcherTimer _checkConnectTimer; private readonly SymbolIcon _symbolIconCancel = new SymbolIcon(Symbol.Cancel); private readonly SymbolIcon _symbolIconRefresh = new SymbolIcon(Symbol.Refresh); private Profile _profile; private string _currentSsid; private bool _protocolactivation; public WebViewPage() { InitializeComponent(); _checkConnectTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 5) }; _checkConnectTimer.Tick += CheckConnectTimerTick; } protected override async void OnNavigatedTo(NavigationEventArgs e) { if (e.Parameter is ProtocolActivatedEventArgs parameter) { MainWebView.Navigate(parameter.Uri); if (parameter.Uri.Query.Contains("defaultTest")) { _protocolactivation = false; var contentDialog = new ContentDialog { Title = "Association", Content = "Associated successfully.", CloseButtonText = "Ok" }; await contentDialog.ShowAsync(); } else { _protocolactivation = true; } } else if (MainWebView.Source == null) { MainWebView.Navigate(new Uri("http://www.msftconnecttest.com/connecttest.txt")); _protocolactivation = false; } } private async void Page_Loaded(object sender, RoutedEventArgs e) { CaptivePortalDetector.DefaultDetectionMethod = SettingsService.Instance.DetectionMethod; _currentSsid = await WifiInfo.GetSsid(); _profile = ProfilesService.Instance.ProfilesDbCollection.FindOne(x => x.Ssid == _currentSsid); _checkConnectTimer.Start(); UpdateButtonStates(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { _checkConnectTimer.Stop(); } private void MainWebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { AddressTextbox.Text = args.Uri.ToString(); RefreshStopButton.Icon = _symbolIconCancel; LoadingProgressBar.IsIndeterminate = true; UpdateButtonStates(); } private async void MainWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) { RefreshStopButton.Icon = _symbolIconRefresh; LoadingProgressBar.IsIndeterminate = false; UpdateButtonStates(); await CheckConnectivity(); if (_protocolactivation) { await Task.Delay(300); await AutoOpration(); } } private void BackButton_Click(object sender, RoutedEventArgs e) { if (MainWebView.CanGoBack) MainWebView.GoBack(); } private void ForwardButton_Click(object sender, RoutedEventArgs e) { if (MainWebView.CanGoForward) MainWebView.GoForward(); } private void RefreshStopButton_Click(object sender, RoutedEventArgs e) { if (LoadingProgressBar.IsIndeterminate) { MainWebView.Stop(); MainWebView_NavigationCompleted(null, null); } else { MainWebView.Refresh(); } } private void AddressTextbox_KeyDown(object sender, KeyRoutedEventArgs e) { if (e.Key != VirtualKey.Enter) return; var url = AddressTextbox.Text.Trim(); if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { url = "http://" + url; } if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) MainWebView.Navigate(new Uri(url)); } private void AddressTextbox_GotFocus(object sender, RoutedEventArgs e) { AddressTextbox.SelectAll(); } private void AddressTextbox_LostFocus(object sender, RoutedEventArgs e) { AddressTextbox.SelectionLength = 0; } private async void FillButton_Click(object sender, RoutedEventArgs e) { await InsertFillScript(false); } private async void LoginButton_Click(object sender, RoutedEventArgs e) { await InsertFillScript(true); } private async void SaveButton_Click(object sender, RoutedEventArgs e) { var result = await MainWebView.InvokeScriptAsync("eval", new[] { ScriptBuilder.GetSaveScript() }); List<List<ProfileField>> forms; try { forms = JsonConvert.DeserializeObject<List<List<ProfileField>>>(result, JsonStorage.GetJsonSerializerSettings()); } catch (JsonException) { await ShowDialog("Error", "Cannot save form."); return; } if (!forms.Any()) { await ShowDialog("Forms not found", "We didn't find any forms that can be saved."); return; } var newSSid = await WifiInfo.GetSsid(); if (!string.IsNullOrWhiteSpace(newSSid)) _currentSsid = newSSid; var saveFormContentDialog = new SaveFormContentDialog(_currentSsid, forms); await saveFormContentDialog.ShowAsync(); Page_Loaded(null, null); } private void SettingsButton_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(SettingsPage)); } private async Task CheckConnectivity() { if (_protocolactivation) { var isCaptivePortal = await CaptivePortalDetector.IsCaptivePortalAsync(); if (!isCaptivePortal) Application.Current.Exit(); } else if (!Frame.ForwardStack.Any()) { Frame.Navigate(typeof(SettingsPage)); } } private async void CheckConnectTimerTick(object sender, object e) { await CheckConnectivity(); } private async Task AutoOpration() { if (_profile == null) return; var automationOption = _profile.AutomationOption == AutomationOption.Global ? SettingsService.Instance.DefaultAutomationOption : _profile.AutomationOption; switch (automationOption) { case AutomationOption.Autologin: await InsertFillScript(true); break; case AutomationOption.Autofill: await InsertFillScript(false); break; } } private async Task InsertFillScript(bool isLoginEnabled) { if (_profile.Fields != null && _profile.Fields.Any()) { await MainWebView.InvokeScriptAsync("eval", new[] { ScriptBuilder.GetFillScript(_profile, isLoginEnabled) }); } } private void UpdateButtonStates() { if (LoadingProgressBar.IsIndeterminate) { FillButton.IsEnabled = LoginButton.IsEnabled = SaveButton.IsEnabled = false; } else { FillButton.IsEnabled = LoginButton.IsEnabled = _profile?.Fields != null; SaveButton.IsEnabled = true; } } private static async Task ShowDialog(string title, string content) { var contentDialog = new ContentDialog { Title = title, Content = content, CloseButtonText = "Ok" }; await contentDialog.ShowAsync(); } } }
using FastReport.Utils; using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Web; using FastReport.Web.Application.Localizations; using FastReport.Web.Controllers; namespace FastReport.Web { partial class WebReport { internal string template_HtmlExportSettings() { var localizationHtml = new HtmlExportSettingsLocalization(Res); var localizationPageSelector = new PageSelectorLocalization(Res); return $@" <div class=""modalcontainer modalcontainer--9"" data-target=""html""> <div class=""fr-webreport-popup-content-export-parameters""> <div class=""fr-webreport-popup-content-title""> {localizationHtml.Title} </div> <label>{localizationPageSelector.PageRange}</label> <div class=""fr-webreport-popup-content-export-parameters-row""> <button type=""button"" class=""fr-webreport-popup-content-export-parameters-button active"" name=""OnAllClick"" onclick=""OnAllClick()""> {localizationPageSelector.All} </button> <button type=""button"" class=""fr-webreport-popup-content-export-parameters-button"" name=""OnFirstClick"" onclick=""OnFirstClick()""> {localizationPageSelector.First} </button> <input name =""PageSelectorInput"" onchange=""OnInputClickHTML()""type=""text""class=""fr-webreport-popup-content-export-parameters-input"" pattern=""[0-9,-\s]"" placeholder=""2, 5-132""value="""" > </div> </div> <div class=""fr-webreport-popup-content-export-parameters""> <label>{localizationHtml.Options}</label> <div class=""fr-webreport-popup-content-export-parameters-row""> <div class=""fr-webreport-popup-content-export-parameters-col""> <button id=""HTMLWysiwyg"" type=""button"" class=""fr-webreport-popup-content-export-parameters-button active""> Wysiwyg </button> <button id=""HTMLPictures"" type=""button"" class=""fr-webreport-popup-content-export-parameters-button active""> {localizationHtml.Pictures} </button> </div> <div class=""fr-webreport-popup-content-export-parameters-col""> <button id=""HTMLSubFolder"" type=""button"" class=""fr-webreport-popup-content-export-parameters-button""> {localizationHtml.SubFolder} </button> <button id=""HTMLNavigator"" type=""button"" class=""fr-webreport-popup-content-export-parameters-button active""> {localizationHtml.Navigator} </button> <button id=""HTMLEmbeddingPictures"" type=""button"" class=""fr-webreport-popup-content-export-parameters-button active""> {localizationHtml.EmbPic} </button> </div> <div class=""fr-webreport-popup-content-export-parameters-col""> <button id=""HTMLSinglePage"" type=""button"" class=""fr-webreport-popup-content-export-parameters-button active""> {localizationHtml.SinglePage} </button> <button id=""HTMLLayers"" type=""button"" class=""fr-webreport-popup-content-export-parameters-button active""> {localizationHtml.Layers} </button> </div> </div> </div> <div class=""fr-webreport-popup-content-buttons""> <button class=""fr-webreport-popup-content-btn-submit"">{localizationPageSelector.LocalizedCancel}</button> <button class=""fr-webreport-popup-content-btn-submit"" onclick=""HTMLExport()"">OK</button> </div> </div> <script> {template_modalcontainerscript} //HTMLEXPORT// var HTMLButtons; var HTMLPictures = false; var HTMLSubFolder = false; var HTMLNavigator = false; var HTMLSinglePage = false; var HTMLLayers = false; var HTMLEmbeddingPictures = false; var HTMLWysiwyg = false; function OnInputClickHTML() {{ {template_pscustom} }} function HTMLExport() {{ if (document.getElementById('HTMLWysiwyg').classList.contains('active')) {{ HTMLWysiwyg = new Boolean(true); }} else {{ HTMLWysiwyg = false; }}; if (document.getElementById('HTMLPictures').classList.contains('active')) {{ HTMLPictures = new Boolean(true); }} else {{ HTMLPictures = false; }}; if (document.getElementById('HTMLSubFolder').classList.contains('active')) {{ HTMLSubFolder = new Boolean(true); }} else {{ HTMLSubFolder = false; }}; if (document.getElementById('HTMLNavigator').classList.contains('active')) {{ HTMLNavigator = new Boolean(true); }} else {{ HTMLNavigator = false; }}; if (document.getElementById('HTMLSinglePage').classList.contains('active')) {{ HTMLSinglePage = new Boolean(true); }} else {{ HTMLSinglePage = false; }}; if (document.getElementById('HTMLLayers').classList.contains('active')) {{ HTMLLayers = new Boolean(true); }} else {{ HTMLLayers = false; }}; if (document.getElementById('HTMLEmbeddingPictures').classList.contains('active')) {{ HTMLEmbeddingPictures = new Boolean(true); }} else {{ HTMLEmbeddingPictures = false; }}; HTMLButtons = ('&Navigator=' + HTMLNavigator + '&Wysiwyg=' + HTMLWysiwyg + '&Pictures=' + HTMLPictures + '&SinglePage=' + HTMLSinglePage + '&Layers=' + HTMLLayers + PageSelector + '&SubFolder=' + HTMLSubFolder + '&EmbedPictures=' + HTMLEmbeddingPictures); window.location.href = HtmlExport.href + HTMLButtons + PageSelector; }} </script> "; } } }
namespace Meadow.Foundation.Sensors.GPS { public class GSADecoder : NMEADecoder { #region Delegates and events /// <summary> /// Delegate for the GSA data received event. /// </summary> /// <param name="activeSatellites">Active satellites.</param> /// <param name="sender">Reference to the object generating the event.</param> public delegate void ActiveSatellitesReceived(object sender, ActiveSatellites activeSatellites); /// <summary> /// Event raised when valid GSA data is received. /// </summary> public event ActiveSatellitesReceived OnActiveSatellitesReceived; #endregion Delegates and events #region INMEADecoder methods & properties /// <summary> /// Prefix for the GSA decoder. /// </summary> public override string Prefix { get { return "$GPGSA"; } } /// <summary> /// Friendly name for the GSA messages. /// </summary> public override string Name { get { return "GSA - DOP and number of active satellites."; } } /// <summary> /// Process the data from a GSA message. /// </summary> /// <param name="data">String array of the message components for a GSA message.</param> public override void Process(string[] data) { if (OnActiveSatellitesReceived != null) { var satellites = new ActiveSatellites(); switch (data[1].ToLower()) { case "a": satellites.SatelliteSelection = ActiveSatelliteSelection.Automatic; break; case "m": satellites.SatelliteSelection = ActiveSatelliteSelection.Manual; break; default: satellites.SatelliteSelection = ActiveSatelliteSelection.Unknown; break; } satellites.Demensions = (DimensionalFixType) int.Parse(data[2]); var satelliteCount = 0; for (var index = 3; index < 15; index++) { if ((data[index] != null) && (data[index] != "")) { satelliteCount++; } } if (satelliteCount > 0) { satellites.SatellitesUsedForFix = new string[satelliteCount]; var currentSatellite = 0; for (var index = 3; index < 15; index++) { if ((data[index] != null) && (data[index] != "")) { satellites.SatellitesUsedForFix[currentSatellite] = data[index]; currentSatellite++; } } } else { satellites.SatellitesUsedForFix = null; } satellites.DilutionOfPrecision = double.Parse(data[15]); satellites.HorizontalDilutionOfPrecision = double.Parse(data[16]); satellites.VerticalDilutionOfPrecision = double.Parse(data[17]); OnActiveSatellitesReceived(this, satellites); } } #endregion NMEADecoder methods & properties } }
using System; using System.Threading.Tasks; using R5T.T0064; namespace R5T.D1001.D001.I001 { [ServiceImplementationMarker] public class ServiceA : IServiceA, IServiceImplementation { private IServiceZ ServiceZ { get; } public ServiceA( IServiceZ serviceZ) { this.ServiceZ = serviceZ; } public async Task RunA() { await this.ServiceZ.RunZ(); Console.WriteLine("Ran A."); Console.WriteLine(); } } }
using System; using System.Globalization; using System.IO; using System.Reflection; using Mix.Attributes; namespace Mix.Commands { [Description("Shows the version of this application.")] public class VersionCommand : Command { public override int Execute() { WriteVersion(); WriteCompilationDate(); WriteCopyright(); return 0; } private void WriteVersion() { var assembly = Assembly.GetExecutingAssembly(); var name = assembly.GetName(); var version = name.Version; WriteLine("Mix, version {0}", version); } private void WriteCompilationDate() { FileInfo fileInfo; try { fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location); } catch (Exception) { return; } if (fileInfo.Exists) { DateTime date; try { date = fileInfo.LastWriteTime; } catch (Exception) { return; } var ci = new CultureInfo("en-US"); WriteLine(" compiled {0}", date.ToString("MMMM %d yyyy, HH:mm:ss", ci)); Write(Environment.NewLine); } } private void WriteCopyright() { WriteLine("Copyright (C) 2006-2013 Richard Hubers."); WriteLine("Mix is open source software, see http://rh.github.com/mix/"); } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleEssentials.ToQuery { public class QueryObject : IQueryObject { public string Query { get; set; } public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>(); public IQueryObject IsQuery(string query) { return new QueryObject() { Parameters = new Dictionary<string, object>(), Query = query }; } public void IsParameter(object value) { var count = Parameters.Count + 1; this.Parameters.Add(count.ToString(), value); this.Query += $"@{count}"; } public IQueryObject IsCollection(ref int countStart, IEnumerable values) { var parameters = new Dictionary<string, object>(); var query = new StringBuilder("("); foreach (var value in values) { parameters.Add((countStart).ToString(), value); query.Append($"@{countStart},"); countStart++; } if (query.Length == 1) { query.Append("null,"); } query[query.Length - 1] = ')'; return new QueryObject() { Parameters = parameters, Query = query.ToString() }; } public void Concat(string message) { this.Query += $"{message}"; } public IQueryObject Concat(IQueryObject left, string @operator, IQueryObject right) { return new QueryObject() { Parameters = left.Parameters.Union(right.Parameters).ToDictionary(kvp => kvp.Key, kvp => kvp.Value), Query = $"({left.Query} {@operator} {right.Query})" }; } } }
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Moq; // ReSharper disable UnusedMember.Global namespace DevOpsTools.UnitTests { public static class TestHelper { // ReSharper disable once InconsistentNaming public const string RealOrganization = "upmcappsvcs"; // ReSharper disable once InconsistentNaming public const string RealProject = "Apollo"; public static Guid FakeProjectId = Guid.NewGuid(); public static Guid RealProjectId = Guid.Parse("f39ff6aa-3b5f-41f1-ba61-e4a72a4a0d13"); public static Mock<IClient> SetUpMockClient() { var clientMock = new Mock<IClient>(); clientMock.Setup(x => x.AddHeaders()); clientMock.Setup(x => x .DeleteAsync(It.IsAny<Uri>())) .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK))); clientMock.Setup(x => x .GetStringAsync(It.IsAny<Uri>())) .Returns(Task.FromResult("result")); clientMock.Setup(x => x .PostStringAsync(It.IsAny<Uri>(), It.IsAny<string>())) .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK))); clientMock.Setup(x => x .PutStringAsync(It.IsAny<Uri>(), It.IsAny<string>())) .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK))); return clientMock; } } }
namespace IcyRain.Resolvers { internal enum ResolverType { Default, Union, UnionByte, UnionUShort, } }
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using System.Windows.Forms; using NEATNeuralNetwork; namespace NEATNeuralNetwork { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Genus pool = new Genus(2, 1); Random r = new Random(); private void Form1_Load(object sender, EventArgs e) { Genus pool = new Genus(2, 1); //Genome p1 = new Genome(); //p1.BuildNode(NodeGene.NodeType.INPUT_NODE, 1); //p1.BuildNode(NodeGene.NodeType.INPUT_NODE, 2); //p1.BuildNode(NodeGene.NodeType.INPUT_NODE, 3); //p1.BuildNode(NodeGene.NodeType.OUTPUT_NODE, 4); //p1.BuildNode(NodeGene.NodeType.HIDDEN_NODE, 5); //p1.BuildConnection(1, 4, 1, true); //p1.BuildConnection(1, 5, 1, true); //p1.BuildConnection(3, 4, 1, true); //p1.BuildConnection(2, 5, 1, true); //p1.BuildConnection(5, 4, 1, true); //Genome p2 = p1.Crossover(p1); //p2.Mutate(); //Genome child = p1.Crossover(p2); //DrawGenome(forceGraphVisualizer1, p1); //DrawGenome(forceGraphVisualizer2, p2); //DrawGenome(forceGraphVisualizer3, child); //Species s = new Species(); //s.AddGenome(p1); //s.AddGenome(p2); //s.AddGenome(child); } private void DrawGenome(ForceDirected.ForceGraphVisualizer graph, Genome genome) { graph.ClearGraph(); foreach(KeyValuePair<int, NodeGene> node in genome.Nodes) { graph.AddNode(node.Value.Innovation, Color.White); } foreach (KeyValuePair<int, ConnectionGene> connection in genome.Connections) { graph.AddEdge(connection.Value.InNode, connection.Value.OutNode); } } private void button1_Click(object sender, EventArgs e) { for (int j = 0; j < 100; j++) { pool.NewGeneration(); foreach (Genome g in pool.Genomes()) { double averageScore = 0; for (int i = 0; i < 2000; i++) { int a = r.Next(0, 2); int b = r.Next(0, 2); float c = a ^ b; double[] outputs = g.Evaluate(new double[] { a, b }); averageScore += Math.Abs(c - outputs[0]); } if (averageScore == 0) // perfect score averageScore = double.MaxValue; else averageScore = 1 / averageScore; g.Fitness = averageScore; } } Genome best = pool.BestGenome(); textBoxFitness.Text = best.Fitness.ToString(); DrawGenome(forceGraphVisualizer1, best); } private void textBoxFitness_TextChanged(object sender, EventArgs e) { } } }
//********************************************************************************** //* Copyright (C) 2007,2016 Hitachi Solutions,Ltd. //********************************************************************************** #region Apache License // // 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 //********************************************************************************** //* クラス名 :WinCustomMaskedTextBoxDgvCell //* クラス日本語名 :DataGridViewのWinCustomMaskedTextBoxセル(テンプレート) //* //* 作成者 :生技 西野 //* 更新履歴 : //* //* 日時 更新者 内容 //* ---------- ---------------- ------------------------------------------------- //* 20xx/xx/xx XX XX 新規作成(テンプレート) //********************************************************************************** using System; using System.Windows.Forms; namespace Touryo.Infrastructure.CustomControl.RichClient { /// <summary>DataGridViewのWinCustomMaskedTextBoxセル</summary> public class WinCustomMaskedTextBoxDgvCell : DataGridViewTextBoxCell { /// <summary>コンストラクタ</summary> public WinCustomMaskedTextBoxDgvCell() : base() { } /// <summary>編集コントロールを初期化</summary> /// <param name="rowIndex">行</param> /// <param name="initialFormattedValue">フォーマットバリュー</param> /// <param name="dataGridViewCellStyle">セル スタイル</param> public override void InitializeEditingControl( int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { //System.Diagnostics.Debug.WriteLine("InitializeEditingControl"); //System.Diagnostics.Debug.WriteLine("・rowIndex:" + rowIndex); // ベースへ。 base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); // 編集コントロールであるWinCustomMaskedTextBoxDgvHostの取得 WinCustomMaskedTextBoxDgvHost winCustomMaskedTextBoxDgvHost = this.DataGridView.EditingControl as WinCustomMaskedTextBoxDgvHost; // 編集コントロールであるWinCustomMaskedTextBoxDgvHostが取得できた場合 if (winCustomMaskedTextBoxDgvHost != null) { // カスタム列のプロパティを反映させる WinCustomMaskedTextBoxDgvCol column = this.OwningColumn as WinCustomMaskedTextBoxDgvCol; // プロパティの移植 if (column != null) { // 追加したプロパティをコピー // チェック系は不要、編集系を設定 winCustomMaskedTextBoxDgvHost.EditInitialValue = column.EditInitialValue; winCustomMaskedTextBoxDgvHost.Mask = column.Mask; winCustomMaskedTextBoxDgvHost.Mask_Editing = column.Mask_Editing; winCustomMaskedTextBoxDgvHost.EditToHankaku = column.EditToHankaku; winCustomMaskedTextBoxDgvHost.EditToYYYYMMDD = column.EditToYYYYMMDD; } //try //{ // Textを設定(3項演算) //System.Diagnostics.Debug.WriteLine("InitializeEditingControl"); //System.Diagnostics.Debug.WriteLine("・this.RowIndex:" + this.RowIndex.ToString()); // DataGridView で DateTimePicker をホストすると ArgumentOutOfException が発生する //http://social.msdn.microsoft.com/Forums/ja-JP/7079fb1c-d171-44f8-81b1-751f3fe1ba6f/datagridview-datetimepicker-argumentoutofexception- //winCustomMaskedTextBoxDgvHost.Text = // this.Value == null ? "" : this.Value.ToString(); winCustomMaskedTextBoxDgvHost.Text = this.GetValue(rowIndex) == null ? "" : this.GetValue(rowIndex).ToString(); //} //catch (ArgumentOutOfRangeException aoorEx) //{ // // この例外は潰す。 //} } } /// <summary>編集コントロールの型を指定する</summary> public override Type EditType { get { return typeof(WinCustomMaskedTextBoxDgvHost); } } ///// <summary>セルの値のデータ型を指定する。</summary> ///// <remarks>ここでは、Object型とする。基本クラスと同じなので、オーバーライドの必要なし</remarks> //public override Type ValueType //{ // get // { // return typeof(object); // } //} /// <summary>新しいレコード行のセルの既定値を指定する</summary> public override object DefaultNewRowValue { get { // ベースへ。 return base.DefaultNewRowValue; } } } }
using Moq; namespace HotelCalifornia.Tests.RepositoryFacts { public class Reservation { public class CreateReservation { public void WillThrowIfRoomIsNotAvailable() { var repository = new Mock<IReservationRepository>(); } } } }
namespace Fidectus.Models { public class PipelineDetails { public DeliverableByBarge DeliverableByBarge { get; set; } public EntryPoint EntryPoint { get; set; } public IncoTerms IncoTerms { get; set; } public PipelineName PipelineName { get; set; } public PipelineCycles PipelineCycles { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIItemDemandController : MonoBehaviour { private Image panel; private Text text; private ItemController item; private ItemController.ItemType demand; private Color originalColor; // Start is called before the first frame update void Start() { panel = GetComponent<Image>(); text = GetComponentInChildren<Text>(); originalColor = panel.color; GameObject itemPrefab = Resources.Load<GameObject>("Prefabs/Item"); item = itemPrefab.GetComponent<ItemController>(); demand = ItemController.ItemType.NONE; EventBus.OnItemDemand += onItemDemand; } void OnDestroy() { EventBus.OnItemDemand -= onItemDemand; } // Update is called once per frame void Update() { if (demand != ItemController.ItemType.NONE) { item.type = demand; panel.color = item.getColor(); text.text = item.getSymbol(); } else { panel.color = originalColor; text.text = ""; } } void onItemDemand(ItemController.ItemType type) { demand = type; } }
using FlowMock.Engine.Models.Trigger; using System.Collections.Generic; using System.Threading.Tasks; namespace FlowMock.Engine.Models.Rules { public abstract class NodeBase : INode { protected Element _element; public NodeBase(Element element) { _element = element; Id = element?.Id; Connectors = new List<Connector>(); } public string Id { get; set; } public IList<Connector> Connectors { get; set; } public abstract Task<INode> GetNextNodeAsync(MockContext context); } }
using System.Collections.Generic; namespace TuFactura.co.Modelo { public class Suscriptor { public string Tipo { get; set; } public string CodigoTipo { get; set; } public string RazonSocial { get; set; } public string NombreComercial { get; set; } public string Documento { get; set; } public string Div { get; set; } public string Id { get; set; } public string Direccion { get; set; } public string CodigoDepartamento { get; set; } public string Departamento { get; set; } public string CodigoCiudad { get; set; } public string Ciudad { get; set; } public string CodigoPais { get; set; } public string CodigoArea { get; set; } public string GenerarPdf { get; set; } public string ServicioIntegrador { get; set; } public string ServicioFacturar { get; set; } public List<Resoluciones> Resoluciones { get; set; } public Suscriptor() { Resoluciones = new List<Resoluciones>(); } // } }
using UnityEngine; using UnityEngine.Rendering; using System.Collections; #pragma warning disable 162 using ImprovedPerlinNoiseProject; namespace MarchingCubesGPUProject { public class MarchingCubesGPU_4DNoise : MonoBehaviour { //The size of the voxel array for each dimension const int N = 40; //The size of the buffer that holds the verts. //This is the maximum number of verts that the //marching cube can produce, 5 triangles for each voxel. const int SIZE = N * N * N * 3 * 5; public int m_seed; public float m_speed = 2.0f; public Material m_drawBuffer; public ComputeShader m_perlinNoise; public ComputeShader m_marchingCubes; public ComputeShader m_normals; public ComputeShader m_clearBuffer; ComputeBuffer m_noiseBuffer, m_meshBuffer; RenderTexture m_normalsBuffer; ComputeBuffer m_cubeEdgeFlags, m_triangleConnectionTable; GPUPerlinNoise perlin; void Start() { //There are 8 threads run per group so N must be divisible by 8. if (N % 8 != 0) throw new System.ArgumentException("N must be divisible by 8"); //Holds the voxel values, generated from perlin noise. m_noiseBuffer = new ComputeBuffer(N * N * N, sizeof(float)); //Holds the normals of the voxels. m_normalsBuffer = new RenderTexture(N, N, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); m_normalsBuffer.dimension = TextureDimension.Tex3D; m_normalsBuffer.enableRandomWrite = true; m_normalsBuffer.useMipMap = false; m_normalsBuffer.volumeDepth = N; m_normalsBuffer.Create(); //Holds the verts generated by the marching cubes. m_meshBuffer = new ComputeBuffer(SIZE, sizeof(float) * 7); //These two buffers are just some settings needed by the marching cubes. m_cubeEdgeFlags = new ComputeBuffer(256, sizeof(int)); m_cubeEdgeFlags.SetData(MarchingCubesTables.CubeEdgeFlags); m_triangleConnectionTable = new ComputeBuffer(256 * 16, sizeof(int)); m_triangleConnectionTable.SetData(MarchingCubesTables.TriangleConnectionTable); //Make the perlin noise, make sure to load resources to match shader used. perlin = new GPUPerlinNoise(m_seed); perlin.LoadResourcesFor4DNoise(); } void Update() { //Clear the buffer from last frame. m_clearBuffer.SetInt("_Width", N); m_clearBuffer.SetInt("_Height", N); m_clearBuffer.SetInt("_Depth", N); m_clearBuffer.SetBuffer(0, "_Buffer", m_meshBuffer); m_clearBuffer.Dispatch(0, N / 8, N / 8, N / 8); //Make the voxels. m_perlinNoise.SetInt("_Width", N); m_perlinNoise.SetInt("_Height", N); m_perlinNoise.SetFloat("_Frequency", 0.02f); m_perlinNoise.SetFloat("_Lacunarity", 2.0f); m_perlinNoise.SetFloat("_Gain", 0.5f); m_perlinNoise.SetFloat("_Time", Time.realtimeSinceStartup * m_speed); m_perlinNoise.SetTexture(0, "_PermTable1D", perlin.PermutationTable1D); m_perlinNoise.SetTexture(0, "_PermTable2D", perlin.PermutationTable2D); m_perlinNoise.SetTexture(0, "_Gradient4D", perlin.Gradient4D); m_perlinNoise.SetBuffer(0, "_Result", m_noiseBuffer); m_perlinNoise.Dispatch(0, N / 8, N / 8, N / 8); //Make the voxel normals. m_normals.SetInt("_Width", N); m_normals.SetInt("_Height", N); m_normals.SetBuffer(0, "_Noise", m_noiseBuffer); m_normals.SetTexture(0, "_Result", m_normalsBuffer); m_normals.Dispatch(0, N / 8, N / 8, N / 8); //Make the mesh verts m_marchingCubes.SetInt("_Width", N); m_marchingCubes.SetInt("_Height", N); m_marchingCubes.SetInt("_Depth", N); m_marchingCubes.SetInt("_Border", 1); m_marchingCubes.SetFloat("_Target", 0.0f); m_marchingCubes.SetBuffer(0, "_Voxels", m_noiseBuffer); m_marchingCubes.SetTexture(0, "_Normals", m_normalsBuffer); m_marchingCubes.SetBuffer(0, "_Buffer", m_meshBuffer); m_marchingCubes.SetBuffer(0, "_CubeEdgeFlags", m_cubeEdgeFlags); m_marchingCubes.SetBuffer(0, "_TriangleConnectionTable", m_triangleConnectionTable); m_marchingCubes.Dispatch(0, N / 8, N / 8, N / 8); } /// <summary> /// Draws the mesh. /// </summary> /// <param name="camera"></param> void OnRenderObject() { //Since mesh is in a buffer need to use DrawProcedual called from OnPostRender or OnRenderObject m_drawBuffer.SetBuffer("_Buffer", m_meshBuffer); m_drawBuffer.SetMatrix("_ModelMatrix", transform.localToWorldMatrix); m_drawBuffer.SetPass(0); Graphics.DrawProceduralNow(MeshTopology.Triangles, SIZE); } void OnDestroy() { //MUST release buffers. m_noiseBuffer.Release(); m_meshBuffer.Release(); m_cubeEdgeFlags.Release(); m_triangleConnectionTable.Release(); m_normalsBuffer.Release(); } } }
using System; using System.Drawing; using System.Media; using System.Threading; using System.Windows.Forms; namespace JRunner.Panels { public partial class NandTools : UserControl { public NandTools() { InitializeComponent(); } public int getNumericIterations() { return (int)numericIterations.Value; } public void setNumericIterations(decimal value) { numericIterations.Value = value; } public void setbtnCreateECC(string text) { btnCreateECC.Text = text; } public void setbtnWriteECC(string text) { btnWriteECC.Text = text; } public string getbtnWriteECC() { return btnWriteECC.Text; } public void setImage(Image m) { pBoxDevice.Image = m; } public delegate void ClickedRead(); public event ClickedRead ReadClick; public delegate void ClickedCreateECC(); public event ClickedCreateECC CreateEccClick; public delegate void ClickedWriteECC(); public event ClickedWriteECC WriteEccClick; public delegate void ClickedXeBuild(); public event ClickedXeBuild XeBuildClick; public delegate void ClickedWrite(); public event ClickedWrite WriteClick; public delegate void ClickedProgramCR(); public event ClickedProgramCR ProgramCRClick; public delegate void ClickedCPUDB(); public event ClickedCPUDB CPUDBClick; public delegate void ChangedIter(int iter); public event ChangedIter IterChange; private void btnRead_Click(object sender, EventArgs e) { ReadClick(); } private void btnCreateECC_Click(object sender, EventArgs e) { CreateEccClick(); } private void btnWriteECC_Click(object sender, EventArgs e) { WriteEccClick(); } private void btnXeBuild_Click(object sender, EventArgs e) { XeBuildClick(); } private void btnWrite_Click(object sender, EventArgs e) { WriteClick(); } private void btnProgramCR_Click(object sender, EventArgs e) { ProgramCRClick(); } private void numericIterations_ValueChanged(object sender, EventArgs e) { IterChange((int)numericIterations.Value); } private void btnExtractFiles_Click(object sender, EventArgs e) { MainForm.mainForm.extractFilesFromNand(); } private void btnCreateDonor_Click(object sender, EventArgs e) { MainForm.mainForm.createDonorNand(); } private void btnCPUDB_Click(object sender, EventArgs e) { CPUDBClick(); } private int funCount = 0; private void pBoxDevice_Click(object sender, EventArgs e) { if (funCount == 5) { MessageBox.Show("Wtf are you doing!?!?!", "Confusion!", MessageBoxButtons.OK, MessageBoxIcon.Question); } else if (funCount == 8) { MessageBox.Show("#%&@ Stop doing that!!!!!", "#%&@", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (funCount == 10) { MessageBox.Show("Cut that shit out!!!!!", "You're Annoying!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (funCount == 12) { MessageBox.Show("CLICK ME AGAIN!\nI DARE YOU!", "You Gon Get It", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (funCount == 13) { SoundPlayer goodbye = new SoundPlayer(Properties.Resources.goodbye); goodbye.Play(); Thread.Sleep(1000); Application.Exit(); } funCount += 1; } } }
using BankUserAccountManagmentDAL.Constants; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace BankUserAccountManagementApplication.ValidationAttributes { public class ExceedMaxValueValidationAttribute : ValidationAttribute { public ExceedMaxValueValidationAttribute(string otherProperty) : base("{0} must be less than or equal to {1}") { OtherProperty = otherProperty; } public string OtherProperty { get; set; } public string FormatErrorMessage(string name, string otherName) { return string.Format(ErrorMessageString, name, otherName); } protected override ValidationResult IsValid(object firstValue, ValidationContext validationContext) { var firstDecimalValue = firstValue as decimal?; var secondDecimalValue = GetSecondAmount(validationContext); if (firstDecimalValue != null && secondDecimalValue != null) { if ((firstDecimalValue + secondDecimalValue) > (decimal)AmountConstants.MaxAmount) { object obj = validationContext.ObjectInstance; var thing = obj.GetType().GetProperty(OtherProperty); var displayName = thing.GetCustomAttribute<DisplayAttribute>(true); string errorMessage = validationContext.DisplayName + " and " + displayName; return new ValidationResult( FormatErrorMessage(errorMessage, AmountConstants.MaxAmount.ToString())); } } return ValidationResult.Success; } protected decimal? GetSecondAmount( ValidationContext validationContext) { var propertyInfo = validationContext .ObjectType .GetProperty(OtherProperty); if (propertyInfo != null) { var secondValue = propertyInfo.GetValue( validationContext.ObjectInstance, null); return secondValue as decimal?; } return null; } } }
//--------------------------------------------------------------------- // <copyright file="IODataStreamListener.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData { #region Namespaces using System.Threading.Tasks; #endregion /// <summary> /// An interface that allows creators of a stream to listen for status changes /// of the operation stream. /// </summary> internal interface IODataStreamListener { /// <summary> /// This method notifies the implementer of this interface that the content stream for a batch operation has been requested. /// </summary> void StreamRequested(); /// <summary> /// This method notifies the implementer of this interface that the content stream for a batch operation has been requested. /// </summary> /// <returns> /// A task representing any async operation that is running in reaction to the /// status change (or null if no such action is required). /// </returns> Task StreamRequestedAsync(); /// <summary> /// This method notifies the implementer of this interface that the content stream of a batch operation has been disposed. /// </summary> void StreamDisposed(); /// <summary> /// Asynchronously notifies the implementer of this interface that the content stream of an operation has been disposed. /// </summary> /// <returns>A task that represents the asynchronous operation.</returns> Task StreamDisposedAsync(); } }
using UnityEngine; namespace pdxpartyparrot.Core.Effects.EffectTriggerComponents { public class CompareFloatEffectTriggerComponent : EffectTriggerComponent { [SerializeField] private string _name; [SerializeField] private float _value; [SerializeField] private EffectTrigger _true; [SerializeField] private EffectTrigger _false; public override bool WaitForComplete => false; public override void OnStart() { float value = Owner.GetFloat(_name); if(Mathf.Approximately(value, _value)) { _true.Trigger(); } else { _false.Trigger(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class EditorUtils : Editor { private bool Change = false; private bool BoolField(ref bool Property, string LabelText) { bool Temp = Property; EditorGUILayout.BeginHorizontal(); GUILayout.Label(LabelText, GUILayout.Width(250)); Property = EditorGUILayout.Toggle("", Property); EditorGUILayout.EndHorizontal(); if (Temp != Property) return true; return false; } private bool ColorField(ref Color Property, string LabelText) { Color TempColor = Property; EditorGUILayout.BeginHorizontal(); GUILayout.Label(LabelText, GUILayout.Width(130)); Property = EditorGUILayout.ColorField(Property); EditorGUILayout.EndHorizontal(); if (!TempColor.Equals(Property)) return true; return false; } private bool TextField(ref string Property, string LabelText) { string TempString = Property; EditorGUILayout.BeginHorizontal(); GUILayout.Label(LabelText, GUILayout.Width(130)); Property = EditorGUILayout.TextField(Property); EditorGUILayout.EndHorizontal(); if (!TempString.Equals(Property)) return true; return false; } }
using System; using System.Windows.Controls; using System.Windows.Threading; namespace GitHub.UI.Login { public partial class Login2FaView : UserControl { public Login2FaView() { InitializeComponent(); IsVisibleChanged += (s, e) => { if (IsVisible) { Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() => SetFocus())); } }; } /// <summary> /// The DataContext of this view as a Login2FaView. /// </summary> public Login2FaViewModel ViewModel => DataContext as Login2FaViewModel; void SetFocus() { authenticationCode.SetFocus(); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Text; namespace Bartok.MSIL { public class SignatureMethod: Signature { // Constructor Methods internal SignatureMethod(CallingConventions callingConvention, uint genericParameterCount, Type returnType, Param[] parameters, int sentinelLocation) { this.callingConvention = callingConvention; this.genericParameterCount = genericParameterCount; this.returnType = returnType; this.parameters = parameters; this.sentinelLocation = sentinelLocation; } // Access Methods public CallingConventions CallingConvention { get { return callingConvention; } } public uint GenericParameterCount { get { return genericParameterCount; } } public Type ReturnType { get { return returnType; } } public Param[] Parameters { get { return parameters; } } public int SentinelLocation { get { return sentinelLocation; } } // other handy methods public bool HasThis { get { return ((((int)callingConvention) & ((int)Signature.CallingConventions.HasThis)) != 0); } } public bool ExplicitThis { get { return ((((int)callingConvention) & ((int)Signature.CallingConventions.ExplicitThis)) != 0); } } public bool NoThis { get { return !(HasThis || ExplicitThis); } } // Debug Methods public override String ToString() { StringBuilder sb = new StringBuilder("SignatureMethod("); sb.Append(((uint) callingConvention).ToString("x")); sb.Append(","); sb.Append(genericParameterCount); sb.Append(","); sb.Append(returnType); sb.Append(","); sb.Append("parameters("); if (parameters.Length > 0) { sb.Append(parameters[0]); for (int i = 1; i < parameters.Length; i++) { sb.Append(","); sb.Append(parameters[i]); } } sb.Append("),"); sb.Append(sentinelLocation); sb.Append(")"); return sb.ToString(); } // State private readonly CallingConventions callingConvention; private readonly uint genericParameterCount; private readonly Type returnType; private readonly Param[] parameters; private readonly int sentinelLocation; } }
using System.Collections.Generic; using NSubstitute; using Visma.Sign.Api.Client.Settings; namespace Visma.Sign.Api.Client.UnitTests.Builders.Settings { sealed class ScopesStubBuilder { private List<string> m_required = new List<string>(); public ScopesStubBuilder WithRequired(params string[] value) { m_required.AddRange(value); return this; } public IScopes Build() { var stub = Substitute.For<IScopes>(); stub.Required().Returns(m_required); return stub; } } }
// Copyright (c) Rapid Software LLC. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Scada.Comm.Channels; using Scada.Comm.Config; using Scada.Forms; using System; using System.IO.Ports; using System.Windows.Forms; namespace Scada.Comm.Drivers.DrvCnlBasic.View.Forms { /// <summary> /// Represents a form for editing serial port options. /// <para>Представляет форму для редактирования параметров последовательного порта.</para> /// </summary> internal partial class FrmSerialPortChannelOptions : Form { private readonly ChannelConfig channelConfig; // the communication channel configuration private readonly SerialPortChannelOptions options; // the communication channel options /// <summary> /// Initializes a new instance of the class. /// </summary> private FrmSerialPortChannelOptions() { InitializeComponent(); } /// <summary> /// Initializes a new instance of the class. /// </summary> public FrmSerialPortChannelOptions(ChannelConfig channelConfig) : this() { this.channelConfig = channelConfig ?? throw new ArgumentNullException(nameof(channelConfig)); options = new SerialPortChannelOptions(channelConfig.CustomOptions); } /// <summary> /// Sets the controls according to the options. /// </summary> private void OptionsToControls() { cbPortName.Text = options.PortName; cbBaudRate.Text = options.BaudRate.ToString(); cbDataBits.Text = options.DataBits.ToString(); cbParity.SelectedIndex = (int)options.Parity; cbStopBits.SelectedIndex = (int)options.StopBits - 1; chkDtrEnable.Checked = options.DtrEnable; chkRtsEnable.Checked = options.RtsEnable; cbBehavior.SelectedIndex = (int)options.Behavior; } /// <summary> /// Sets the options according to the controls. /// </summary> private void ControlsToOptions() { options.PortName = cbPortName.Text; if (int.TryParse(cbBaudRate.Text, out int baudRate)) options.BaudRate = baudRate; if (int.TryParse(cbDataBits.Text, out int dataBits)) options.DataBits = dataBits; options.Parity = (Parity)cbParity.SelectedIndex; options.StopBits = (StopBits)(cbStopBits.SelectedIndex + 1); options.DtrEnable = chkDtrEnable.Checked; options.RtsEnable = chkRtsEnable.Checked; options.Behavior = (ChannelBehavior)cbBehavior.SelectedIndex; options.AddToOptionList(channelConfig.CustomOptions); } private void FrmCommSerialProps_Load(object sender, EventArgs e) { FormTranslator.Translate(this, GetType().FullName); OptionsToControls(); } private void btnOK_Click(object sender, EventArgs e) { ControlsToOptions(); DialogResult = DialogResult.OK; } } }
using MongoDB.Bson; using System.Collections.Generic; namespace Network.NetTools { /// <summary> /// A basic structure defining a 2D Position with <see cref="int"/> variables /// </summary> public class Point { /// <summary> /// The X position /// </summary> public int x { get; set; } /// <summary> /// The X position /// </summary> public int y { get; set; } /// <summary> /// Constructor of <see cref="Point"/> /// </summary> public Point() { x = 0; y = 0; } } /// <summary> /// Defines the data stored in an <see cref="ANode"/> /// </summary> public class ANodeData { /// <summary> /// The <see cref="ANode"/>'s name /// </summary> public string name { get; set; } /// <summary> /// The <see cref="ANode"/>'s service name /// </summary> public string serviceName { get; set; } /// <summary> /// The <see cref="ANode"/>'s event name /// </summary> public string eventName { get; set; } /// <summary> /// The <see cref="ANode"/>'s position in the canvas /// </summary> public Point pos { get; set; } /// <summary> /// The <see cref="ANode"/>'s type ("action" or "reaction") /// </summary> public string type { get; set; } /// <summary> /// Constructor of the <see cref="ANodeData"/> /// </summary> public ANodeData() { name = ""; serviceName = ""; eventName = ""; pos = new Point(); type = ""; } } /// <summary> /// Defines a node in the AREA's tree structure /// </summary> public class ANode { /// <summary> /// The data contained in the <see cref="ANode"/> /// </summary> public ANodeData data { get; set; } /// <summary> /// A list of the <see cref="ANode"/> children /// </summary> public List<ANode> children { get; set; } /// <summary> /// Constructor of <see cref="ANode"/> /// </summary> public ANode() { data = new ANodeData(); children = new List<ANode>(); } } /// <summary> /// Defines an AREA /// </summary> public class ATreeRoot { /// <summary> /// The <see cref="ATreeRoot"/>'s name /// </summary> public string Name { get; set; } /// <summary> /// The root for the tree structure /// </summary> public ANode root { get; set; } /// <summary> /// Constructor of <see cref="ATreeRoot"/> /// </summary> /// <param name="name">The <see cref="ATreeRoot"/>'s name</param> public ATreeRoot(string name) { Name = name; root = new ANode(); } } /// <summary> /// Defines all AREAs for an <see cref="User"/> /// </summary> public class AreaTree { /// <summary> /// The <see cref="ObjectId"/> <see cref="User"/>'s identifier /// </summary> public ObjectId Id { get; set; } /// <summary> /// The <see cref="User"/>'s email /// </summary> public string Email { get; set; } /// <summary> /// The list of all AREAs for the <see cref="User"/> /// </summary> public List<ATreeRoot> AreasList { get; set; } /// <summary> /// Constructor of <see cref="AreaTree"/> /// </summary> /// <param name="email">The <see cref="User"/>'s email</param> public AreaTree(string email) { Email = email; AreasList = new List<ATreeRoot>(); } } }
using Bing.Admin.Commons.Domain.Models; using FreeSql.Extensions.EfCoreFluentApi; namespace Bing.Admin.Data.Mappings.Commons.MySql { /// <summary> /// 文件 映射配置 /// </summary> public class FileMap : Bing.FreeSQL.MySql.AggregateRootMap<File> { /// <summary> /// 映射表 /// </summary> protected override void MapTable(EfCoreTableFluent<File> builder ) { builder.ToTable( "`Commons.File`" ); } /// <summary> /// 映射属性 /// </summary> protected override void MapProperties(EfCoreTableFluent<File> builder ) { // 文件编号 builder.Property(t => t.Id) .HasColumnName("FileId"); } } }
 namespace DotCommerce.Persistence.SqlServer.Test.Infrastructure.Support { using System.Collections.Generic; using System.Configuration; using global::DotCommerce.Domain; using global::DotCommerce.Interfaces; using global::DotCommerce.Persistence.SqlServer.Test.Infrastructure.DTO; using Respawn; using Shouldly; public static class TestSupport { public static void AddProductToOrder(this IDotCommerceApi dc, IOrder order, Product product) { dc.AddItemToOrder( order: order, itemid: product.Id, quantity: product.Quantity, price: product.Price, name: product.Name, discount: product.Discount, weight: product.Weight, url: product.Url, imageUrl: product.ImageUrl); } public static void SetShippingAddress(this IDotCommerceApi dc, IOrder order, Address address) { dc.SetShippingAddress( order: order, title: address.Title, firstName: address.FirstName, lastName: address.LastName, company: address.Company, street: address.Street, streetNumber: address.StreetNumber, city: address.City, zip: address.Zip, country: address.Country, state: address.State, province: address.Province, email: address.Email, phone: address.Phone, singleAddress: address.SingleAddress); } public static void SetBillingAddress(this IDotCommerceApi dc, IOrder order, Address address) { dc.SetBillingAddress( order: order, title: address.Title, firstName: address.FirstName, lastName: address.LastName, company: address.Company, street: address.Street, streetNumber: address.StreetNumber, city: address.City, zip: address.Zip, country: address.Country, state: address.State, province: address.Province, email: address.Email, phone: address.Phone, singleAddress: address.SingleAddress); } public static void ResetDatabase() { Checkpoint checkpoint = new Checkpoint { TablesToIgnore = new[] { "__MigrationHistory" }, }; try { checkpoint.Reset(ConfigurationManager.ConnectionStrings["DotCommerce"].ConnectionString); } catch { // we will get exception in he case when database is not existing } } public static void VerifyLogEntries(this IDotCommerceApi dc, IOrder order, List<LogAction> actions) { var log = dc.GetLogEntries(order.Id); log.Count.ShouldBe(actions.Count); for (int i = 0; i < actions.Count; i++) { log[i].Action.ShouldBe(actions[i]); } } public static void VerifyLogEntries(this IDotCommerceApi dc, IOrder order, List<TestOrderLog> testLog) { var log = dc.GetLogEntries(order.Id); log.Count.ShouldBe(testLog.Count); for (int i = 0; i < testLog.Count; i++) { VerifyLogEntry(log[i], testLog[i]); } } public static void VerifyLogEntry(IOrderLog logEntry, TestOrderLog testLogEntry) { logEntry.OrderId.ShouldBe(testLogEntry.OrderId); logEntry.OrderLineId.ShouldBe(testLogEntry.OrderLineId); logEntry.Action.ShouldBe(testLogEntry.Action); if (testLogEntry.OldValue != null) logEntry.OldValue.ShouldBe(testLogEntry.OldValue); if (testLogEntry.Value != null) logEntry.Value.ShouldBe(testLogEntry.Value); } } }
@using Microsoft.AspNetCore.Mvc.Localization @inject IViewLocalizer Localiser <form method="POST" action="/login"> <h1>@Localiser["Title"]</h1> <fieldset> <label for="username">@Localiser["UsernameLabel"]</label> <div> <input id="username" type="text" name="username" placeholder="@Localiser["UsernamePlaceholder"]" required> <a href="/forgot-username">Forgot my username</a> </div> <label for="password">@Localiser["PasswordLabel"]</label> <div> <input id="password" type="password" name="password" placeholder="@Localiser["PasswordPlaceholder"]" required> <a href="/forgot-password">Forgot my password</a> </div> </fieldset> <p> <button type="submit">@Localiser["LoginLabel"]</button> </p> </form>
// // Copyright 2011 abhatia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using MonoTouch.UIKit; using System.IO; using MonoTouch.Foundation; using MonoTouch.Dialog; using System.Drawing; namespace WebServices.RxNormSample { public class DrugImageViewController : UIViewController { RxTerm _Term; UIScrollView _DrugScrollView; public DrugImageViewController(RxTerm term) : base() { _Term = term; this.Title = term.DisplayName; } public override void LoadView() { base.LoadView(); _DrugScrollView = new UIScrollView(); _DrugScrollView.ContentSize = new SizeF(500, 400); _DrugScrollView.ScrollEnabled = true; _DrugScrollView.UserInteractionEnabled = true; _DrugScrollView.MultipleTouchEnabled = true; if(PillboxClient.IsInitialized == false) { PillboxClient.Initialize(); } } public override void ViewDidLoad() { base.ViewDidLoad(); _DrugScrollView.Frame = this.View.Bounds; this.View.AddSubview(_DrugScrollView); } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); PillboxClient.DownloadPillboxImageAsync(_Term.RxCUI, FinishedDownloadingImage); } private void FinishedDownloadingImage(string path) { if(File.Exists(path)){ using(var pool = new NSAutoreleasePool()) { pool.BeginInvokeOnMainThread(() => { var drugImageView = new UIImageView(UIImage.FromFile(path)); drugImageView.Frame = new RectangleF(0, 0, 448, 320); _DrugScrollView.AddSubview(drugImageView); }); } } else { using(var pool = new NSAutoreleasePool()) { pool.BeginInvokeOnMainThread(() => { var alert = new UIAlertView ("", "No Image Found", null, "OK"); alert.AlertViewStyle = UIAlertViewStyle.Default; alert.Dismissed += delegate { // do something, go back maybe. }; alert.Show(); }); } } } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable namespace Microsoft.CodeAnalysis { // members of special types internal enum SpecialMember { System_String__CtorSZArrayChar, System_String__ConcatStringString, System_String__ConcatStringStringString, System_String__ConcatStringStringStringString, System_String__ConcatStringArray, System_String__ConcatObject, System_String__ConcatObjectObject, System_String__ConcatObjectObjectObject, System_String__ConcatObjectArray, System_String__op_Equality, System_String__op_Inequality, System_String__Length, System_String__Chars, System_String__Format, System_String__Substring, System_Double__IsNaN, System_Single__IsNaN, System_Delegate__Combine, System_Delegate__Remove, System_Delegate__op_Equality, System_Delegate__op_Inequality, System_Decimal__Zero, System_Decimal__MinusOne, System_Decimal__One, System_Decimal__CtorInt32, System_Decimal__CtorUInt32, System_Decimal__CtorInt64, System_Decimal__CtorUInt64, System_Decimal__CtorSingle, System_Decimal__CtorDouble, System_Decimal__CtorInt32Int32Int32BooleanByte, System_Decimal__op_Addition, System_Decimal__op_Subtraction, System_Decimal__op_Multiply, System_Decimal__op_Division, System_Decimal__op_Modulus, System_Decimal__op_UnaryNegation, System_Decimal__op_Increment, System_Decimal__op_Decrement, System_Decimal__NegateDecimal, System_Decimal__RemainderDecimalDecimal, System_Decimal__AddDecimalDecimal, System_Decimal__SubtractDecimalDecimal, System_Decimal__MultiplyDecimalDecimal, System_Decimal__DivideDecimalDecimal, System_Decimal__ModuloDecimalDecimal, System_Decimal__CompareDecimalDecimal, System_Decimal__op_Equality, System_Decimal__op_Inequality, System_Decimal__op_GreaterThan, System_Decimal__op_GreaterThanOrEqual, System_Decimal__op_LessThan, System_Decimal__op_LessThanOrEqual, System_Decimal__op_Implicit_FromByte, System_Decimal__op_Implicit_FromChar, System_Decimal__op_Implicit_FromInt16, System_Decimal__op_Implicit_FromInt32, System_Decimal__op_Implicit_FromInt64, System_Decimal__op_Implicit_FromSByte, System_Decimal__op_Implicit_FromUInt16, System_Decimal__op_Implicit_FromUInt32, System_Decimal__op_Implicit_FromUInt64, System_Decimal__op_Explicit_ToByte, System_Decimal__op_Explicit_ToUInt16, System_Decimal__op_Explicit_ToSByte, System_Decimal__op_Explicit_ToInt16, System_Decimal__op_Explicit_ToSingle, System_Decimal__op_Explicit_ToDouble, System_Decimal__op_Explicit_ToChar, System_Decimal__op_Explicit_ToUInt64, System_Decimal__op_Explicit_ToInt32, System_Decimal__op_Explicit_ToUInt32, System_Decimal__op_Explicit_ToInt64, System_Decimal__op_Explicit_FromDouble, System_Decimal__op_Explicit_FromSingle, System_DateTime__MinValue, System_DateTime__CtorInt64, System_DateTime__CompareDateTimeDateTime, System_DateTime__op_Equality, System_DateTime__op_Inequality, System_DateTime__op_GreaterThan, System_DateTime__op_GreaterThanOrEqual, System_DateTime__op_LessThan, System_DateTime__op_LessThanOrEqual, System_Collections_IEnumerable__GetEnumerator, System_Collections_IEnumerator__Current, System_Collections_IEnumerator__get_Current, System_Collections_IEnumerator__MoveNext, System_Collections_IEnumerator__Reset, System_Collections_Generic_IEnumerable_T__GetEnumerator, System_Collections_Generic_IEnumerator_T__Current, System_Collections_Generic_IEnumerator_T__get_Current, System_IDisposable__Dispose, System_Array__Length, System_Array__LongLength, System_Array__GetLowerBound, System_Array__GetUpperBound, System_Object__GetHashCode, System_Object__Equals, System_Object__EqualsObjectObject, System_Object__ToString, System_Object__ReferenceEquals, System_IntPtr__op_Explicit_ToPointer, System_IntPtr__op_Explicit_ToInt32, System_IntPtr__op_Explicit_ToInt64, System_IntPtr__op_Explicit_FromPointer, System_IntPtr__op_Explicit_FromInt32, System_IntPtr__op_Explicit_FromInt64, System_UIntPtr__op_Explicit_ToPointer, System_UIntPtr__op_Explicit_ToUInt32, System_UIntPtr__op_Explicit_ToUInt64, System_UIntPtr__op_Explicit_FromPointer, System_UIntPtr__op_Explicit_FromUInt32, System_UIntPtr__op_Explicit_FromUInt64, System_Nullable_T_GetValueOrDefault, System_Nullable_T_get_Value, System_Nullable_T_get_HasValue, System_Nullable_T__ctor, System_Nullable_T__op_Implicit_FromT, System_Nullable_T__op_Explicit_ToT, System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces, System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses, Count } }
//----------------------------------------------------------------------- // <copyright file="NodeDataActor.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; using Akka.MultiNode.TestAdapter.Internal.Sinks; namespace Akka.MultiNode.TestAdapter.Internal.Reporting { /// <summary> /// Actor responsible for processing test messages for an individual node within a multi-node test /// </summary> public class NodeDataActor : ReceiveActor { /// <summary> /// Data that will be processed and aggregated for an individual node /// </summary> protected NodeData NodeData; /// <summary> /// The ID of this node in the 0-N index of all nodes for this test. /// </summary> protected readonly int NodeIndex; /// <summary> /// The Role of this node. /// </summary> protected readonly string NodeRole; public NodeDataActor(int nodeIndex, string nodeRole) { NodeIndex = nodeIndex; NodeRole = nodeRole; NodeData = new NodeData(nodeIndex, nodeRole); SetReceive(); } #region Message-handling private void SetReceive() { Receive<MultiNodeMessage>(message => NodeData.Put(message)); Receive<EndSpec>(spec => { //Send NodeData to parent for aggregation purposes Sender.Tell(NodeData.Copy()); //Begin shutdown Context.Self.GracefulStop(TimeSpan.FromSeconds(1)); }); } #endregion } }
namespace AllInPoker.Models { using System; using System.Collections.Generic; public class MasterclassModel { public int Id { get; set; } public DateTime Date { get; set; } public DateTime Time { get; set; } public int MinPlayers { get; set; } public int MinRating { get; set; } public int LocationId { get; set; } public int ProfessionalId { get; set; } public ProfessionalModel Professional { get; set; } public List<MasterclassEntryModel> Entries { get; set; } public EventLocationModel Location { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using AspectCore.DynamicProxy; using Xunit; namespace AspectCore.Tests.DynamicProxy { // https://github.com/dotnetcore/AspectCore-Framework/issues/192 public class InterceptorAttributeWithArrayMemberTests : DynamicProxyTestBase { public class PropAttribute : AbstractInterceptorAttribute { public int[] TimesOfProp { get; set; } = { 1, 100, 10000, 1000000 }; public override async Task Invoke(AspectContext context, AspectDelegate next) { await next(context); context.ReturnValue = (int)context.ReturnValue + TimesOfProp.Sum(); } } public class FieldAttribute : AbstractInterceptorAttribute { public int[] TimesOfField = { 1, 100, 10000, 1000000 }; public override async Task Invoke(AspectContext context, AspectDelegate next) { await next(context); context.ReturnValue = (int)context.ReturnValue + TimesOfField.Sum(); } } public class CtorAttribute : AbstractInterceptorAttribute { private readonly int[] _times; public CtorAttribute(int[] times) { _times = times; } public override async Task Invoke(AspectContext context, AspectDelegate next) { await next(context); context.ReturnValue = (int)context.ReturnValue + _times.Sum(); } } public interface IService { [Prop(TimesOfProp = new[] { 10, 100 })] int ExcuteWithProp(int initTimes); [Field(TimesOfField = new[] { 10, 100 })] int ExcuteWithField(int initTimes); [Ctor(new[] { 10, 100 })] int ExcuteWithCtor(int initTimes); } public class Service : IService { public int ExcuteWithProp(int initTimes) => initTimes; public int ExcuteWithField(int initTimes) => initTimes; public int ExcuteWithCtor(int initTimes) => initTimes; } [Theory] [InlineData(0)] [InlineData(100)] [InlineData(-100)] public void InterceptorAttributeWithArrayMember_Property_Test(int initTimes) { var service = ProxyGenerator.CreateInterfaceProxy<IService, Service>(); var times = service.ExcuteWithProp(initTimes); Assert.Equal(initTimes + 10 + 100, times); } [Theory] [InlineData(0)] [InlineData(100)] [InlineData(-100)] public void InterceptorAttributeWithArrayMember_Field_Test(int initTimes) { var service = ProxyGenerator.CreateInterfaceProxy<IService, Service>(); var times = service.ExcuteWithField(initTimes); Assert.Equal(initTimes + 10 + 100, times); } [Theory] [InlineData(0)] [InlineData(100)] [InlineData(-100)] public void InterceptorAttributeWithArrayMember_Ctor_Test(int initTimes) { var service = ProxyGenerator.CreateInterfaceProxy<IService, Service>(); var times = service.ExcuteWithCtor(initTimes); Assert.Equal(initTimes + 10 + 100, times); } } }
namespace SwitchVsVersion { internal interface ISwitcher { bool IsMatch(string version); void Switch(string path, string version); } }
using System.IO; namespace UnshieldSharp.Cabinet { public class FileDescriptor { public uint NameOffset { get; private set; } public uint DirectoryIndex { get; private set; } public FileDescriptorFlag Flags { get; set; } public ulong ExpandedSize { get; private set; } public ulong CompressedSize { get; private set; } public ulong DataOffset { get; private set; } public byte[] Md5 { get; private set; } = new byte[16]; public ushort Volume { get; set; } public uint LinkPrevious { get; private set; } public uint LinkNext { get; private set; } public FileDescriptorLinkFlag LinkFlags { get; private set; } /// <summary> /// Create a new FileDescriptor from a header and an index /// </summary> public static FileDescriptor Create(Header header, int index) { var fd = new FileDescriptor(); if (header.MajorVersion <= 5) { int p = (int)(header.CommonHeader.DescriptorOffset + header.Descriptor.FileTableOffset + header.FileOffsetTable[header.Descriptor.DirectoryCount + index]); header.Data.Seek(p, SeekOrigin.Begin); fd.Volume = (ushort)header.Index; fd.NameOffset = header.Data.ReadUInt32(); fd.DirectoryIndex = header.Data.ReadUInt32(); fd.Flags = (FileDescriptorFlag)header.Data.ReadUInt16(); fd.ExpandedSize = header.Data.ReadUInt32(); fd.CompressedSize = header.Data.ReadUInt32(); header.Data.Seek(0x14, SeekOrigin.Current); fd.DataOffset = header.Data.ReadUInt32(); if (header.MajorVersion == 5) header.Data.Read(fd.Md5, 0, 0x10); } else { int p = (int)(header.CommonHeader.DescriptorOffset + header.Descriptor.FileTableOffset + header.Descriptor.FileTableOffset2 + index * 0x57); header.Data.Seek(p, SeekOrigin.Begin); fd.Flags = (FileDescriptorFlag)header.Data.ReadUInt16(); fd.ExpandedSize = header.Data.ReadUInt64(); fd.CompressedSize = header.Data.ReadUInt64(); fd.DataOffset = header.Data.ReadUInt64(); header.Data.Read(fd.Md5, 0, 0x10); header.Data.Seek(0x10, SeekOrigin.Current); fd.NameOffset = header.Data.ReadUInt32(); fd.DirectoryIndex = header.Data.ReadUInt16(); header.Data.Seek(0xC, SeekOrigin.Current); fd.LinkPrevious = header.Data.ReadUInt32(); fd.LinkNext = header.Data.ReadUInt32(); fd.LinkFlags = (FileDescriptorLinkFlag)header.Data.ReadUInt8(); fd.Volume = header.Data.ReadUInt16(); } return fd; } } }
using LINGYUN.Abp.TenantManagement; using Volo.Abp.Caching; using Volo.Abp.Modularity; namespace LINGYUN.Abp.MultiTenancy.RemoteService { [DependsOn( typeof(AbpCachingModule), typeof(AbpTenantManagementHttpApiClientModule))] public class AbpRemoteServiceMultiTenancyModule : AbpModule { } }
using System.Drawing; using System.Windows.Forms; namespace ModBotInstaller { public class NewProgressBar : ProgressBar { Brush _orangeBrush; Brush _backgroundBrush; public int Padding = 1; public NewProgressBar() { SetStyle(ControlStyles.UserPaint, true); } public float Progress { get { return Value / 100f; } set { Value = (int)(value * 100); } } protected override void OnPaint(PaintEventArgs e) { if (_orangeBrush == null) _orangeBrush = new SolidBrush(ForeColor); if (_backgroundBrush == null) _backgroundBrush = new SolidBrush(BackColor); Rectangle rec = e.ClipRectangle; e.Graphics.FillRectangle(_backgroundBrush, 0, 0, rec.Width, rec.Height); rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - (Padding * 2); rec.Height -= Padding * 2; e.Graphics.FillRectangle(_orangeBrush, Padding, Padding, rec.Width, rec.Height); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; namespace ShootTheTraps { public class Particle : GameObject { private Color color; private int alpha = 255; private int mImageIndex; private const double particleLifeTimeMilliseconds = 2000; public static List<Texture2D> Images { get; private set; } = new List<Texture2D>(); public override Rectangle BoundingRect { get { return new Rectangle( (int)Position.X, (int)Position.Y, 1, 1); } } /// Creates a new instance of Particle */ public Particle(Color clr, Random rnd) { Acceleration.Y = Gravity; color = clr; mImageIndex = rnd.Next(Images.Count); } public override void Draw(SpriteBatch spriteBatch) { alpha = (int)(255 * (1 - LifeTime_ms / particleLifeTimeMilliseconds)); if (alpha < 0) { alpha = 0; return; } var image = Images[mImageIndex]; //image.DisplayAlignment = OriginAlignment.Center; //image.RotationCenter = OriginAlignment.Center; //image.Color = Color.FromArgb(alpha, color); //image.RotationAngle = RotationAngle; //image.Draw((float)Position.X, (float)Position.Y); spriteBatch.Draw(image, position: Position, origin: new Vector2(image.Width / 2, image.Height / 2), rotation: RotationAngle, color: new Color(color, alpha)); } public override bool DeleteMe { get { if (OutsideField) return true; if (alpha <= 0) return true; else return false; } } } }
using System; using System.Runtime.InteropServices; namespace RecklessBoon.MacroDeck.GPUZ { [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct GPUZ_SH_MEM { public UInt32 version; public volatile Int32 busy; public UInt32 lastUpdate; } }
using System; using Timeline.Commands; namespace Sample.Application.Write { public class BoxPerson : Command { public BoxPerson(Guid id) { AggregateIdentifier = id; } } }
 namespace FastQuant { public static class IdArrayExtensions { public static T GetOrCreate<T>(this IdArray<T> array, int id, int size = 1024) where T : class, new() { var o = array[id]; if (o == null) array[id] = o = new T(); return o; } } }
// SMARTTYPE int // SMARTTEMPLATE ReadSmartVarTemplate // Do not move or delete the above lines using System.Collections; using System.Collections.Generic; using UnityEngine; using SmartData.Abstract; namespace SmartData.SmartInt.Components { /// <summary> /// Automatically listens to a <cref>SmartInt</cref> and fires a <cref>UnityEvent<int></cref> when data changes. /// </summary> [AddComponentMenu("SmartData/Int/Read Smart Int", 0)] public class ReadSmartInt : ReadSmartBase<IntReader> {} }
using BluebirdPS.APIV2.Objects; namespace BluebirdPS.APIV2.UserInfo.Metrics { public class Public : BaseMetrics { public long FollowersCount { get; set; } public long FollowingCount { get; set; } public long ListedCount { get; set; } public long TweetCount { get; set; } public Public() { } public Public(dynamic input) { FollowersCount = input.followers_count; FollowingCount = input.following_count; ListedCount = input.listed_count; TweetCount = input.tweet_count; OriginalObject = input; } } }
using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using IntelligentApp.Models; using Microsoft.ProjectOxford; using Microsoft.ProjectOxford.Emotion; namespace IntelligentApp.CognitiveServices { public class Emotion : IVisionService { public async Task<VisionResult> Analyze(Stream stream) { var client = new EmotionServiceClient(Constants.EmotionApiKey, Constants.EmotionApiEndpoint); var attributes = new List<VisionAttribute>(); var rectangles = new List<Rectangle>(); using (stream) { var emotionResult = await client.RecognizeAsync(stream); if (emotionResult != null && emotionResult.Length > 0) { for (int i = 0; i < emotionResult.Length; i++) { var emotion = emotionResult[i]; rectangles.Add(emotion.FaceRectangle.ToRectangle()); foreach (var score in emotion.Scores.ToRankedList()) { attributes.Add(new VisionAttribute($"Pessoa {i}", score.Key, score.Value)); } } } } return new VisionResult { Attributes = attributes, Rectangles = rectangles }; } } }
using System; using System.IO; using System.Threading; using Rocket.Core.Logging; using SDG.Unturned; using UnityEngine; using ILogger = Rocket.API.Logging.ILogger; namespace Rocket.Unturned.Console { public class UnturnedConsolePipe : MonoBehaviour { public ILogger Logger { get; set; } } }
using System; namespace CurrencyCloud { class ParamAttribute : Attribute { } }
// Copyright (c) 2021 Jeevan James // This file is licensed to you under the MIT License. // See the LICENSE file in the project root for more information. using Datask.Providers.Scripts; using Microsoft.Data.SqlClient; namespace Datask.Providers.SqlServer; public sealed class SqlServerScriptGeneratorProvider : ScriptGeneratorProvider<SqlConnection> { public SqlServerScriptGeneratorProvider(SqlConnection connection) : base(connection) { } }
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using MyMiniTradingSystem.DataAccess; using System; namespace MyMiniTradingSystem.DataAccess.Migrations { [DbContext(typeof(MyMiniTradingSystemContext))] partial class MyMiniTradingSystemContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.0-rtm-26452"); modelBuilder.Entity("MyMiniTradingSystem.Model.CommodityPrice", b => { b.Property<string>("CommodityCode") .HasColumnName("commodity_code") .HasMaxLength(32); b.Property<DateTime>("TradingStartDate") .HasColumnName("trading_start_date"); b.Property<decimal>("Atr") .HasColumnName("atr") .HasColumnType("decimal(10, 3)"); b.Property<decimal>("ClosePrice") .HasColumnName("close_price") .HasColumnType("decimal(10, 3)"); b.Property<decimal>("HighestPrice") .HasColumnName("highest_price") .HasColumnType("decimal(10, 3)"); b.Property<decimal>("LowestPrice") .HasColumnName("lowest_price") .HasColumnType("decimal(10, 3)"); b.Property<decimal>("OpenPrice") .HasColumnName("open_price") .HasColumnType("decimal(10, 3)"); b.Property<decimal>("Tr") .HasColumnName("tr") .HasColumnType("decimal(10, 3)"); b.Property<DateTime>("TradingFinishDate") .HasColumnName("trading_finish_date"); b.Property<long>("Volume") .HasColumnName("volume"); b.HasKey("CommodityCode", "TradingStartDate"); b.ToTable("mts_commodity_price"); }); modelBuilder.Entity("MyMiniTradingSystem.Model.DailySummary", b => { b.Property<long>("DailySummaryID") .ValueGeneratedOnAdd() .HasColumnName("daily_summary_id"); b.Property<decimal>("ClosePrice") .HasColumnName("close_price") .HasColumnType("decimal(10, 3)"); b.Property<DateTime>("DailySummaryDate") .HasColumnName("daily_summary_date"); b.Property<string>("PositionCommodityCode") .IsRequired() .HasColumnName("position_commodity_code") .HasMaxLength(32); b.Property<int>("PositionQuantity") .HasColumnName("position_quantity"); b.Property<decimal>("PositionValue") .HasColumnName("position_value") .HasColumnType("decimal(10, 3)"); b.Property<decimal>("StopLossPrice") .HasColumnName("stop_loss_price"); b.Property<string>("Todo") .HasColumnName("todo") .HasMaxLength(64); b.Property<string>("UserCode") .IsRequired() .HasColumnName("user_code") .HasMaxLength(32); b.HasKey("DailySummaryID"); b.HasIndex("PositionCommodityCode"); b.HasIndex("UserCode"); b.ToTable("mts_daily_summary"); }); modelBuilder.Entity("MyMiniTradingSystem.Model.Position", b => { b.Property<long>("PositionID") .ValueGeneratedOnAdd() .HasColumnName("position_id"); b.Property<string>("CommodityCode") .IsRequired() .HasColumnName("commodity_code") .HasMaxLength(32); b.Property<bool>("IsLong") .HasColumnName("is_long"); b.Property<int>("Quantity") .HasColumnName("quantity"); b.Property<string>("UserCode") .IsRequired() .HasColumnName("user_code") .HasMaxLength(32); b.HasKey("PositionID"); b.HasIndex("CommodityCode"); b.HasIndex("UserCode"); b.ToTable("mts_position"); }); modelBuilder.Entity("MyMiniTradingSystem.Model.TradableCommodity", b => { b.Property<string>("CommodityCode") .ValueGeneratedOnAdd() .HasColumnName("commodity_code") .HasMaxLength(32); b.Property<string>("CommodityName") .IsRequired() .HasColumnName("commodity_name") .HasMaxLength(32); b.Property<int>("DepositRatio") .HasColumnName("deposit_ratio"); b.Property<int>("NumOfOneHand") .HasColumnName("num_of_one_hand"); b.HasKey("CommodityCode"); b.ToTable("mts_commodity"); }); modelBuilder.Entity("MyMiniTradingSystem.Model.UserAccount", b => { b.Property<string>("UserCode") .ValueGeneratedOnAdd() .HasColumnName("user_code") .HasMaxLength(32); b.Property<string>("UserName") .IsRequired() .HasColumnName("user_name") .HasMaxLength(32); b.HasKey("UserCode"); b.ToTable("mts_user_account"); }); modelBuilder.Entity("MyMiniTradingSystem.Model.CommodityPrice", b => { b.HasOne("MyMiniTradingSystem.Model.TradableCommodity", "TradableCommodityData") .WithMany("CommodityPrices") .HasForeignKey("CommodityCode") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("MyMiniTradingSystem.Model.DailySummary", b => { b.HasOne("MyMiniTradingSystem.Model.TradableCommodity", "PositionTradableCommodity") .WithMany("DailySummarys") .HasForeignKey("PositionCommodityCode") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MyMiniTradingSystem.Model.UserAccount", "UserAccountData") .WithMany("DailySummarys") .HasForeignKey("UserCode") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("MyMiniTradingSystem.Model.Position", b => { b.HasOne("MyMiniTradingSystem.Model.TradableCommodity", "TradableCommodityData") .WithMany("Positions") .HasForeignKey("CommodityCode") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MyMiniTradingSystem.Model.UserAccount", "UserAccountData") .WithMany("Positions") .HasForeignKey("UserCode") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
using MixERP.Net.VCards.Serializer; using MixERP.Net.VCards.Types; namespace MixERP.Net.VCards.Processors { public static class Base64StringProcessor { public static string SerializeBase64String(string value, string key, string type, VCardVersion version) { if (string.IsNullOrWhiteSpace(value)) { return string.Empty; } /*************************************************************** V2.1 PHOTO;VALUE=URL:file:///jqpublic.gif OR PHOTO;ENCODING=BASE64;TYPE=GIF: R0lGODdhfgA4AOYAAAAAAK+vr62trVIxa6WlpZ+fnzEpCEpzlAha/0Kc74+PjyGM SuecKRhrtX9/fzExORBSjCEYCGtra2NjYyF7nDGE50JrhAg51qWtOTl7vee1MWu1 50o5e3PO/3sxcwAx/4R7GBgQOcDAwFoAQt61hJyMGHuUSpRKIf8A/wAY54yMjHtz ... **************************************************************/ string encoding = "BASE64"; if (version == VCardVersion.V3) { /*************************************************************** Looks like this in V3.0 PHOTO;VALUE=uri:http://www.abc.com/pub/photos /jqpublic.gif OR PHOTO;ENCODING=b;TYPE=JPEG:MIICajCCAdOgAwIBAgICBEUwDQYJKoZIhvcN AQEEBQAwdzELMAkGA1UEBhMCVVMxLDAqBgNVBAoTI05ldHNjYXBlIENvbW11bm ljYXRpb25zIENvcnBvcmF0aW9uMRwwGgYDVQQLExNJbmZvcm1hdGlvbiBTeXN0 <...remainder of "B" encoded binary data...> **************************************************************/ encoding = "b"; } else if (version == VCardVersion.V4) { /*************************************************************** Looks like this in V4.0 PHOTO:data:image/jpeg;base64,MIICajCCAdOgAwIBAgICBEUwDQYJKoZIhv AQEEBQAwdzELMAkGA1UEBhMCVVMxLDAqBgNVBAoTI05ldHNjYXBlIENvbW11bm ljYXRpb25zIENvcnBvcmF0aW9uMRwwGgYDVQQLExNJbmZvcm1hdGlvbiBTeXN0 <...remainder of base64-encoded data...> **************************************************************/ encoding = string.Empty; } return DefaultSerializer.GetVCardString(key, value, false, version, type, encoding); } } }
using System; using UnityEngine; namespace Wowsome { public delegate T Delegate<T, U>(U t); public class CapacityData { public int Max { get; private set; } public int Cur { get; private set; } public float DecimalPercentage => (float)Cur / Max; public float Percentage => DecimalPercentage * 100f; public bool IsAny => Cur > 0; public bool IsFull => Cur == Max; int _initCur; public CapacityData(int max) { Max = max; Cur = 0; _initCur = Cur; } public CapacityData(int max, int cur) { Max = max; Cur = cur; _initCur = Cur; } public CapacityData(CapacityData other) { Max = other.Max; Cur = other.Cur; _initCur = Cur; } public bool Add() { if (IsFull) { return false; } ++Cur; return true; } public bool Remove() { --Cur; if (Cur < 0) { Cur = 0; return false; } return true; } public void Reset() { Cur = _initCur; } } [Serializable] public struct RangeData { public float min; public float max; bool _hasClamped; public RangeData(float def) { min = max = def; _hasClamped = false; } public RangeData(float min, float max) { this.min = min; this.max = max; _hasClamped = false; } public float GetRand() { Clamp(); if (Mathf.Approximately(min, max)) { return max; } float rand = (((float)MathExtensions.GetRandom().NextDouble()) * (max - min) + min); return rand; } void Clamp() { if (_hasClamped) { return; } const float min = 0f; const float max = 1000f; this.min = this.min.Clamp(min, max); this.max = this.max.Clamp(this.min, max); _hasClamped = true; } } [Serializable] public class TimeData { public RangeData duration; public RangeData delay; public TimeData(float duration) { this.duration = new RangeData(duration); delay = new RangeData(0f); } public TimeData(float duration, float delay) { this.duration = new RangeData(duration); this.delay = new RangeData(delay); } public TimeData(RangeData duration) { this.duration = duration; delay = new RangeData(0f); } public TimeData(RangeData duration, RangeData delay) { this.duration = duration; this.delay = delay; } } public struct Vec2Int { public static Vec2Int Create(Vector3 v) { return new Vec2Int(v); } Vector2 _vector; public int X { get { return Mathf.FloorToInt(_vector.x); } } public int XHalf { get { return X / 2; } } public int Y { get { return Mathf.FloorToInt(_vector.y); } } public int YHalf { get { return Y / 2; } } public int Xy { get { return X * Y; } } public int Sum { get { return X + Y; } } public Vec2Int Half { get { return new Vec2Int(XHalf, YHalf); } } public Vec2Int(Vector2 v) { _vector = v; } public Vec2Int(int x, int y) { _vector = new Vector2(x, y); } public override string ToString() { return X + "," + Y; } public override int GetHashCode() { return (X << 16) | Y; } public override bool Equals(object obj) { if (!(obj is Vec2Int)) return false; Vec2Int other = (Vec2Int)obj; return X == other.X && Y == other.Y; } public Vector2 ToVec2() { return new Vector2(X, Y); } } [Serializable] public class PlatformBasedString { public string ios; public string google; public string amazon; public PlatformBasedString(string ios, string google, string amazon) { this.ios = ios; this.google = google; this.amazon = amazon; } public string Get() { if (Application.platform == RuntimePlatform.IPhonePlayer) return ios; return AppSettings.AndroidPlatform == AndroidPlatform.Google ? google : amazon; } } }
using Dockman.CLI.Commands; using Dockman.CLI.Commands.Projects; using Dockman.CLI.Platform; using Dockman.Environment.Providers; using System; using System.Linq; using System.Threading.Tasks; namespace Dockman.CLI { public class Program { public static int Main() => SecureRun().Result; private static async Task Run() { var commander = GetCommander(); while (true) { Console.Write("> "); await commander.Run(GetCommand()); } } private static Commander GetCommander() { var commander = new Commander(); var shell = new ShellFactory(new SystemConfigurationProvider()).Create(); commander.Register(new BuildProjectCommand(shell)); return commander; } private static string GetCommand() => string.Join(" ", Console.ReadLine().Split(' ') .Select(arg => arg.Trim()) .Where(arg => !string.IsNullOrWhiteSpace(arg))); private static async Task<int> SecureRun() { try { await Run(); } catch (Exception exception) { Console.WriteLine(exception); return 1; } return 0; } } }
using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Controllers; using JsonApiDotNetCore.Controllers.Annotations; using JsonApiDotNetCore.QueryStrings; using JsonApiDotNetCore.Services; using Microsoft.Extensions.Logging; namespace JsonApiDotNetCoreExampleTests.IntegrationTests.RestrictedControllers { [NoHttpDelete] [DisableQueryString(StandardQueryStringParameters.Sort | StandardQueryStringParameters.Page)] public sealed class BlockingHttpDeleteController : JsonApiController<Sofa> { public BlockingHttpDeleteController(IJsonApiOptions options, ILoggerFactory loggerFactory, IResourceService<Sofa> resourceService) : base(options, loggerFactory, resourceService) { } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; using Adxstudio.Xrm.Globalization; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; namespace Adxstudio.Xrm.Search { internal class ExtendedAttributeSearchResultInfo { private static readonly int[] _extendedInfoAttributeQueryTypes = new[] { 64, 0 }; public ExtendedAttributeSearchResultInfo(OrganizationServiceContext context, string logicalName, IDictionary<string, EntityMetadata> metadataCache) { if (context == null) { throw new ArgumentNullException("context"); } Context = context; Metadata = GetEntityMetadata(context, logicalName, metadataCache); DisplayName = GetEntityDisplayName(Metadata); TypeCode = GetEntityTypeCode(Metadata); AttributeLayoutXml = GetAttributeLayoutXml(context, Metadata, TypeCode); } public string DisplayName { get; private set; } public EntityMetadata Metadata { get; private set; } public int TypeCode { get; private set; } protected XDocument AttributeLayoutXml { get; private set; } protected OrganizationServiceContext Context { get; private set; } public IDictionary<string, string> GetAttributes(Entity entity, IDictionary<string, EntityMetadata> metadataCache) { if (AttributeLayoutXml == null || entity == null) { return CreateBaseAttributesDictionary(); } var attributeLookup = Metadata.Attributes.ToDictionary(a => a.LogicalName, a => a); var attributes = CreateBaseAttributesDictionary(); var names = from cell in AttributeLayoutXml.XPathSelectElements("//cell") select cell.Attribute("name") into nameAttibute where nameAttibute != null select nameAttibute.Value into name where !string.IsNullOrEmpty(name) select name; foreach (var name in names) { AttributeMetadata attributeMetadata; if (!attributeLookup.TryGetValue(name, out attributeMetadata)) { continue; } var resultAttribute = GetSearchResultAttribute(Context, entity, attributeMetadata, metadataCache); if (resultAttribute == null) { continue; } attributes[resultAttribute.Value.Key] = resultAttribute.Value.Value; } return attributes; } private IDictionary<string, string> CreateBaseAttributesDictionary() { return new Dictionary<string, string> { { "_EntityDisplayName", DisplayName }, { "_EntityTypeCode", TypeCode.ToString() }, }; } private static XDocument GetAttributeLayoutXml(OrganizationServiceContext context, EntityMetadata metadata, int typeCode) { var queries = context.CreateQuery("savedquery") .Where(e => e.GetAttributeValue<bool?>("isdefault").GetValueOrDefault(false) && e.GetAttributeValue<int>("returnedtypecode") == typeCode) .ToList(); return ( from queryType in _extendedInfoAttributeQueryTypes select queries.FirstOrDefault(e => e.GetAttributeValue<int>("querytype") == queryType) into query where query != null select XDocument.Parse(query.GetAttributeValue<string>("layoutxml"))).FirstOrDefault(); } private static string GetEntityDisplayName(EntityMetadata metadata) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (metadata.DisplayName != null && metadata.DisplayName.UserLocalizedLabel != null) { return metadata.DisplayName.GetLocalizedLabelString(); } throw new InvalidOperationException("Unable to retrieve the label for entity name.".FormatWith(metadata.LogicalName)); } private static EntityMetadata GetEntityMetadata(OrganizationServiceContext context, string logicalName, IDictionary<string, EntityMetadata> metadataCache) { EntityMetadata cachedMetadata; if (metadataCache.TryGetValue(logicalName, out cachedMetadata)) { return cachedMetadata; } var metadataReponse = context.Execute(new RetrieveEntityRequest { LogicalName = logicalName, EntityFilters = EntityFilters.Attributes }) as RetrieveEntityResponse; if (metadataReponse != null && metadataReponse.EntityMetadata != null) { metadataCache[logicalName] = metadataReponse.EntityMetadata; return metadataReponse.EntityMetadata; } throw new InvalidOperationException("Unable to retrieve the metadata for entity name {0}.".FormatWith(logicalName)); } private static int GetEntityTypeCode(EntityMetadata metadata) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (metadata.ObjectTypeCode != null) { return metadata.ObjectTypeCode.Value; } throw new InvalidOperationException("Unable to retrieve the object type code for entity name {0}.".FormatWith(metadata.LogicalName)); } private static KeyValuePair<string, string>? GetSearchResultAttribute(OrganizationServiceContext context, Entity entity, AttributeMetadata attributeMetadata, IDictionary<string, EntityMetadata> metadataCache) { var label = attributeMetadata.DisplayName.GetLocalizedLabelString(); if (AttributeTypeEqualsOneOf(attributeMetadata, "lookup", "customer")) { return null; } if (AttributeTypeEqualsOneOf(attributeMetadata, "picklist")) { var picklistMetadata = attributeMetadata as PicklistAttributeMetadata; if (picklistMetadata == null) { return null; } var picklistValue = entity.GetAttributeValue<OptionSetValue>(attributeMetadata.LogicalName); if (picklistValue == null) { return null; } var option = picklistMetadata.OptionSet.Options.FirstOrDefault(o => o.Value != null && o.Value.Value == picklistValue.Value); if (option == null || option.Label == null || option.Label.UserLocalizedLabel == null) { return null; } new KeyValuePair<string, string>(label, option.Label.GetLocalizedLabelString()); } var value = entity.GetAttributeValue<object>(attributeMetadata.LogicalName); return value == null ? null : new KeyValuePair<string, string>?(new KeyValuePair<string, string>(label, value.ToString())); } private static bool AttributeTypeEqualsOneOf(AttributeMetadata attributeMetadata, params string[] typeNames) { var attributeTypeName = attributeMetadata.AttributeType.Value.ToString(); return typeNames.Any(name => string.Equals(attributeTypeName, name, StringComparison.InvariantCultureIgnoreCase)); } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp { public class RevRepContentBuilder { private readonly Asn1EncodableVector status = new Asn1EncodableVector(); private readonly Asn1EncodableVector revCerts = new Asn1EncodableVector(); private readonly Asn1EncodableVector crls = new Asn1EncodableVector(); public virtual RevRepContentBuilder Add(PkiStatusInfo status) { this.status.Add(status); return this; } public virtual RevRepContentBuilder Add(PkiStatusInfo status, CertId certId) { if (this.status.Count != this.revCerts.Count) throw new InvalidOperationException("status and revCerts sequence must be in common order"); this.status.Add(status); this.revCerts.Add(certId); return this; } public virtual RevRepContentBuilder AddCrl(CertificateList crl) { this.crls.Add(crl); return this; } public virtual RevRepContent Build() { Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerSequence(status)); if (revCerts.Count != 0) { v.Add(new DerTaggedObject(true, 0, new DerSequence(revCerts))); } if (crls.Count != 0) { v.Add(new DerTaggedObject(true, 1, new DerSequence(crls))); } return RevRepContent.GetInstance(new DerSequence(v)); } } } #pragma warning restore #endif
namespace Tftp.NetStandard.Transfer { static class InitialStateFactory { /*public enum TransferInitiatedBy { LocalSystem, RemoteSystem } public enum TransferMode { Read, Write } public static ITftpState GetInitialState(TransferInitiatedBy direction, TransferMode mode) { if (direction == TransferInitiatedBy.RemoteSystem && mode == TransferMode.Read) { return new StartIncomingRead(this); } if (direction == TransferInitiatedBy.RemoteSystem && mode == TransferMode.Write) { return new StartIncomingWrite(this); } if (direction == TransferInitiatedBy.LocalSystem && mode == TransferMode.Read) { return new StartOutgoingRead(this); } if (direction == TransferInitiatedBy.LocalSystem && mode == TransferMode.Write) { } return null; }*/ } }
// Copyright (c) Arctium. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Arctium.WoW.Launcher.Constants; enum MemProtection { NoAccess = 0x1, ReadOnly = 0x2, ReadWrite = 0x4, WriteCopy = 0x8, Execute = 0x10, ExecuteRead = 0x20, ExecuteReadWrite = 0x40, ExecuteWriteCopy = 0x80, Guard = 0x100, NoCache = 0x200, WriteCombine = 0x400, }
using System; using System.ComponentModel.DataAnnotations; namespace Petminder_RestApi.Dtos { public class UserCreateDto : UserCreateUpdateBaseDto { [Required] [StringLength(250)] public string Username { get; set; } public Guid AccountId { get; set; } } }
using System; using Wanghzh.Prism.Regions.Behaviors; namespace Wanghzh.Prism.Regions { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = true )] public sealed class RegionMemberLifetimeAttribute : Attribute { public RegionMemberLifetimeAttribute() { KeepAlive = true; } public bool KeepAlive { get; set; } } }
#pragma warning disable 1591 using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; namespace GenericSearch.Searches { public class TextSearch : AbstractSearch { public enum Comparer { [Display(Name = "Contains")] Contains, [Display(Name = "==")] Equals } [ExcludeFromCodeCoverage] public TextSearch() { } public TextSearch(params string[] properties) : base(properties) { } [DefaultValue(null)] public string Term { get; set; } [DefaultValue(Comparer.Equals)] public Comparer Is { get; set; } = Comparer.Equals; public override bool IsActive() { return !string.IsNullOrWhiteSpace(Term); } private static readonly MethodInfo Contains = typeof(string).GetMethod(nameof(string.Contains), new[] {typeof(string)}); protected override Expression BuildFilterExpression(Expression property) { var constant = Expression.Constant(Term); if (Is == Comparer.Contains) { return Expression.Call(property, Contains, constant); } return Expression.Equal(property, constant); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace ExamInvigilatorProject.Pages { public class RegisterModel : PageModel { public bool success = true; private readonly ILogger<RegisterModel> _logger; public RegisterModel(ILogger<RegisterModel> logger) { _logger = logger; } public void OnGet() { } public void OnPostRegister() { dbEdit editor = new dbEdit(); var emailAddress = Request.Form["email"]; var userpassword = Request.Form["userpassword"]; var confirm = Request.Form["passwordConfirm"]; var firstName = Request.Form["firstName"]; var lastName = Request.Form["surname"]; var roled = Request.Form["userType"]; string role = "UNDEFINED"; if (roled == "learner") { role = "LEARNER"; } else if (roled == "invigilator") { role = "INVIGILATOR"; } if (userpassword == confirm) { byte[] salt = editor.generateSalt(); success = editor.register(emailAddress, firstName, lastName, userpassword, salt, role); Response.Redirect("/Login"); } } } }
using NUnit.Framework; using Sonneville.Utilities.Reflection; namespace Sonneville.Utilities.Test.Reflection { [TestFixture] public class PropertyComparerTests { private PropertyComparer _propertyComparer; [SetUp] public void Setup() { _propertyComparer = new PropertyComparer(); } [Test] public void LeftNullReturnsNotEqual() { var compare = _propertyComparer.Compare(null, 1); Assert.AreNotEqual(0, compare); } [Test] public void RightNullReturnsNotEqual() { var compare = _propertyComparer.Compare(1, null); Assert.AreNotEqual(0, compare); } [Test] public void DifferentTypesReturnsNotEqual() { var compare = _propertyComparer.Compare(1, 1L); Assert.AreNotEqual(0, compare); } [Test] public void SameTypeSameValueReturnsEqualForValueType() { var compare = _propertyComparer.Compare(1, 1); Assert.AreEqual(0, compare); } [Test] public void SameTypeDifferentValueReturnsNotEqualForValueTypes() { var compare = _propertyComparer.Compare(1, 2); Assert.AreNotEqual(0, compare); } [Test] public void SameTypeSameValueReturnsEqualForReferenceType() { var compare = _propertyComparer.Compare("1", "1"); Assert.AreEqual(0, compare); } [Test] public void SameTypeDifferentValueReturnsNotEqualForReferenceType() { var compare = _propertyComparer.Compare("1", "2"); Assert.AreEqual(0, compare); } } }
using JetBrains.Annotations; namespace XyrusWorx.Threading { [PublicAPI] public enum SequenceErrorBehavior { Ignore, Continue, Abort } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using MvcSolution.Data; using MvcSolution.Services.Admin; using MvcSolution.Web.ViewModels; namespace MvcSolution.Web.Admin.ViewModels { public class UserIndexViewModel: LayoutViewModel { public List<SelectListItem> Tags { get; set; } public UserIndexViewModel Build() { this.Tags = Ioc.Get<ITagService>().GetAll() .ToSelectList(x => x.Name, x => x.Id, "Any/All"); return this; } } public class UserEditorViewModel { private readonly Guid _userId; public User User { get; set; } public List<SelectListItem> Tags { get; set; } public UserEditorViewModel(Guid userId) { _userId = userId; } public UserEditorViewModel Build() { this.User = Ioc.Get<Services.IUserService>().Get(_userId); var service = Ioc.Get<ITagService>(); var userTags = service.GetUserTags(_userId); this.Tags = service.GetAll().ToSelectList(x => x.Name, x => x.Id, x => userTags.Any(u => u == x.Id)); return this; } } }
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; namespace System.Reflection { public static class AttributeExtensions { public static bool HasAttribute<T>(this MemberInfo element) where T : Attribute { return Attribute.IsDefined(element, typeof(T)); } // public static bool HasAttribute<T>(this ParameterInfo element) where T : Attribute // { // return Attribute.IsDefined(element, typeof(T)); // } // public static bool HasAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute // { // return Attribute.IsDefined(element, typeof(T), inherit); // } // public static bool HasAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute // { // return Attribute.IsDefined(element, typeof(T), inherit); // } // public static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute // { // return (T)Attribute.GetCustomAttribute(element, typeof(T)); // } // public static T GetCustomAttribute<T>(this ParameterInfo element) where T : Attribute // { // return (T)Attribute.GetCustomAttribute(element, typeof(T)); // } // public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute // { // return (T)Attribute.GetCustomAttribute(element, typeof(T), inherit); // } // public static T GetCustomAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute // { // return (T)Attribute.GetCustomAttribute(element, typeof(T), inherit); // } // public static T[] GetCustomAttributes<T>(this MemberInfo element) where T : Attribute // { // return (T[])Attribute.GetCustomAttributes(element, typeof(T)); // } // public static T[] GetCustomAttributes<T>(this ParameterInfo element) where T : Attribute // { // return (T[])Attribute.GetCustomAttributes(element, typeof(T)); // } // public static T[] GetCustomAttributes<T>(this MemberInfo element, bool inherit) where T : Attribute // { // return (T[])Attribute.GetCustomAttributes(element, typeof(T), inherit); // } // public static T[] GetCustomAttributes<T>(this ParameterInfo element, bool inherit) where T : Attribute // { // return (T[])Attribute.GetCustomAttributes(element, typeof(T), inherit); // } } }
using System; using System.Windows; using System.Windows.Threading; using Microsoft.Web.Media.SmoothStreaming; namespace Microsoft.SilverlightMediaFramework.Player { // shim SSME helper, does two things: 1) monitors the state of the SSME control // so it can be restored later, and 2) encapsulates the retry and auto retry logic internal class RetryMonitor { // events public event EventHandler<SimpleEventArgs<Exception>> Retrying; public event RoutedEventHandler RetrySuccessful; public event EventHandler<ExceptionRoutedEventArgs> RetryFailed; public event RoutedEventHandler RetryAttempted; // the ssme control monitoring private CoreSmoothStreamingMediaElement mediaElement; // status, get last good state so can be restored private DispatcherTimer statusTimer; // retry private DispatcherTimer retryTimer; private DateTime startTime; private TimeSpan retryInterval; internal RetryState RetryState { get; set; } internal TimeSpan RetryDuration { get; set; } internal int RetryAttempt { get; private set; } internal TimeSpan RetryInterval { get { return retryInterval; } set { retryInterval = value; retryTimer.Interval = retryInterval; } } // state information that can be restored internal Uri LastSmoothStreamingSource { get; set; } internal TimeSpan LastPosition { get; set; } public RetryMonitor(CoreSmoothStreamingMediaElement mediaElement) { // store media element monitoring this.mediaElement = mediaElement; // status timer statusTimer = new DispatcherTimer(); statusTimer.Interval = TimeSpan.FromMilliseconds(1000); statusTimer.Tick += statusTimer_Tick; // retry timer retryTimer = new DispatcherTimer(); retryTimer.Interval = retryInterval; retryTimer.Tick += retryTimer_Tick; // events, note use the base class SmoothStreamingMediaElement // events since SmoothStreamingMediaElement shadows some events SmoothStreamingMediaElement baseMediaElement = (SmoothStreamingMediaElement)mediaElement; baseMediaElement.MediaOpened += mediaElement_MediaOpened; baseMediaElement.MediaEnded += mediaElement_MediaEnded; baseMediaElement.MediaFailed += mediaElement_MediaFailed; //Breaking Change: Moving PDC team from SSME build 604.9 to 604.3 //SmoothStreamingMediaElement.ManifestReady event is no longer //available --Kevin Rohling (11/5/2009 4:20PM) //baseMediaElement.ManifestReady += baseMediaElement_ManifestReady; ResetAutoRetry(); } // retry loading the stream source, only retry one time internal void Retry() { Retry(TimeSpan.Zero); } // retry loading the stream source for the specified amount of time internal void Retry(TimeSpan retryDuration) { // adjust time so it retries for the time specified, the retry // duration is an override, and the RetryDuration property // should not be updated with the new value RetryState = RetryState.Retrying; startTime = DateTime.Now.Subtract(RetryDuration - retryDuration); if (Retrying != null) { Retrying(this, null); } ResetSource(); } private void ResetSource() { RetryAttempt++; if (RetryAttempted != null) { RetryAttempted(this, new RoutedEventArgs()); } // retry setting the source, note call SetSmoothStreamingVideo instead of // setting the SmoothStreamingSource property, this is required since the // SmoothStreamingSource property resets any auto retry operations mediaElement.SetSmoothStreamingVideo(null); mediaElement.SetSmoothStreamingVideo(new Uri(LastSmoothStreamingSource.AbsoluteUri)); } // stop and reset auto retrys internal void ResetAutoRetry() { RetryState = RetryState.None; retryTimer.Stop(); } // status timer private void statusTimer_Tick(object sender, EventArgs e) { // make sure should still collect monitor information if (statusTimer.IsEnabled) { // get retry values LastPosition = mediaElement.Position; } } // retry timer private void retryTimer_Tick(object sender, EventArgs e) { retryTimer.Stop(); ResetSource(); } private void mediaElement_MediaOpened(object sender, RoutedEventArgs e) { // store values that can be restored later LastSmoothStreamingSource = mediaElement.SmoothStreamingSource; // see if this is the result of a retry if (RetryState == RetryState.Retrying) { OnRetrySucceeded(); } // start monitor timer statusTimer.Start(); } private void mediaElement_MediaEnded(object sender, RoutedEventArgs e) { // stop monitor timer statusTimer.Stop(); // media was loaded but ended, stop auto retry ResetAutoRetry(); } private void mediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e) { // store source when fail, otherwise don't know which source was trying to be opened LastSmoothStreamingSource = mediaElement.SmoothStreamingSource; // stop monitor timer statusTimer.Stop(); // auto retry // see if first time media failed if (RetryState == RetryState.None) { OnAutoRetryStart(e.ErrorException); } // see if should try again TimeSpan elapsedTime = DateTime.Now.Subtract(startTime); if (RetryDuration > elapsedTime) { // retry again, first start the timer and // retry during the timer tick event retryTimer.Start(); } else { // time expired, don't retry again OnRetryFailed(e); } } private void OnAutoRetryStart(Exception exception) { // store current time so can tell when time expires startTime = DateTime.Now; RetryState = RetryState.Retrying; if (Retrying != null) { // TODO: jack Retrying(this, new SimpleEventArgs<Exception>(exception)); } } private void OnRetrySucceeded() { RetryAttempt = 0; ResetAutoRetry(); // restore state of player if (mediaElement.IsLive && LastPosition == TimeSpan.Zero) { // go to live if a live feed and don't have a last position, // most likely this is the result of the first load attempt mediaElement.StartSeekToLive(); } else { // restore position mediaElement.Position = LastPosition; } if (RetrySuccessful != null) { RetrySuccessful(this, new RoutedEventArgs()); } } private void OnRetryFailed(ExceptionRoutedEventArgs e) { // gave up on auto retry ResetAutoRetry(); RetryState = RetryState.RetriesFailed; if (RetryFailed != null) { RetryFailed(this, e); } } } }
using MVCCustomer.Entities; using MVCCustomer.Services; using Microsoft.AspNetCore.Mvc; using MVCCustomer.ViewModels; using System.Linq; using System; namespace MVCCustomer.Controllers { public class CustomerController : Controller { public ICustomerData _customerData; public CustomerController(ICustomerData customerData) { _customerData = customerData; } public ViewResult Index() { var model = new CustomerViewModel(); model.Customers = _customerData.GetAll(); return View(model); } //public ViewResult Index(string errorMessage) //{ // var model = new CustomerViewModel(); // model.Customers = _customerData.GetAll(); // return View(model); //} [HttpGet] public IActionResult Edit(int id) { var model = _customerData.Get(id); if (model == null) { return RedirectToAction("Index"); } return View(model); } [HttpPost] public IActionResult Edit(int id, CustomerEditViewModel input) { var customer = _customerData.Get(id); if (customer != null && ModelState.IsValid) { customer.FirstName = input.FirstName; customer.LastName = input.LastName; customer.Email = input.Email; customer.FavoriteColor = input.FavoriteColor; _customerData.Commit(); return RedirectToAction("Details", new { id = customer.Id }); } return View(customer); } [HttpGet] public ViewResult Create() { return View(); } [HttpPost] public IActionResult Create(CustomerEditViewModel model) { var result = TryValidateModel(model); if (ModelState.IsValid) { var customer = new Customer(); customer.FirstName = model.FirstName; customer.LastName = model.LastName; customer.Email = model.Email; customer.FavoriteColor = model.FavoriteColor; if (_customerData.Add(customer) == false) { return View("ErrorEmail", customer); } _customerData.Commit(); return RedirectToAction("Index"); } return View(); } public IActionResult Details(int id) { var model = _customerData.Get(id); if (model == null) { return RedirectToAction("Index"); } return View(model); } } }
using System; using System.Collections.Generic; namespace Eric.Morrison.Harmony.Chords { public class ChordFormulaFunctionalEqualityComparer : IEqualityComparer<ChordFormula> { public bool Equals(ChordFormula x, ChordFormula y) {//Don't compare keys, due to BorrowedChordHarmonicAnalysisRule dependence. var result = false; if (x.Root == y.Root) { if (x.IsDiminished && y.IsDiminished) result = true; else if (!result && x.IsDominant && y.IsDominant) result = true; #warning This is going to match I, IV and V chords in a Major Scale. else if (!result && x.IsMajor && y.IsMajor) { result = true; } else if (!result && x.IsMinor && y.IsMinor) result = true; } return result; } public int GetHashCode(ChordFormula obj) { throw new NotImplementedException(); } } }
using System.Diagnostics.CodeAnalysis; namespace Cake.Common.Tools.DotCover { /// <summary> /// Represents DotCover ReportType /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DotCoverReportType { /// <summary> /// ReportType: <c>XML</c> /// </summary> XML = 0, /// <summary> /// ReportType: <c>HTML</c> /// </summary> HTML, /// <summary> /// ReportType: <c>JSON</c> /// </summary> JSON, /// <summary> /// ReportType: <c>DetailedXML</c> /// </summary> DetailedXML, /// <summary> /// ReportType: <c>NDependXML</c> /// </summary> NDependXML, } }
using UnityEngine; namespace Juniper.Animation { /// <summary> /// Performs a shrinking/growing animation on scene transitions. /// </summary> [DisallowMultipleComponent] public class AlphaTransition : AbstractTransitionController { /// <summary> /// The minimum opacity of the object, where 0 = completely transparent. /// </summary> public float minAlpha = 0; /// <summary> /// The maximum opacity of the object, where 1 = completely opaque. /// </summary> public float maxAlpha = 1; /// <summary> /// The amount of time it takes to complete the transition. /// </summary> public float length = 0.25f; /// <summary> /// The amount of time it takes to complete the transition. /// </summary> public override float TransitionLength { get { return length; } } /// <summary> /// The scale range the transition has to traverse. /// </summary> protected float DeltaAlpha { get { return maxAlpha - minAlpha; } } /// <summary> /// Updates the size of the transitioning object every frame the transition is active. /// </summary> /// <param name="value"></param> protected override void RenderValue(float value) { if (transitionMaterial == null) { var rend = GetComponent<Renderer>(); if (rend != null) { transitionMaterial = rend.GetMaterial(); } } if (transitionMaterial != null) { var o = Mathf.Clamp01(minAlpha + value * DeltaAlpha); transitionMaterial.SetFloat("_Alpha", o); } } /// <summary> /// The material on which the opacity is being set. /// </summary> private Material transitionMaterial; } }
//----------------------------------------------------------------------- // <copyright file="PropertyChangingEventArgs.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Arguments object containing information about</summary> //----------------------------------------------------------------------- #if (ANDROID || IOS) || NETFX_CORE using System; namespace Csla.Core { /// <summary> /// Arguments object containing information about /// a property changing. /// </summary> public class PropertyChangingEventArgs : System.EventArgs { private string _propertyName = string.Empty; /// <summary> /// Creates an instnace of the object. /// </summary> /// <param name="propertyName"> /// Name of the property that is changing. /// </param> public PropertyChangingEventArgs(string propertyName) { _propertyName = propertyName; } /// <summary> /// Gets the name of the changing property. /// </summary> public string PropertyName { get { return _propertyName; } } } } #endif
using FatturaElettronica.Common; using FluentValidation; using FluentValidation.TestHelper; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FatturaElettronica.Test.Ordinaria { [TestClass] public abstract class DenominazioneNomeCognomeValidator<TClass, TValidator> : BaseClass<TClass, TValidator> where TClass : DenominazioneNomeCognome where TValidator : IValidator<TClass> { [TestMethod] public void DenominazioneIsRequiredWhenNomeCognomeIsEmpty() { Challenge.Nome = null; Challenge.Cognome = null; AssertRequired(x => x.Denominazione, expectedErrorCode: "00200"); AssertMinMaxLength(x => x.Denominazione, 1, 80, expectedErrorCode: "00200"); AssertMustBeLatin1Supplement(x => x.Denominazione); } [TestMethod] public void DenominazioneMustBeEmptyWhenNomeCognoneIsNotEmpty() { Challenge.Nome = "nome"; Challenge.Denominazione = "x"; Validator.ShouldHaveValidationErrorFor(x => x.Denominazione, Challenge).WithErrorCode("00200"); Challenge.Denominazione = null; Validator.ShouldNotHaveValidationErrorFor(x => x.Denominazione, Challenge); Challenge.Denominazione = string.Empty; Validator.ShouldNotHaveValidationErrorFor(x => x.Denominazione, Challenge); } [TestMethod] public void NomeIsRequiredWhenDenominazioneIsEmpty() { Challenge.Denominazione = null; AssertRequired(x => x.Nome, expectedErrorCode: "00200"); AssertMinMaxLength(x => x.Nome, 1, 60, expectedErrorCode: "00200"); AssertMustBeLatin1Supplement(x => x.Nome); } [TestMethod] public void NomeMustBeEmptyWhenDenominazioneIsNotEmpty() { Challenge.Denominazione = "denominazione"; Challenge.Nome = "x"; Validator.ShouldHaveValidationErrorFor(x => x.Nome, Challenge).WithErrorCode("00200"); Challenge.Nome = null; Validator.ShouldNotHaveValidationErrorFor(x => x.Nome, Challenge); Challenge.Nome = string.Empty; Validator.ShouldNotHaveValidationErrorFor(x => x.Nome, Challenge); } [TestMethod] public void CognomeIsRequiredWhenDenominazioneIsEmpty() { Challenge.Denominazione = null; AssertRequired(x => x.Cognome, expectedErrorCode: "00200"); AssertMinMaxLength(x => x.Cognome, 1, 60, expectedErrorCode: "00200"); AssertMustBeLatin1Supplement(x => x.Cognome); } [TestMethod] public void CognomeMustBeEmptyWhenDenominazioneIsNotEmpty() { Challenge.Denominazione = "denominazione"; Challenge.Cognome = "x"; Validator.ShouldHaveValidationErrorFor(x => x.Cognome, Challenge).WithErrorCode("00200"); Challenge.Cognome = null; Validator.ShouldNotHaveValidationErrorFor(x => x.Cognome, Challenge); Challenge.Cognome = string.Empty; Validator.ShouldNotHaveValidationErrorFor(x => x.Cognome, Challenge); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Cake.Core; namespace Cake.Helpers.Tasks { internal class HelperTask : IHelperTask { internal const string DefaultTaskCategory = "Generic"; internal const string DefaultTaskType = "Unknown"; private string _Category = DefaultTaskCategory; /// <inheritdoc /> public string Category { get { if (string.IsNullOrWhiteSpace(this._Category)) { this._Category = DefaultTaskCategory; } return this._Category; } set { this._Category = value; } } private string _TaskType = DefaultTaskType; /// <inheritdoc /> public string TaskType { get { if (string.IsNullOrWhiteSpace(this._TaskType)) { this._TaskType = DefaultTaskType; } return this._TaskType; } set { this._TaskType = value; } } /// <inheritdoc /> public bool IsTarget { get; set; } /// <inheritdoc /> public ActionTask Task { get; set; } /// <inheritdoc /> public string TaskName { get { return this.Task?.Name; } } } [ExcludeFromCodeCoverage] internal class TaskCache : IDictionary<string, IHelperTask> { #region Private Fields private ConcurrentDictionary<string, IHelperTask> _Cache = new ConcurrentDictionary<string, IHelperTask>(); #endregion #region IDictionary Members /// <inheritdoc /> public IEnumerator<KeyValuePair<string, IHelperTask>> GetEnumerator() { return this._Cache.GetEnumerator(); } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) this._Cache).GetEnumerator(); } /// <inheritdoc /> public void Add(KeyValuePair<string, IHelperTask> item) { this._Cache.AddOrUpdate(item.Key, item.Value, (s, task) => item.Value); } /// <inheritdoc /> public void Clear() { this._Cache.Clear(); } /// <inheritdoc /> public bool Contains(KeyValuePair<string, IHelperTask> item) { return this._Cache.Contains(item); } /// <inheritdoc /> public void CopyTo(KeyValuePair<string, IHelperTask>[] array, int arrayIndex) { } /// <inheritdoc /> public bool Remove(KeyValuePair<string, IHelperTask> item) { return this.Remove(item.Key); } /// <inheritdoc /> public int Count { get { return this._Cache.Count; } } /// <inheritdoc /> public bool IsReadOnly { get { return false; } } /// <inheritdoc /> public bool ContainsKey(string key) { return this._Cache.ContainsKey(key); } /// <inheritdoc /> public void Add(string key, IHelperTask value) { this.Add(new KeyValuePair<string, IHelperTask>(key, value)); } /// <inheritdoc /> public bool Remove(string key) { return this._Cache.TryRemove(key, out IHelperTask task); } /// <inheritdoc /> public bool TryGetValue(string key, out IHelperTask value) { return this._Cache.TryGetValue(key, out value); } /// <inheritdoc /> public IHelperTask this[string key] { get { return this._Cache[key]; } set { this._Cache.GetOrAdd(key, value); } } /// <inheritdoc /> public ICollection<string> Keys { get { return this._Cache.Keys; } } /// <inheritdoc /> public ICollection<IHelperTask> Values { get { return this._Cache.Values; } } #endregion } }
using System.Threading.Tasks; using Microsoft.AspNetCore.JsonPatch; using Microsoft.EntityFrameworkCore; using Nervestaple.EntityFrameworkCore.Models.Entities; using Nervestaple.EntityFrameworkCore.Repositories; namespace Nervestaple.WebService.Repositories { /// <summary> /// Extends the standard repository with methods that can accept a /// JsonPatchDocument for updating entity instances. /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <typeparam name="K">Entity's unique identifier type</typeparam> public class AbstractWebReadWriteRepository<T, K> : AbstractReadWriteRepository<T, K>, IWebReadWriteRepository<T, K> where T : Entity<K> where K : struct { /// <summary> /// Creates a new repository instance. /// </summary> /// <param name="context">the database context to use</param> /// <returns>a new instance</returns> public AbstractWebReadWriteRepository(DbContext context) : base(context) { } /// <summary> /// Returns a current copy of the entity after updating the Entity with /// the matching unique identifier with the values provided in the model /// <param name="id">Unique ID of the Entity to update</param> /// <param name="model">Data object used to update the Entity</param> /// </summary> public T Update(K id, JsonPatchDocument<AbstractEntity> model) { return HandlePatchUpdate(id, model); } /// <summary> /// Returns a current copy of the entity after updating the Entity with /// the matching unique identifier with the values provided in the model /// <param name="id">Unique ID of the Entity to update</param> /// <param name="model">Data object used to update the Entity</param> /// </summary> public async Task<T> UpdateAsync(K id, JsonPatchDocument<AbstractEntity> model) { return await HandlePatchUpdateAsync(id, model); } /// <summary> /// Called after updating of the Entity and before that Entity is /// persisted /// </summary> public virtual T PostUpdate(T instance, JsonPatchDocument<AbstractEntity> model) { return PostUpdateAsync(instance, model).Result; } /// <summary> /// Called after updating of the Entity and before that Entity is /// persisted /// </summary> public virtual async Task<T> PostUpdateAsync(T instance, JsonPatchDocument<AbstractEntity> model) { return instance; } /// <summary> /// Updates the entity with the values from the JSON patch document and /// then saves the entity /// </summary> /// <param name="id">unique identifier of the entity</param> /// <param name="model">model with new values</param> /// <returns>the updated entity instance</returns> protected virtual T HandlePatchUpdate(K id, JsonPatchDocument<AbstractEntity> model) { return HandlePatchUpdateAsync(id, model).Result; } /// <summary> /// Updates the entity with the values from the JSON patch document and /// then saves the entity /// </summary> /// <param name="id">unique identifier of the entity</param> /// <param name="model">model with new values</param> /// <returns>the updated entity instance</returns> protected virtual async Task<T> HandlePatchUpdateAsync(K id, JsonPatchDocument<AbstractEntity> model) { // fetch the target instance var instance = await FindAsync(id); // update the target instance's fields with the model's values model.ApplyTo(instance); // save and return the target instance Context.Update(instance); instance = await PostUpdateAsync(instance, model); await Context.SaveChangesAsync(); return instance; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.Xna.Framework; //using Microsoft.Xna.Framework.Audio; //using Microsoft.Xna.Framework.Content; //using Microsoft.Xna.Framework.Graphics; //using Microsoft.Xna.Framework.Input; //using Microsoft.Xna.Framework.Storage; using Boku.Base; using Boku.Common; using Boku.UI; using Boku.UI2D; using Boku.Input; using Boku.SimWorld; using Boku.SimWorld.Terra; namespace Boku.Scenes.InGame.Tools { public class RoadTool : BaseTool { #region Members private static RoadTool instance = null; private bool rightTriggered = false; #endregion Members #region Public // c'tor public RoadTool() { Description = Strings.Instance.tools.roadTool; HelpOverlayID = @"RoadTool"; HelpOverlayStartID = @"RoadToolStart"; HelpOverlayGoingID = @"RoadToolGoing"; IconTextureName = @"\UI2D\Tools\RoadTool"; } // end of c'tor public static BaseTool GetInstance() { if (instance == null) { instance = new RoadTool(); } return instance; } // end of RoadTool GetInstance() public override void Update() { if (Active) { CheckSelectCursor(); if (DebouncePending) return; CheckLevel(); ProcessTriggers( Terrain.EditMode.Road, Terrain.EditMode.RoadSnap, Terrain.EditMode.Smooth); SelectOverlay(); } base.Update(); } // end of RoadTool Update() #endregion Public #region Internal protected override void SelectOverlay() { if (StretchGoing && rightTriggered) { HelpOverlay.Pop(); HelpOverlay.Push(@"RoadToolRightTrig"); } else { base.SelectOverlay(); } } /// <summary> /// If we're using the right trigger, then null out the a button action. /// It will still advance the cursor, but we don't want to do a road snap over it. /// </summary> /// <param name="rightMode"></param> /// <param name="aButton"></param> /// <param name="leftMode"></param> protected override void ProcessStretched( Terrain.EditMode rightMode, Terrain.EditMode aButton, Terrain.EditMode leftMode) { GamePadInput pad = GamePadInput.GetGamePad1(); if (StretchGoing && RightTriggerOn) { rightTriggered = true; } aButton = rightTriggered ? Terrain.EditMode.Noop : Terrain.EditMode.RoadSnap; base.ProcessStretched(Terrain.EditMode.Road, aButton, Terrain.EditMode.Smooth); if (pad.ButtonA.WasPressed) { rightTriggered = false; } } /// <summary> /// Grab snapshot terrain heights as appropriate. /// </summary> private void CheckLevel() { GamePadInput pad = GamePadInput.GetGamePad1(); if (pad.ButtonA.WasPressed) { inGame.Terrain.LevelStart = Terrain.GetTerrainHeight(shared.editBrushStart); } if(shared.editBrushMoved) { inGame.Terrain.LevelHeight = Terrain.GetTerrainHeight(shared.editBrushPosition); } } public override void OnActivate() { base.OnActivate(); PickerX = brushPicker; brushPicker.BrushSet = Brush2DManager.BrushType.StretchedAll; } // end of HeightMapTool OnActivate() public override void OnDeactivate() { base.OnDeactivate(); } // end of RoadTool OnDeactivate() #endregion Internal } // class RoadTool } // end of namespace Boku.Scenes.InGame.Tools
using System.Collections.Generic; namespace GridExplorerBot { public class Game { public const int numRoomRows = 8; public const int numRoomColumns = 8; public const int numCommandResponseRows = 1; public const int numInventoryRows = 1; public const int numSaveDataRows = 1; public const int numTotalRows = numCommandResponseRows + numRoomRows + numInventoryRows + numSaveDataRows; public const int saveDataRowIndex = numTotalRows - 1; const InitialRooms.ID defaultInitialRoom = InitialRooms.ID.Overworld; const string newGameCommand = "New Game"; string mLastCommandResponse = newGameCommand; public static System.Random random = null; public Room mRoom = null; public Inventory mInventory = null; public GameTime mGameTime = null; public static Dictionary<int,NPCIdentityData> mNPCIdentities = null; string mSaveDataString = ""; InitialRooms.ID mTeleportDestinationRoomID = InitialRooms.ID.Unknown; Point? mTeleportDestinationSpawnLocation = null; // Returns true if the game was successfully parsed public bool ParsePreviousText(string inputText) { string[] lines = inputText.Split('\n'); if (lines.Length != numTotalRows) { return false; } string saveDataLine = lines[saveDataRowIndex]; mRoom = new Room(); mInventory = new Inventory(); mGameTime = new GameTime(); mNPCIdentities = new Dictionary<int, NPCIdentityData>(); InitialRooms.Initialize(); Load( saveDataLine ); return true; } public void GenerateFreshGame(InitialRooms.ID initialRoomID = defaultInitialRoom) { mLastCommandResponse = newGameCommand; mInventory = new Inventory(); mRoom = new Room(); mGameTime = new GameTime(); mNPCIdentities = InitialRooms.identityData; InitialRooms.Initialize(); mRoom.CreateFrom(initialRoomID, this); } public void ChangeToRoom(InitialRooms.ID initialRoomID) { mRoom.CreateFrom(initialRoomID, this); } public string Render() { string commandResponse = mLastCommandResponse; commandResponse = commandResponse.Substring(0,1).ToUpper() + commandResponse.Substring(1); string roomRender = mRoom.Render(); string inventory = mInventory.Render(); string saveData = mSaveDataString; return commandResponse + '\n' + roomRender + '\n' + inventory + '\n' + saveData; } public void Simulate(string inputCommand) { mLastCommandResponse = mRoom.Simulate(inputCommand, this); if (mTeleportDestinationRoomID != InitialRooms.ID.Unknown && mTeleportDestinationSpawnLocation != null) { ChangeToRoom(mTeleportDestinationRoomID); mRoom.TeleportPlayerTo(mTeleportDestinationSpawnLocation.Value); mLastCommandResponse = mRoom.mDescription; } mGameTime.Increment(); } public void Save() { // arbitrary estimated size WriteStream stream = new WriteStream(36); Stream(stream); mSaveDataString = StringUtils.SaveDataEncode(stream.GetStreamData()); } public void Load(string saveData) { byte[] bytes = StringUtils.SaveDataDecode(saveData); ReadStream stream = new ReadStream(bytes); Stream(stream); } private void Stream(SaveStream stream) { if (!stream.IsWriting()) { NPCIdentifier.currentMaxID = 0; } mInventory.Stream(stream); mRoom.Stream(stream); mGameTime.Stream(stream); int numNPCData = mNPCIdentities.Count; stream.Stream(ref numNPCData, SaveUtils.GetNumBitsToStoreValue(NPCIdentifier.maxNumNPCs)); if (stream.IsWriting()) { foreach (KeyValuePair<int,NPCIdentityData> pair in mNPCIdentities) { int id = pair.Key; stream.Stream(ref id, SaveUtils.GetNumBitsToStoreValue(NPCIdentifier.maxNumNPCs - 1)); pair.Value.Stream(stream); } } else { mNPCIdentities.Clear(); for (int npcIdentityIndex = 0; npcIdentityIndex < numNPCData; npcIdentityIndex++) { int id = 0; NPCIdentityData data = new NPCIdentityData(); stream.Stream(ref id, SaveUtils.GetNumBitsToStoreValue(NPCIdentifier.maxNumNPCs - 1)); data.Stream(stream); mNPCIdentities[id] = data; } } } public void SetTeleport(InitialRooms.ID destinationRoomID, Point destinationSpawnLocation) { mTeleportDestinationRoomID = destinationRoomID; mTeleportDestinationSpawnLocation = destinationSpawnLocation; } public static void InitializeRandom(System.DateTimeOffset seedTime) { random = new System.Random((int)seedTime.ToUnixTimeSeconds()); } public static bool MatchesResetCommand(string input) { return PlayerCharacter.MatchesResetCommand(input); } public static bool MatchesHelpCommand(string input) { return PlayerCharacter.MatchesHelpCommand(input); } public static string GetCommandsList() { PlayerCharacter pc = new PlayerCharacter(); return pc.GetCommandsListText(); } public void AwardMobilePhone() { mInventory.AddItem(Objects.ID.MobilePhone); mLastCommandResponse = "Thank you so much for your prayers! Here's your mobile phone."; } } }
using UnityEngine; public abstract class GenericPrefabFactory<T> where T : MonoBehaviour { protected T m_component; private GameObject m_prefab; public GenericPrefabFactory(GameObject prefab) { m_prefab = prefab; m_component = m_prefab.GetComponent<T>(); if (m_component == null && typeof(T) != typeof(MonoBehaviour)) { m_component = m_prefab.AddComponent<T>(); } } public void Add(TextAsset asset) { Deserialize(asset); } protected virtual void Deserialize(TextAsset xmlAsset) { Debug.LogWarning("Deserialize: routine not implemented."); } protected GameObject AddChild(string name) { GameObject element = new GameObject(name); element.transform.SetParent(m_prefab.transform); return element; } }
using ApplicationServices.DTOs; using MVC.CompanyService; using MVC.Units; using MVC.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace MVC.Controllers { public class ProjectEmployeeController : Controller { // GET: ProjectEmployee [HttpGet] [Authorize] public async Task<ActionResult> Index(string name) { List<ProjectEmployeeViewModel> peVM = new List<ProjectEmployeeViewModel>(); using (Service1Client service = new Service1Client()) { foreach (var item in service.GetProjectEmployees()) { peVM.Add(new ProjectEmployeeViewModel(item)); } } if (!String.IsNullOrEmpty(name)) { peVM.Clear(); using (Service1Client service = new Service1Client()) { foreach (var item in service.GetAllProjectEmployeeByName(name)) { peVM.Add(new ProjectEmployeeViewModel(item)); } } return View(peVM); } return View(peVM); } [HttpGet] [Authorize] public async Task<ActionResult> Details(int id) { ProjectEmployeeViewModel peVM = new ProjectEmployeeViewModel(); using (Service1Client service = new Service1Client()) { var peDto = service.GetProjectEmployeeById(id); peVM = new ProjectEmployeeViewModel(peDto); } return View(peVM); } [HttpGet] [Authorize] public ActionResult Create() { using (Service1Client service = new Service1Client()) { ViewBag.Projects = new SelectList(service.GetProjects(), "Id", "Name"); ViewBag.Employees = new SelectList(service.GetEmployees(), "Id", "FirstName"); } return View(); } [HttpPost] [Authorize] [ValidateAntiForgeryToken] public async Task<ActionResult> Create(ProjectEmployeeViewModel peVM) { try { using (Service1Client service = new Service1Client()) { ProjectEmployeeDto peDto = new ProjectEmployeeDto { id_project = peVM.projectID, projectDto = new ProjectDto { Id = peVM.projectID }, id_employee = peVM.employeeId, employeeDto = new EmployeeDto { Id = peVM.employeeId } }; service.PostProjectEmployee(peDto); } ViewBag.Projects = LoadProjects.LoadProjectsData(); ViewBag.Employees = LoadEmployees.LoadEmployeesData(); return RedirectToAction("Index"); } catch { ViewBag.Projects = LoadProjects.LoadProjectsData(); ViewBag.Employees = LoadEmployees.LoadEmployeesData(); return View(); } } [HttpGet] [Authorize] public async Task<ActionResult> Edit(int id) { ProjectEmployeeViewModel peVM = new ProjectEmployeeViewModel(); using (Service1Client service = new Service1Client()) { var peDto = service.GetProjectEmployeeById(id); peVM = new ProjectEmployeeViewModel(peDto); } ViewBag.Projects = LoadProjects.LoadProjectsData(); ViewBag.Employees = LoadEmployees.LoadEmployeesData(); return View(peVM); } [HttpPost] [Authorize] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit(ProjectEmployeeViewModel peVM) { try { if (ModelState.IsValid) { using (Service1Client service = new Service1Client()) { ProjectEmployeeDto peDto = new ProjectEmployeeDto { Id = peVM.Id, id_project = peVM.projectID, projectDto = new ProjectDto { Id = peVM.projectID }, id_employee = peVM.employeeId, employeeDto = new EmployeeDto { Id = peVM.employeeId } }; service.PutProjectEmployee(peDto); } ViewBag.Projects = LoadProjects.LoadProjectsData(); ViewBag.Employees = LoadEmployees.LoadEmployeesData(); return RedirectToAction("Index"); } ViewBag.Projects = LoadProjects.LoadProjectsData(); ViewBag.Employees = LoadEmployees.LoadEmployeesData(); return View(); } catch { ViewBag.Projects = LoadProjects.LoadProjectsData(); ViewBag.Employees = LoadEmployees.LoadEmployeesData(); return View(); } } [Authorize] [ValidateAntiForgeryToken] public async Task<ActionResult> Delete(int id) { ProjectEmployeeViewModel peVM = new ProjectEmployeeViewModel(); using (Service1Client service = new Service1Client()) { service.DeleteProjectEmployee(id); } return RedirectToAction("Index"); } } }
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Splat.SimpleInjector { /// <summary> /// sad. /// </summary> #pragma warning disable CA1063 // Implement IDisposable Correctly public class SimpleInjectorInitializer : IDependencyResolver #pragma warning restore CA1063 // Implement IDisposable Correctly { private readonly object _lockObject = new object(); /// <summary> /// Gets dictionary of registered factories. /// </summary> public Dictionary<Type, List<Func<object>>> RegisteredFactories { get; } = new Dictionary<Type, List<Func<object>>>(); /// <inheritdoc /> public object GetService(Type serviceType, string contract = null) { lock (_lockObject) { Func<object> fact = RegisteredFactories[serviceType].LastOrDefault(); return fact?.Invoke(); } } /// <inheritdoc/> public IEnumerable<object> GetServices(Type serviceType, string contract = null) { lock (_lockObject) { return RegisteredFactories[serviceType] .Select(n => n()); } } /// <inheritdoc /> public bool HasRegistration(Type serviceType, string contract = null) { lock (_lockObject) { return RegisteredFactories.TryGetValue(serviceType, out List<Func<object>> values) && values.Any(); } } /// <inheritdoc /> public void Register(Func<object> factory, Type serviceType, string contract = null) { lock (_lockObject) { if (!RegisteredFactories.ContainsKey(serviceType)) { RegisteredFactories.Add(serviceType, new List<Func<object>>()); } RegisteredFactories[serviceType].Add(factory); } } /// <inheritdoc /> public void UnregisterCurrent(Type serviceType, string contract = null) { throw new NotImplementedException(); } /// <inheritdoc /> public void UnregisterAll(Type serviceType, string contract = null) { lock (_lockObject) { if (RegisteredFactories.ContainsKey(serviceType)) { RegisteredFactories.Remove(serviceType); } } } /// <inheritdoc /> public IDisposable ServiceRegistrationCallback(Type serviceType, string contract, Action<IDisposable> callback) { throw new NotImplementedException(); } /// <inheritdoc /> #pragma warning disable CA1063 // Implement IDisposable Correctly public void Dispose() #pragma warning restore CA1063 // Implement IDisposable Correctly { } } }
using Spear.Framework; using Spear.Sharp.Contracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Threading.Tasks; namespace Spear.Sharp.Tests { [TestClass] public class DatabaseTest : DTest { private readonly IDatabaseContract _contract; public DatabaseTest() { _contract = Resolve<IDatabaseContract>(); } [TestMethod] public async Task TablesTest() { var db = await _contract.GetAsync("b5ff8cc7-2100-ced2-d13a-08d67552b2a1"); Print(db); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace California.Creator.Service.Models.Core { public class Webfont { public int WebfontId { get; set; } [Required] public string Family { get; set; } [Required] public string Version { get; set; } } }
@page @model RegisterModel @{ ViewData["Title"] = "Регистрирай се"; } <section id="register"> <form id="register-form" method="post" enctype="multipart/form-data"> <div class="container"> <h1>Регистрация</h1> <label asp-for="Input.Email">Потребителско име</label> <input id="username" asp-for="Input.Email" type="text" placeholder="Въведете потребителско име"> <span asp-validation-for="Input.Email" class="text-danger"></span> <label asp-for="Input.Password">Парола</label> <input id="password" asp-for="Input.Password" type="password" placeholder="Въведете парола"> <span asp-validation-for="Input.Password" class="text-danger"></span> <label asp-for="Input.ConfirmPassword">Повторете паролата</label> <input id="repeatPass" asp-for="Input.ConfirmPassword" type="password" placeholder="Повторете паролата"> <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span> <label asp-for="Input.PhoneNumber">Телефонен номер</label> <input id="phoneNumber" asp-for="Input.PhoneNumber" type="text" placeholder="Телефонен номер"> <span asp-validation-for="Input.PhoneNumber" class="text-danger"></span> <label asp-for="Input.Images">Документ за самоличност</label> <input id="images" asp-for="Input.Images" placeholder="Документ за самоличност"> <span asp-validation-for="Input.Images" class="text-danger"></span><br /> <input type="submit" class="registerbtn button" value="Регистрирай се"> <div class="container signin"> <p>Вече имате създаден акаунт? <a href="login" class="loginLink">Влезте</a>.</p> </div> </div> </form> </section> @section Scripts { <partial name="_ValidationScriptsPartial" /> }