content
stringlengths
23
1.05M
using Common; using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace WebApi.Configuration { internal class ConfigReader : IConfiguration { #region Fields private ushort transactionId = 0; private byte unitAddress; private int tcpPort; private ConfigItemEqualityComparer confItemEqComp = new ConfigItemEqualityComparer(); private Dictionary<string, IConfigItem> pointTypeToConfiguration = new Dictionary<string, IConfigItem>(); private string path = "RtuCfg.txt"; #endregion public ConfigReader() { if (!File.Exists(path)) { throw new Exception("File doesn't exist!"); } ReadConfiguration(); } /// <summary> /// Gets aquisition interval for specified point description /// </summary> /// <param name="pointDescription">Requested point description</param> /// <returns>Acquisition interval</returns> public int GetAcquisitionInterval(string pointDescription) { IConfigItem ci; if (pointTypeToConfiguration.TryGetValue(pointDescription, out ci)) { return ci.AcquisitionInterval; } throw new ArgumentException(string.Format("Invalid argument:{0}", nameof(pointDescription))); } /// <summary> /// Returns start address for specified point description /// </summary> /// <param name="pointDescription">Requested point description</param> /// <returns>Start address</returns> public ushort GetStartAddress(string pointDescription) { IConfigItem ci; if (pointTypeToConfiguration.TryGetValue(pointDescription, out ci)) { return ci.StartAddress; } throw new ArgumentException(string.Format("Invalid argument:{0}", nameof(pointDescription))); } /// <summary> /// Gets number of registers for specific point description /// </summary> /// <param name="pointDescription"></param> /// <returns>Number of registers</returns> public ushort GetNumberOfRegisters(string pointDescription) { IConfigItem ci; if (pointTypeToConfiguration.TryGetValue(pointDescription, out ci)) { return ci.NumberOfRegisters; } throw new ArgumentException(string.Format("Invalid argument:{0}", nameof(pointDescription))); } /// <summary> /// Reads configuration file /// </summary> private void ReadConfiguration() { using (TextReader tr = new StreamReader(path)) { string s = string.Empty; while ((s = tr.ReadLine()) != null) { string[] splited = s.Split(' ', '\t'); List<string> filtered = splited.ToList().FindAll(t => !string.IsNullOrEmpty(t)); if (filtered.Count == 0) { continue; } if (s.StartsWith("STA")) { unitAddress = Convert.ToByte(filtered[filtered.Count - 1]); continue; } if (s.StartsWith("TCP")) { TcpPort = Convert.ToInt32(filtered[filtered.Count - 1]); continue; } if (s.StartsWith("DBC")) { DelayBetweenCommands = Convert.ToInt32(filtered[filtered.Count - 1]); continue; } try { ConfigItem ci = new ConfigItem(filtered); if (pointTypeToConfiguration.Count > 0) { foreach (ConfigItem cf in pointTypeToConfiguration.Values) { if (!confItemEqComp.Equals(cf, ci)) { pointTypeToConfiguration.Add(ci.Description, ci); break; } } } else { pointTypeToConfiguration.Add(ci.Description, ci); } } catch (ArgumentException argEx) { throw new Exception($"Configuration error: {argEx.Message}", argEx); } catch (Exception ex) { throw ex; } } if (pointTypeToConfiguration.Count == 0) { throw new Exception("Configuration error! Check RtuCfg.txt file!"); } } } /// <summary> /// Returns transcation id /// </summary> /// <returns>Transaction Id</returns> public ushort GetTransactionId() { return transactionId++; } #region Properties public byte UnitAddress { get { return unitAddress; } private set { unitAddress = value; } } public int TcpPort { get { return tcpPort; } private set { tcpPort = value; } } private int dbc; public int DelayBetweenCommands { get { return dbc; } private set { dbc = value; } } #endregion /// <summary> /// Returns list of configuration items /// </summary> /// <returns>List of configuration items</returns> public List<IConfigItem> GetConfigurationItems() { return new List<IConfigItem>(pointTypeToConfiguration.Values); } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.ComponentModel; namespace UPnPValidator { /// <summary> /// Summary description for SendLogFrom. /// </summary> public class SendLogFrom : System.Windows.Forms.Form { private System.Windows.Forms.Label CompanyLabel; private System.Windows.Forms.TextBox CompanyNameTextBox; private System.Windows.Forms.TextBox EmailAddressTextBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private new System.Windows.Forms.Button CancelButton; private System.Windows.Forms.Button SendButton; private System.Windows.Forms.TextBox DeviceDescriptionTextBox; private System.Windows.Forms.TextBox SMTPServerTextBox; private System.Windows.Forms.Label label3; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public SendLogFrom() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } public new string CompanyName { get {return CompanyNameTextBox.Text;} } public string EmailAddress { get {return EmailAddressTextBox.Text;} } public string DeviceDescription { get {return DeviceDescriptionTextBox.Text;} } public string SMTPServer { get {return SMTPServerTextBox.Text;} set {SMTPServerTextBox.Text = value;} } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SendLogFrom)); this.CompanyLabel = new System.Windows.Forms.Label(); this.CompanyNameTextBox = new System.Windows.Forms.TextBox(); this.EmailAddressTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.DeviceDescriptionTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.CancelButton = new System.Windows.Forms.Button(); this.SendButton = new System.Windows.Forms.Button(); this.SMTPServerTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // CompanyLabel // this.CompanyLabel.Location = new System.Drawing.Point(16, 18); this.CompanyLabel.Name = "CompanyLabel"; this.CompanyLabel.Size = new System.Drawing.Size(120, 16); this.CompanyLabel.TabIndex = 0; this.CompanyLabel.Text = "Company"; // // CompanyNameTextBox // this.CompanyNameTextBox.Location = new System.Drawing.Point(152, 16); this.CompanyNameTextBox.Name = "CompanyNameTextBox"; this.CompanyNameTextBox.Size = new System.Drawing.Size(192, 20); this.CompanyNameTextBox.TabIndex = 1; this.CompanyNameTextBox.Text = ""; // // EmailAddressTextBox // this.EmailAddressTextBox.Location = new System.Drawing.Point(152, 48); this.EmailAddressTextBox.Name = "EmailAddressTextBox"; this.EmailAddressTextBox.Size = new System.Drawing.Size(192, 20); this.EmailAddressTextBox.TabIndex = 3; this.EmailAddressTextBox.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(16, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(112, 16); this.label1.TabIndex = 2; this.label1.Text = "Email Address"; // // DeviceDescriptionTextBox // this.DeviceDescriptionTextBox.Location = new System.Drawing.Point(152, 112); this.DeviceDescriptionTextBox.Multiline = true; this.DeviceDescriptionTextBox.Name = "DeviceDescriptionTextBox"; this.DeviceDescriptionTextBox.Size = new System.Drawing.Size(192, 64); this.DeviceDescriptionTextBox.TabIndex = 5; this.DeviceDescriptionTextBox.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(16, 112); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(120, 16); this.label2.TabIndex = 4; this.label2.Text = "Device Description"; // // CancelButton // this.CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.CancelButton.Location = new System.Drawing.Point(152, 192); this.CancelButton.Name = "CancelButton"; this.CancelButton.Size = new System.Drawing.Size(96, 23); this.CancelButton.TabIndex = 6; this.CancelButton.Text = "Cancel"; // // SendButton // this.SendButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.SendButton.Location = new System.Drawing.Point(248, 192); this.SendButton.Name = "SendButton"; this.SendButton.Size = new System.Drawing.Size(96, 23); this.SendButton.TabIndex = 7; this.SendButton.Text = "Send"; // // SMTPServerTextBox // this.SMTPServerTextBox.Location = new System.Drawing.Point(152, 80); this.SMTPServerTextBox.Name = "SMTPServerTextBox"; this.SMTPServerTextBox.Size = new System.Drawing.Size(192, 20); this.SMTPServerTextBox.TabIndex = 9; this.SMTPServerTextBox.Text = ""; // // label3 // this.label3.Location = new System.Drawing.Point(16, 80); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(112, 16); this.label3.TabIndex = 8; this.label3.Text = "SMTP Server"; // // SendLogFrom // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(376, 230); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.SMTPServerTextBox, this.label3, this.SendButton, this.CancelButton, this.DeviceDescriptionTextBox, this.label2, this.EmailAddressTextBox, this.label1, this.CompanyNameTextBox, this.CompanyLabel}); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "SendLogFrom"; this.Text = "SendLogFrom"; this.ResumeLayout(false); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.CommunityToolkit.ObjectModel; using Xamarin.Essentials; using Xamarin.Forms; namespace Svg.Skia.Forms.Sample { /// <summary> /// View model for the sample page, providing some image sources to reference from XAML. /// </summary> public class SamplePageViewModel : ObservableObject { /// <summary> /// Backing store for dynamic image size /// </summary> private double dynamicImageSize = 64.0; #region Binding properties /// <summary> /// Image source from stream coming from the app package's Assets folder /// </summary> public ImageSource ImageFromPlatformAssets { get; } /// <summary> /// Image source from a Forms based assmbly, integrated with EmbeddedResource /// </summary> public ImageSource ImageFromFormsAssets { get; } /// <summary> /// Data URL containing base64 encoded SVG image /// </summary> public string SvgImageDataUrlBase64Encoded { get; } = SvgConstants.DataUriBase64Prefix + SvgTestImages.EncodeBase64(SvgTestImages.TestSvgImageText); /// <summary> /// Data URL containing unencoded SVG image /// </summary> public string SvgImageDataUrlUnencoded { get; } = SvgConstants.DataUriPlainPrefix + SvgTestImages.TestSvgImageText; /// <summary> /// Plain SVG image data /// </summary> public string SvgImagePlainData { get; } = SvgTestImages.TestSvgImageText; /// <summary> /// Indicates if dark mode is currently enabled /// </summary> public bool IsDarkModeOn { get => Application.Current.RequestedTheme != OSAppTheme.Light; set => Application.Current.UserAppTheme = value ? OSAppTheme.Dark : OSAppTheme.Light; } /// <summary> /// Command to execute when tapping on an image using a gesture recognizer /// </summary> public ICommand TappedImageCommand { get; } /// <summary> /// Command to execute when user clicked on the "Pick SVG image" button /// </summary> public ICommand PickSvgImageCommand { get; } /// <summary> /// Image source of picked image /// </summary> public ImageSource PickedImage { get; private set; } /// <summary> /// Current image size for dynamic image resizing /// </summary> public double DynamicImageSize { get => this.dynamicImageSize; set => this.SetProperty(ref this.dynamicImageSize, value); } #endregion /// <summary> /// Creates a new view model object and initializes all binding properties /// </summary> public SamplePageViewModel() { this.ImageFromPlatformAssets = ImageSource.FromStream( () => GetPlatformStream()); this.ImageFromFormsAssets = ImageSource.FromResource( SvgTestImages.ResourcePathColibriSvg, typeof(SvgTestImages).Assembly); this.TappedImageCommand = new AsyncCommand(this.TappedImage); this.PickSvgImageCommand = new AsyncCommand(this.PickSvgImage); } /// <summary> /// Returns a stream from the platform's assets folder /// </summary> /// <returns>platform file stream</returns> private static Stream GetPlatformStream() { string filename = "Assets/toucan.svg"; if (DeviceInfo.Platform == DevicePlatform.Android) { filename = filename.Replace("Assets/", string.Empty); } return FileSystem.OpenAppPackageFileAsync(filename).Result; } /// <summary> /// Called when an SVG image is tapped /// </summary> /// <returns>task to wait on</returns> private async Task TappedImage() { await App.Current.MainPage.DisplayAlert( "Svg.Skia.Forms Sample", "Image was tapped", "Close"); } /// <summary> /// Lets the user pick an SVG image from storage and tries to display it /// </summary> /// <returns>task to wait on</returns> private async Task PickSvgImage() { try { var options = new PickOptions { FileTypes = new FilePickerFileType( new Dictionary<DevicePlatform, IEnumerable<string>> { { DevicePlatform.Android, new string[] { "image/svg+xml" } }, { DevicePlatform.UWP, new string[] { ".svg" } }, { DevicePlatform.iOS, null }, }), PickerTitle = "Select an SVG image to display" }; var result = await FilePicker.PickAsync(options); if (result == null || string.IsNullOrEmpty(result.FullPath)) { return; } var stream = await result.OpenReadAsync(); this.PickedImage = ImageSource.FromStream(() => stream); this.OnPropertyChanged(nameof(this.PickedImage)); } catch (Exception ex) { await App.Current.MainPage.DisplayAlert( "Svg.Skia.Forms Sample", "Error while picking an SVG image file: " + ex.Message, "Close"); } } } }
using Universalis.Mogboard.Entities; using Universalis.Mogboard.Entities.Id; namespace Universalis.Mogboard.Identity; public class MogboardAuthenticationService : IMogboardAuthenticationService { private readonly IMogboardTable<User, UserId> _users; private readonly IMogboardSessionTable _sessions; public MogboardAuthenticationService(IMogboardTable<User, UserId> users, IMogboardSessionTable sessions) { _users = users; _sessions = sessions; } public async Task<MogboardUser> Authenticate(string session, CancellationToken cancellationToken = default) { // TODO: Perform a single query for this var sessionInst = await _sessions.Get(session, cancellationToken); if (sessionInst == null) { throw new InvalidOperationException("No session found."); } if (sessionInst.UserId == null) { throw new InvalidOperationException("Session instance does not contain a user ID."); } var userInst = await _users.Get(sessionInst.UserId.Value, cancellationToken); if (userInst == null) { throw new InvalidOperationException("No user found for the retrieved session."); } return new MogboardUser(userInst); } }
// Doc/Reference/Logging.md #if !(UNITY_EDITOR || DEBUG) #define AL_OPTIMIZE #endif #if !AL_OPTIMIZE using Active.Core; using Active.Core.Details; using F = Active.Core.Details.StatusFormat; using L = System.Runtime.CompilerServices.CallerLineNumberAttribute; using V = Active.Core.Details.ValidString; using M = System.Runtime.CompilerServices.CallerMemberNameAttribute; using P = System.Runtime.CompilerServices.CallerFilePathAttribute; using S = System.String; using X = Active.Core.status; using Lg = Active.Core.Details.Logging; using static Active.Status; namespace Active.Core.Details{ public static class Logging{ internal static status Status(in status @base, V reason, S p, S m, int l) => log ? ViaScope(@base, F.SysTrace(p, m, l), reason) : @base; internal static action Action(V reason, S p, S m, int l) => log ? new action(ViaScope(status._done, F.SysTrace(p,m,l), reason).meta) : action._done; internal static failure Failure(V reason, S p, S m, int l) => log ? new failure(ViaScope(status._fail, F.SysTrace(p,m,l), reason).meta) : failure._fail; internal static loop Forever(V reason, S p, S m, int l) => log ? new loop(ViaScope(status._cont, F.SysTrace(p,m,l), reason).meta) : loop._cont; internal static pending Pending(pending @base, V reason, string p, string m, int l) => log ? new pending(@base.ω, ViaScope(@base.due, F.SysTrace(p,m,l), reason).meta) : @base; internal static impending Impending(impending @base, V reason, string p, string m, int l) => log ? new impending(@base.ω, ViaScope(@base.undue, F.SysTrace(p,m,l), reason).meta) : @base; internal static status ViaScope(in status s, object scope, string reason) => new status(s.ω, s.meta.ViaScope(s, scope, reason)); }} // Active.Core.Details #endif // !AL_OPTIMIZE
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeleeWeapon : MonoBehaviour { public int Damage = 10; private void OnTriggerEnter(Collider other) { if(other.GetComponent<DamageObjectInterface>() != null && !other.CompareTag("Player")) { other.GetComponent<DamageObjectInterface>().Damage(Damage); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using Rhino.Geometry; using Rhino.Display; namespace SpeckleRhino { /// <summary> /// kudos to Luis @fraguada /// </summary> public class SpeckleDisplayConduit : Rhino.Display.DisplayConduit { public List<GeometryBase> Geometry { get; set; } public List<Color> Colors { get; set; } public List<bool> VisibleList { get; set; } public Interval? HoverRange { get; set; } public SpeckleDisplayConduit( ) { Geometry = new List<GeometryBase>(); Colors = new List<Color>(); VisibleList = new List<bool>(); } public SpeckleDisplayConduit( List<GeometryBase> _Geometry ) { Geometry = _Geometry; Colors = new List<Color>(); VisibleList = new List<bool>(); } public SpeckleDisplayConduit( List<GeometryBase> _Geometry, List<Color> _Colors, List<bool> _VisibleList ) { Geometry = _Geometry; Colors = _Colors; VisibleList = _VisibleList; } protected override void CalculateBoundingBox( CalculateBoundingBoxEventArgs e ) { Rhino.Geometry.BoundingBox bbox = Rhino.Geometry.BoundingBox.Unset; if ( null != Geometry ) { var localCopy = Geometry.ToList(); foreach ( var obj in localCopy ) if ( obj != null ) try { bbox.Union( obj.GetBoundingBox( false ) ); } catch { } e.IncludeBoundingBox( bbox ); } } protected override void CalculateBoundingBoxZoomExtents( CalculateBoundingBoxEventArgs e ) { Rhino.Geometry.BoundingBox bbox = Rhino.Geometry.BoundingBox.Unset; if ( null != Geometry ) { var localCopy = Geometry.ToList(); foreach ( var obj in localCopy ) if ( obj != null ) try { bbox.Union( obj.GetBoundingBox( false ) ); } catch { } e.IncludeBoundingBox( bbox ); } } protected override void PostDrawObjects( DrawEventArgs e ) { if ( VisibleList.Count == 0 ) return; base.PostDrawObjects( e ); int count = 0; var LocalCopy = Geometry.ToArray(); foreach ( var obj in LocalCopy ) { if ( VisibleList[ count ] && obj != null && !obj.IsDocumentControlled ) switch ( obj.ObjectType ) { case Rhino.DocObjects.ObjectType.Point: e.Display.DrawPoint( ( ( Rhino.Geometry.Point ) obj ).Location, PointStyle.X, 2, Colors[ count ] ); break; case Rhino.DocObjects.ObjectType.Curve: e.Display.DrawCurve( ( Curve ) obj, Colors[ count ] ); break; case Rhino.DocObjects.ObjectType.Extrusion: DisplayMaterial eMaterial = new DisplayMaterial( Colors[ count ], 0.5 ); e.Display.DrawBrepShaded( ( ( Extrusion ) obj ).ToBrep(), eMaterial ); break; case Rhino.DocObjects.ObjectType.Brep: DisplayMaterial bMaterial = new DisplayMaterial( Colors[ count ], 0.5 ); e.Display.DrawBrepShaded( ( Brep ) obj, bMaterial ); //e.Display.DrawBrepWires((Brep)obj, Color.DarkGray, 1); break; case Rhino.DocObjects.ObjectType.Mesh: var mesh = obj as Mesh; if ( mesh.VertexColors.Count > 0 ) { for ( int i = 0; i < mesh.VertexColors.Count; i++ ) mesh.VertexColors[ i ] = Color.FromArgb( 100, mesh.VertexColors[ i ] ); e.Display.DrawMeshFalseColors( mesh ); } else { DisplayMaterial mMaterial = new DisplayMaterial( Colors[ count ], 0.5 ); e.Display.DrawMeshShaded( mesh, mMaterial ); } //e.Display.DrawMeshWires((Mesh)obj, Color.DarkGray); break; case Rhino.DocObjects.ObjectType.TextDot: //e.Display.Draw3dText( ((TextDot)obj).Text, Colors[count], new Plane(((TextDot)obj).Point)); var textDot = ( TextDot ) obj; e.Display.DrawDot( textDot.Point, textDot.Text, Colors[ count ], Color.White ); break; case Rhino.DocObjects.ObjectType.Annotation: if ( obj is TextEntity ) { var textObj = ( Rhino.Geometry.TextEntity ) obj; #if WINR6 var textHeight = Rhino.RhinoDoc.ActiveDoc.DimStyles.FindId(textObj.DimensionStyleId).TextHeight; e.Display.Draw3dText( textObj.PlainText, Colors[ count ], textObj.Plane, textHeight, textObj.Font.FaceName ); #else e.Display.Draw3dText(textObj.Text, Color.Black, textObj.Plane,textObj.TextHeight ,Rhino.RhinoDoc.ActiveDoc.Fonts[textObj.FontIndex].FaceName); #endif } break; } count++; } } protected override void DrawOverlay( DrawEventArgs e ) { base.DrawOverlay( e ); if ( HoverRange == null ) return; var LocalCopy = Geometry.ToArray(); var selectColor = Rhino.ApplicationSettings.AppearanceSettings.SelectedObjectColor; for ( int i = ( int ) HoverRange.Value.T0; i < HoverRange.Value.T1; i++ ) { if ( LocalCopy[ i ] != null ) { var obj = LocalCopy[ i ]; //if ( obj.IsDocumentControlled ) continue; switch ( obj.ObjectType ) { case Rhino.DocObjects.ObjectType.Point: e.Display.DrawPoint( ( ( Rhino.Geometry.Point ) obj ).Location, PointStyle.X, 4, selectColor); break; case Rhino.DocObjects.ObjectType.Curve: e.Display.DrawCurve( ( Curve ) obj, selectColor); break; case Rhino.DocObjects.ObjectType.Brep: e.Display.DrawBrepWires((Brep)obj, selectColor, 1); break; case Rhino.DocObjects.ObjectType.Extrusion: e.Display.DrawBrepWires((obj as Extrusion).ToBrep(), selectColor); break; case Rhino.DocObjects.ObjectType.Mesh: e.Display.DrawMeshWires((Mesh)obj, selectColor); break; case Rhino.DocObjects.ObjectType.TextDot: var textDot = ( TextDot ) obj; e.Display.DrawDot( textDot.Point, textDot.Text, selectColor, Color.Black ); break; case Rhino.DocObjects.ObjectType.Annotation: if ( obj is TextEntity ) { var textObj = ( Rhino.Geometry.TextEntity ) obj; #if WINR6 e.Display.Draw3dText( textObj.PlainText, selectColor, textObj.Plane, textObj.TextHeight, textObj.Font.FaceName ); #else e.Display.Draw3dText(textObj.Text, selectColor, textObj.Plane,textObj.TextHeight ,Rhino.RhinoDoc.ActiveDoc.Fonts[textObj.FontIndex].FaceName); #endif } break; } } } } } }
using Genesis.Cli.Extensions; using Genesis.Output; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Genesis.Cli.Commands { public class DepsCommand : GenesisCommand { public override string Name => "deps"; public override string Description => "Manipulate generator dependencies"; public override async Task<IGenesisExecutionResult> Execute(GenesisContext genesis, string[] args) { var exe = (IOutputExecutor)GetExecutor(args[1]); switch (args[2]) { case "list": Text.Line(); foreach (var d in exe.Dependencies) { Text.YellowLine(d.PathFragment); Text.White("\t"); Text.Blue(d.Contents.Length.ToString() + " bytes"); Text.Line(); } break; case "dump": await exe.DepositDependencies(exe.Configuration.OutputPath); Text.Line(); break; default: Text.Line(); Text.White("Choose an operation:"); Text.FriendlyText("\tdump", false); Text.WhiteLine("\tWrites dependencies to the filesystem."); Text.FriendlyText("\tlist", false); Text.WhiteLine("\tDisplays dependency information"); Text.Line(); break; } return await Task.FromResult(new OutputGenesisExecutionResult() { Success = true }); //heh } } }
using JNCC.PublicWebsite.Core.Constants; using System.Web.Mvc; namespace JNCC.PublicWebsite.Core.Extensions { public static class TempDataDictionaryExtensions { public static void SetSuccessFlag(this TempDataDictionary tempData, string key = SuccessFlags.Default) { tempData.Add(key, true); } public static bool HasSuccessFlag(this TempDataDictionary tempData, string key = SuccessFlags.Default) { return tempData.ContainsKey(key) && tempData[key] != null; } } }
// Copyright (c) 2013 Richard Long & HexBeerium // // Released under the MIT license ( http://opensource.org/licenses/MIT ) // using System; using System.Collections.Generic; using System.Text; namespace dotnet.lib.CoreAnnex.json { public interface JsonDocumentHandler { //////////////////////////////////////////////////////////////////////////// // document void onObjectDocumentStart(); void onObjectDocumentEnd(); void onArrayDocumentStart(); void onArrayDocumentEnd(); //////////////////////////////////////////////////////////////////////////// // array void onArrayStart(int index); void onArrayEnd(int index); void onBoolean(int index, bool value); void onNull(int index); void onNumber(int index, double value); void onNumber(int index, int value); void onNumber(int index, float value); void onNumber(int index, long value); void onObjectStart(int index); void onObjectEnd(int index); void onString(int index, String value); //////////////////////////////////////////////////////////////////////////// // object void onArrayStart(String key); void onArrayEnd(String key); void onBoolean(String key, bool value); void onNull(String key); void onNumber(String key, double value); void onNumber(String key, int value); void onNumber(String key, float value); void onNumber(String key, long value); void onObjectStart(String key); void onObjectEnd(String key); void onString(String key, String value); } }
using System; using System.Threading.Tasks; using Fibon.Messages.Commands; using Fibon.Messages.Events; using RawRabbit; namespace Fibon.Service.Handlers { public class CalculateValueCommandHandler : ICommandHandler<CalculateValueCommand> { private readonly IBusClient busClient; public CalculateValueCommandHandler(IBusClient busClient) { this.busClient = busClient; } private static int Fib(int n) { switch (n) { case 0: return 0; case 1: return 1; default: return Fib(n - 2) + Fib(n - 1); } } public Task HandleAsync(CalculateValueCommand command) { var result = Fib(command.Number); return busClient.PublishAsync(new ValueCalculatedEvent(command.Number, result)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Umbraco.Core.Composing; namespace Our.Umbraco.ContentList.DataSources.Listables { public class ListableDataSourceFactory { static readonly object LockObj = new object(); public virtual IListableDataSource Create(string key) { var type = FindDataSourceType(key); return (IListableDataSource) Current.Factory.GetInstance(type); } public static IList<DataSourceParameterDefinition> CreateParameters(string typeName) { var type = FindDataSourceType(typeName); return CreateParameters(type); } public static IList<DataSourceParameterDefinition> CreateParameters(Type type) { var metadata = FindMetadata(type); if (metadata != null) return metadata.Parameters; return new DataSourceParameterDefinition[0]; } public static List<DataSourceMetadata> GetDataSources() { // TODO: Should we be able to access IRegister? var listableDataSourceTypes = Current.Factory .GetAllInstances<IListableDataSource>() .Select(x => x.GetType()); var dataSources = listableDataSourceTypes.Select(FindMetadata).ToList(); return dataSources; } private static DataSourceMetadata FindMetadata(Type type) { var metadataTypes = type.GetCustomAttributes<DataSourceMetadataAttribute>().ToList(); if (metadataTypes.Any()) { var metadataType = metadataTypes[0].MetadataType; return (DataSourceMetadata) Activator.CreateInstance(metadataType); } return new SimpleDataSourceMetadata(type); } private static Type FindDataSourceType(string key) { var type = Type.GetType(key); if (type == null) throw new ArgumentException(String.Format("Couldn't find listable datasource '{0}'", key)); if (type.GetInterface("IListableDataSource") == null) throw new InvalidCastException(String.Format("Type '{0}' is not a valid IListableDataSource", key)); return type; } } }
public interface IKs { } public class GoodCar { } public class BadCar { public BadCar(string message) { } } public class OfficeCamper : GoodCar, IKs { } public class CarValue<T> where T : struct { } // 값 형식만 public class CarReference<T> where T : class { } // 참조 형식만 public class CarNew<T> where T : new() { } // Default 생성자 public class CarClass<T> where T : GoodCar { } // GoodCar에서 파생 public class CarInterface<T> where T : IKs { } // IKs인터페이스 public class TypeConstraint { public static void Main() { CarValue<int> c = new CarValue<int>(); // struct 성공 CarReference<string> cs = new CarReference<string>(); // class 성공 CarNew<GoodCar> cn = new CarNew<GoodCar>(); // new() 성공 CarClass<OfficeCamper> cc = new CarClass<OfficeCamper>(); // 사용자 정의 타입 CarInterface<IKs> h = new CarInterface<IKs>(); // 인터페이스 지정 } }
using System; using System.Collections.Generic; namespace Exceptionless.Core.Repositories { public class OneOptions : QueryOptions { public OneOptions() { Fields = new List<string>(); } public List<string> Fields { get; set; } public string CacheKey { get; set; } public TimeSpan? ExpiresIn { get; set; } public DateTime? ExpiresAtUtc { get; set; } public DateTime GetCacheExpirationDate() { if (ExpiresAtUtc.HasValue && ExpiresAtUtc.Value < DateTime.UtcNow) throw new ArgumentException("ExpiresAt can't be in the past."); if (ExpiresAtUtc.HasValue) return ExpiresAtUtc.Value; if (ExpiresIn.HasValue) return DateTime.UtcNow.Add(ExpiresIn.Value); return DateTime.UtcNow.AddSeconds(RepositoryConstants.DEFAULT_CACHE_EXPIRATION_SECONDS); } public bool UseCache => !String.IsNullOrEmpty(CacheKey); } }
using Content.Shared.Administration.Logs; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; namespace Content.Client.Administration.UI.CustomControls; public class AdminLogLabel : RichTextLabel { public AdminLogLabel(ref SharedAdminLog log, HSeparator separator) { Log = log; Separator = separator; SetMessage($"{log.Date:HH:mm:ss}: {log.Message}"); OnVisibilityChanged += VisibilityChanged; } public SharedAdminLog Log { get; } public HSeparator Separator { get; } private void VisibilityChanged(Control control) { Separator.Visible = Visible; } protected override void Dispose(bool disposing) { base.Dispose(disposing); OnVisibilityChanged -= VisibilityChanged; } }
using System; using System.Collections.Generic; using SierpinskiFractal.Data; namespace SierpinskiFractal { public class Triangle:ITriangle { public delegate void TriangleMessageHandler(string message); public delegate void TrianglePointsHandler(object point); public event TrianglePointsHandler CreatedPointsStruct; public event TriangleMessageHandler CreatedPoints; private Point[] attractors; private float figureSize = 0.165f; public Triangle(Size size) { attractors = GetAttractors(size); } public Triangle(float width, float height) { attractors = GetAttractors(new Size(width, height)); } public Triangle() { } public void CreateAttractors(Size size) { attractors = GetAttractors(size); } public void CreateAttractors(float width, float height) { attractors = GetAttractors(new Size(width,height)); } /// <summary> /// Получение аттракторов в виде равнобедренного треугольника /// </summary> private Point[] GetAttractors(Size size) { //Расположение точки А исходя из заданного размера Point A = new Point(size.Width - (size.Width * figureSize), size.Height - (size.Height * ((figureSize / 100f) * 6.06f))); //Расположение точки B исходя из заданного размера Point B = new Point(size.Width * figureSize, size.Height - (size.Height * ((figureSize / 100f) * 6.06f))); //Расчет координаты X для точки C float xC = (float)((B.X - A.X) * Math.Cos(1.05f) - (B.Y - A.Y) * Math.Sin(1.05f) + A.X); //Расчет координаты Y для точки C float yC = (float)((B.X - A.X) * Math.Sin(1.05f) + (B.Y - A.Y) * Math.Cos(1.05f) + A.Y); //Создание точки C Point C = new Point(xC, yC); return new Point[] { A,B,C }; } public Point[] GetPoints(int count) { List<Point> points = new List<Point>(); PointGenerator pointGenerator = new PointGenerator(attractors); points.Add(pointGenerator.GetPoint(attractors[0], 0)); for (int i = 1; i < count + 1; i++) { points.Add(pointGenerator.GetPoint(points[i-1], 0)); } CreatedPointsStruct?.Invoke(points); CreatedPoints?.Invoke("Points created!"); return points.ToArray(); } } }
using System.Collections.Generic; using TipsTrade.HMRC.Api.Model; namespace TipsTrade.HMRC.Api.CreateTestUser.Model { /// <summary>Represents a model that provides a list of service names.</summary> public interface ICreateTestUserRequest { /// <summary>The list of services that the user should be enrolled for.</summary> List<string> ServiceNames { get; set; } } }
using System.Collections.ObjectModel; using Windows.UI.Xaml; using Windows.UI.Xaml.Navigation; namespace AppStudio.Uwp.Samples { [SamplePage(Category = "LayoutControls", Name = "Pivorama", Order = 20)] public sealed partial class PivoramaPage : SamplePage { public PivoramaPage() { this.InitializeComponent(); this.DataContext = this; commandBar.DataContext = this; paneHeader.DataContext = this; } public override string Caption { get { return "Pivorama Control"; } } #region Items public ObservableCollection<object> Items { get { return (ObservableCollection<object>)GetValue(ItemsProperty); } set { SetValue(ItemsProperty, value); } } public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<object>), typeof(PivoramaPage), new PropertyMetadata(null)); #endregion protected override void OnNavigatedTo(NavigationEventArgs e) { Items = new ObservableCollection<object>(PhotosDataSource.GetGroupedItems()); base.OnNavigatedTo(e); } protected override void OnSettings() { AppShell.Current.Shell.ShowRightPane(new PivoramaSettings() { DataContext = control }); } } }
using System; using System.Collections; using System.Collections.Generic; namespace RabbitMQ.Client.Impl { public struct MethodArgumentWriter { private byte _bitAccumulator; private int _bitMask; private bool _needBitFlush; public int Offset { get; private set; } public Memory<byte> Memory { get; } public MethodArgumentWriter(Memory<byte> memory) { Memory = memory; _needBitFlush = false; _bitAccumulator = 0; _bitMask = 1; Offset = 0; } public void Flush() { BitFlush(); } public void WriteBit(bool val) { if (_bitMask > 0x80) { BitFlush(); } if (val) { // The cast below is safe, because the combination of // the test against 0x80 above, and the action of // BitFlush(), causes m_bitMask never to exceed 0x80 // at the point the following statement executes. _bitAccumulator = (byte)(_bitAccumulator | (byte)_bitMask); } _bitMask <<= 1; _needBitFlush = true; } public void WriteContent(byte[] val) { throw new NotSupportedException("WriteContent should not be called"); } public void WriteLong(uint val) { BitFlush(); Offset += WireFormatting.WriteLong(Memory.Slice(Offset), val); } public void WriteLonglong(ulong val) { BitFlush(); Offset += WireFormatting.WriteLonglong(Memory.Slice(Offset), val); } public void WriteLongstr(byte[] val) { BitFlush(); Offset += WireFormatting.WriteLongstr(Memory.Slice(Offset), val); } public void WriteOctet(byte val) { BitFlush(); Memory.Slice(Offset++).Span[0] = val; } public void WriteShort(ushort val) { BitFlush(); Offset += WireFormatting.WriteShort(Memory.Slice(Offset), val); } public void WriteShortstr(string val) { BitFlush(); Offset += WireFormatting.WriteShortstr(Memory.Slice(Offset), val); } public void WriteTable(IDictionary val) { BitFlush(); Offset += WireFormatting.WriteTable(Memory.Slice(Offset), val); } public void WriteTable(IDictionary<string, object> val) { BitFlush(); Offset += WireFormatting.WriteTable(Memory.Slice(Offset), val); } public void WriteTimestamp(AmqpTimestamp val) { BitFlush(); Offset += WireFormatting.WriteTimestamp(Memory.Slice(Offset), val); } private void BitFlush() { if (_needBitFlush) { Memory.Slice(Offset++).Span[0] = _bitAccumulator; ResetBitAccumulator(); } } private void ResetBitAccumulator() { _needBitFlush = false; _bitAccumulator = 0; _bitMask = 1; } // TODO: Consider using NotImplementedException (?) // This is a completely bizarre consequence of the way the // Message.Transfer method is marked up in the XML spec. } }
//----------------------------------------------------------------------- // <copyright file="PolylineUtils.cs" company="Mapbox"> // Copyright (c) 2016 Mapbox. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Mapbox.Utils { using System; using System.Collections.Generic; using System.Text; /// <summary> /// A set of Polyline utils. /// </summary> public static class PolylineUtils { /// <summary>Decodes an encoded path string into a sequence of Positions.</summary> /// <remarks> /// Adapted from <see href="https://github.com/mapbox/mapbox-java/blob/9bda93a2f84e26ad67434de1a5c73c335ecac12c/libjava/lib/src/main/java/com/mapbox/services/commons/utils/PolylineUtils.java"/> /// </remarks> /// <param name="encodedPath">A string representing a path.</param> /// <param name="precision">Level of precision. OSRMv4 uses 6, OSRMv5 and Google use 5.</param> /// <returns>List of <see cref="Vector2d"/> making up the line.</returns> public static List<Vector2d> Decode(string encodedPath, int precision = 5) { int len = encodedPath.Length; double factor = Math.Pow(10, precision); // For speed we preallocate to an upper bound on the final length, then // truncate the array before returning. var path = new List<Vector2d>(); int index = 0; int lat = 0; int lng = 0; while (index < len) { int result = 1; int shift = 0; int b; do { b = encodedPath[index++] - 63 - 1; result += b << shift; shift += 5; } while (b >= 0x1f); lat += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); result = 1; shift = 0; do { b = encodedPath[index++] - 63 - 1; result += b << shift; shift += 5; } while (b >= 0x1f); lng += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); path.Add(new Vector2d(y: lng / factor, x: lat / factor)); } return path; } /// <summary> /// Encodes a sequence of Positions into an encoded path string. /// </summary> /// <remarks> /// Adapted from <see href="https://github.com/mapbox/mapbox-java/blob/9bda93a2f84e26ad67434de1a5c73c335ecac12c/libjava/lib/src/main/java/com/mapbox/services/commons/utils/PolylineUtils.java"/> /// </remarks> /// <param name="path">List of <see cref="Vector2d"/> making up the line.</param> /// <param name="precision">Level of precision. OSRMv4 uses 6, OSRMv5 and Google use 5..</param> /// <returns>A string representing a polyLine.</returns> public static string Encode(List<Vector2d> path, int precision = 5) { long lastLat = 0; long lastLng = 0; var result = new StringBuilder(); double factor = Math.Pow(10, precision); foreach (Vector2d point in path) { var lat = (long)Math.Round(point.x * factor); var lng = (long)Math.Round(point.y * factor); Encode(lat - lastLat, result); Encode(lng - lastLng, result); lastLat = lat; lastLng = lng; } return result.ToString(); } /// <summary> /// Encode the latitude or longitude. /// </summary> /// <param name="variable">The value to encode.</param> /// <param name="result">String representation of latitude or longitude.</param> private static void Encode(long variable, StringBuilder result) { variable = variable < 0 ? ~(variable << 1) : variable << 1; while (variable >= 0x20) { result.Append((char)((int)((0x20 | (variable & 0x1f)) + 63))); variable >>= 5; } result.Append((char)((int)(variable + 63))); } } }
using System.Threading.Tasks; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.EventBus.Distributed; namespace LINGYUN.Abp.IM.Messages { public class MessageSender : IMessageSender, ITransientDependency { protected IDistributedEventBus EventBus { get; } public MessageSender(IDistributedEventBus eventBus) { EventBus = eventBus; } public virtual async Task SendMessageAsync(ChatMessage chatMessage) { chatMessage.SetProperty(nameof(ChatMessage.IsAnonymous), chatMessage.IsAnonymous); // 如果先存储的话,就紧耦合消息处理模块了 // await Store.StoreMessageAsync(chatMessage); await EventBus.PublishAsync(chatMessage); } } }
using System.Threading; namespace Fluxor.UnitTests.StoreTests.UnhandledExceptionTests.SupportFiles { public class ThrowSimpleExceptionAction { public ManualResetEvent TriggerHasFinished { get; } = new(initialState: false); } }
using EPDM.Interop.epdm; using System; using System.Linq; using System.Runtime.InteropServices; namespace PdmCardVariableUpdate { [ComVisible(true)] [Guid("9AD5B02B-5027-4751-BBC3-6EF4AE6E3206")] public class ButtonPdmAddIn : IEdmAddIn5 { private const string BUTTON_TAG = "_UpdateDesc_"; public void GetAddInInfo(ref EdmAddInInfo poInfo, IEdmVault5 poVault, IEdmCmdMgr5 poCmdMgr) { poInfo.mbsAddInName = "ButtonPdmAddIn"; poInfo.mlAddInVersion = 1; poInfo.mlRequiredVersionMajor = 16; poCmdMgr.AddHook(EdmCmdType.EdmCmd_CardButton); } public void OnCmd(ref EdmCmd poCmd, ref EdmCmdData[] ppoData) { switch (poCmd.meCmdType) { case EdmCmdType.EdmCmd_CardButton: var addInTagName = poCmd.mbsComment; if (addInTagName == BUTTON_TAG) { var confName = ppoData.First().mbsStrData1; var enumVar = poCmd.mpoExtra as IEdmEnumeratorVariable5; object varVal; enumVar.GetVar("Number", confName, out varVal); var number = varVal?.ToString(); enumVar.GetVar("Revision", confName, out varVal); var revision = varVal?.ToString(); var desc = (object)$"{number} ({revision})"; enumVar.SetVar("Description", confName, ref desc); } break; } } } }
@model cloudscribe.SimpleContent.ContentTemplates.ViewModels.SectionsWithImageViewModel @{ Layout = "_LayoutEmpty"; } <partial name="@Model.Layout" model="Model" />
using System; using System.Collections.Generic; namespace Mutations { class RealOneFifthRuleMutationES11Adaptation : ARealMutationES11Adaptation { private const double OneFifth = 0.2; private readonly int archiveSize; private readonly double modifier; private int successCounter; private readonly Queue<bool> successes; public RealOneFifthRuleMutationES11Adaptation(int archiveSize, double modifier, RealGaussianMutation mutation) : base(mutation) { this.archiveSize = archiveSize; this.modifier = modifier; successCounter = 0; successes = new Queue<bool>(); } public override void Adapt(double beforeMutationValue, List<double> beforeMutationSolution, double afterMutationValue, List<double> afterMutationSolution) { if(successes.Count == archiveSize) { successCounter -= Convert.ToInt32(successes.Dequeue()); } bool isSuccess = afterMutationValue > beforeMutationValue; successes.Enqueue(isSuccess); successCounter += Convert.ToInt32(isSuccess); if (successes.Count == archiveSize) { double ratio = successCounter / (double)archiveSize; if (ratio > OneFifth) { Mutation.MultiplySigmas(1.0 / modifier); } else if (ratio < OneFifth) { Mutation.MultiplySigmas(modifier); } } } } }
using System; namespace website_performance { public class RobotsDoesNotContainSitemaps : Exception { } }
namespace ParseDiff { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; internal class DiffParser { const string noeol = "\\ No newline at end of file"; const string devnull = "/dev/null"; private delegate void ParserAction(string line, Match m); private List<FileDiff> files = new List<FileDiff>(); private int in_del, in_add; private ChunkDiff current = null; private FileDiff file = null; private int oldStart, newStart; private int oldLines, newLines; private readonly HandlerCollection schema; public DiffParser() { schema = new HandlerCollection { { @"^diff\s", Start }, { @"^new file mode \d+$", NewFile }, { @"^deleted file mode \d+$", DeletedFile }, { @"^old mode \d+$", OldPermissions }, { @"^new mode \d+$", NewPermissions }, { @"^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$", Index }, { @"^Binary files ", BinaryFile }, { @"^---\s", FromFile }, { @"^\+\+\+\s", ToFile }, { @"^@@\s+\-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@", Chunk }, { @"^-", DeleteLine }, { @"^\+", AddLine } }; } public IEnumerable<FileDiff> Run(IEnumerable<string> lines) { foreach (var line in lines) if (!ParseLine(line)) ParseNormalLine(line); return files; } private void Start(string line) { file = new FileDiff(); files.Add(file); if (file.To == null && file.From == null) { var fileNames = ParseFileNames(line); if (fileNames != null) { file.From = fileNames[0]; file.To = fileNames[1]; } } } private void Restart() { if (file == null || file.Chunks.Count != 0) Start(null); } private void NewFile() { Restart(); file.Type = FileChangeType.Add; file.From = devnull; } private void DeletedFile() { Restart(); file.Type = FileChangeType.Delete; file.To = devnull; } private void OldPermissions(string line) { Restart(); file.OldPermissions = line.Split(' ').Last(); } private void NewPermissions(string line) { Restart(); file.NewPermissions = line.Split(' ').Last(); } private void Index(string line) { Restart(); file.Index = line.Split(' ').Skip(1); } private void BinaryFile() { Restart(); file.IsBinary = true; } private void FromFile(string line) { Restart(); file.From = ParseFileName(line); } private void ToFile(string line) { Restart(); file.To = ParseFileName(line); } private void Chunk(string line, Match match) { in_del = oldStart = int.Parse(match.Groups[1].Value); oldLines = match.Groups[2].Success ? int.Parse(match.Groups[2].Value) : 0; in_add = newStart = int.Parse(match.Groups[3].Value); newLines = match.Groups[4].Success ? int.Parse(match.Groups[4].Value) : 0; current = new ChunkDiff( content: line, oldStart: oldStart, oldLines: oldLines, newStart: newStart, newLines: newLines ); file.Chunks.Add(current); } private void DeleteLine(string line) { current.Changes.Add(new LineDiff(type: LineChangeType.Delete, index: in_del++, content: line)); file.Deletions++; } private void AddLine(string line) { current.Changes.Add(new LineDiff(type: LineChangeType.Add, index: in_add++, content: line)); file.Additions++; } private void ParseNormalLine(string line) { if (file == null) return; if (string.IsNullOrEmpty(line)) return; current.Changes.Add(new LineDiff( oldIndex: line == noeol ? 0 : in_del++, newIndex: line == noeol ? 0 : in_add++, content: line)); } private bool ParseLine(string line) { foreach (var p in schema) { var m = p.Expression.Match(line); if (m.Success) { p.Action(line, m); return true; } } return false; } private static string[] ParseFileNames(string s) { if (string.IsNullOrEmpty(s)) return null; return s .Split(' ') .Reverse().Take(2).Reverse() .Select(fileName => Regex.Replace(fileName, @"^(a|b)\/", "")).ToArray(); } private static string ParseFileName(string s) { s = s.TrimStart('-', '+'); s = s.Trim(); // ignore possible time stamp var t = new Regex(@"\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d").Match(s); if (t.Success) { s = s.Substring(0, t.Index).Trim(); } // ignore git prefixes a/ or b/ return Regex.IsMatch(s, @"^(a|b)\/") ? s.Substring(2) : s; } private class HandlerRow { public HandlerRow(Regex expression, Action<string, Match> action) { Expression = expression; Action = action; } public Regex Expression { get; } public Action<string, Match> Action { get; } } private class HandlerCollection : IEnumerable<HandlerRow> { private List<HandlerRow> handlers = new List<HandlerRow>(); public void Add(string expression, Action action) { handlers.Add(new HandlerRow(new Regex(expression), (line, m) => action())); } public void Add(string expression, Action<string> action) { handlers.Add(new HandlerRow(new Regex(expression), (line, m) => action(line))); } public void Add(string expression, Action<string, Match> action) { handlers.Add(new HandlerRow(new Regex(expression), action)); } public IEnumerator<HandlerRow> GetEnumerator() { return handlers.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return handlers.GetEnumerator(); } } } }
namespace OzekiDemoSoftphone.PM.Data { /// <summary> /// Keep alive settings data. /// </summary> public class KeepAliveSettingInfo { /// <summary> /// The desired interval of keep alive packets in seconds. /// </summary> public int Interval { get; private set; } /// <summary> /// Constructs a KeepAliveSettingsInfo data object. /// </summary> /// <param name="interval">The desired interval of keep alive packets in seconds.</param> public KeepAliveSettingInfo(int interval) { Interval = interval; } /// <summary> /// Determines whether the specified Object is equal to the current Object. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj == this) return true; KeepAliveSettingInfo other = obj as KeepAliveSettingInfo; if (other == null) return false; return other.Interval.Equals(Interval); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns></returns> public override int GetHashCode() { return Interval.GetHashCode(); } } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Don't include the CachedWebDiscoveryDevice on Silverlight as the File-operations are not available, // and because this discovery implementation should not be used at runtime. #if !SILVERLIGHT using System; using System.IO; using System.Net; using Google.Apis.Logging; using Google.Apis.Util; namespace Google.Apis.Discovery { /// <summary> /// WebDiscoveryDevice allows clients to fetch discovery documents from a web based service. /// Caches discovery files locally to prevent unnecessary requests to the discovery server /// </summary> public class CachedWebDiscoveryDevice : IDiscoveryDevice { private const int BufferSize = 32 * 1024; // 32kb private static readonly ILogger logger = ApplicationContext.Logger.ForType<CachedWebDiscoveryDevice>(); private DirectoryInfo cacheDirectory; private FileStream fileStream; public CachedWebDiscoveryDevice() : this(null) {} /// <summary> /// Creates a new cached web discovery device with the default cache folder /// </summary> /// <param name="discoveryUri"></param> public CachedWebDiscoveryDevice(Uri discoveryUri) : this(discoveryUri, GetDefaultCacheDirectory()) { // Set the default cache duration to 3 days CacheDuration = (uint) (new TimeSpan(3, 0, 0, 0).TotalSeconds); } /// <summary> /// Creates a new cached web discovery device /// </summary> /// <param name="discoveryUri"></param> /// <param name="cacheDirectory"></param> public CachedWebDiscoveryDevice(Uri discoveryUri, DirectoryInfo cacheDirectory) { DiscoveryUri = discoveryUri; CacheDirectory = cacheDirectory; } /// <summary> /// The URI from which the data is fetched /// </summary> public Uri DiscoveryUri { get; set; } /// <summary> /// Defines the cache duration in seconds /// </summary> public uint CacheDuration { get; set; } /// <summary> /// DirectoryInfo of the cache directory /// Must be a valid directory /// </summary> public DirectoryInfo CacheDirectory { get { return cacheDirectory; } set { value.ThrowIfNull("value"); if (value.Exists == false) { throw new ArgumentException("CachedDirectory", "Does not exist [" + value + "]"); } cacheDirectory = value; } } #region IDiscoveryDevice Members /// <summary> /// Fetches the discovery document from either a local cache if it exsits otherwise using /// a WebDiscoveryDecivce /// </summary> /// <returns> /// A <see cref="System.String"/> /// </returns> public Stream Fetch() { FileInfo cachedFile = GetCacheFile(); bool fetchFile = false; // Check if we need to (re)download the document if (cachedFile.Exists == false) { logger.Debug("Document Not Found In Cache, fetching from web"); fetchFile = true; } else if ((DateTime.UtcNow - cachedFile.LastWriteTimeUtc).TotalSeconds > CacheDuration) { logger.Debug("Document is outdated, refetching from web"); fetchFile = true; } else { logger.Debug("Found Document In Cache"); } // (re-)Fetch the document if (fetchFile) { try { using (var device = new WebDiscoveryDevice(DiscoveryUri)) { WriteToCache(device); } } catch (WebException ex) { // If we have a working cached file, we can still return it if (cachedFile.Exists) { logger.Warning( string.Format( "Failed to refetch an outdated cache document [{0}]" + " - Using cached document. Exception: {1}", DiscoveryUri, ex.Message), ex); return cachedFile.OpenRead(); } // Otherwise: Throw the exception throw; } } fileStream = cachedFile.OpenRead(); return fileStream; } public void Dispose() { if (fileStream != null) { fileStream.Dispose(); } } #endregion private static DirectoryInfo GetDefaultCacheDirectory() { return new DirectoryInfo(Path.GetTempPath()); } private string CreateFileName() { // Start with the URI as a file name string fileName = DiscoveryUri.ToString(); // Add hash code for uniqueness, in case removing invalid chars cause collision fileName = fileName + "-" + fileName.GetHashCode(); fileName += ".tmp"; // Replace all invalid characters foreach (char c in Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, '_'); } return fileName; } /// <summary> /// Retrieves a file info of the cache file used for this device /// </summary> /// <returns></returns> public FileInfo GetCacheFile() { string path = Path.Combine(CacheDirectory.ToString(), CreateFileName()); return new FileInfo(path); } private void WriteToCache(WebDiscoveryDevice device) { using (Stream webDocument = device.Fetch()) { FileInfo fileInfo = GetCacheFile(); using (FileStream cachedFileStream = fileInfo.OpenWrite()) { var buffer = new byte[BufferSize]; int read; while ((read = webDocument.Read(buffer, 0, buffer.Length)) > 0) { cachedFileStream.Write(buffer, 0, read); } cachedFileStream.Close(); } } } } } #endif
// Copyright (c) 2021 Keen Software House // Licensed under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using Unreal.Converters; using Unreal.NativeMetadata; namespace Unreal { public class MetadataCollector { public List<UEField> Types = new(); public List<UEModule> Modules = new(); /// <summary> /// Collect all files in a given directory. /// </summary> /// <param name="path"></param> public MetadataCollector(string path) { foreach (var file in Directory.EnumerateFiles(path, "*.umeta", SearchOption.AllDirectories)) { var meta = LoadFromString(File.ReadAllText(file)); if (meta is UEModule module) Modules.Add(module); else { Types.Add((UEField) meta); if (meta is not UEStruct s) continue; foreach (var prop in s.Properties) prop.Struct = s; if (meta is not UEClass c) continue; foreach (var f in c.Functions) { f.Class = c; foreach (var prop in f.Parameters) { prop.Struct = c; prop.Function = f; } } } } } public IEnumerable<UEProperty> GetAllProperties() { foreach (var type in Types) { if (type is not UEStruct s) continue; foreach (var p in s.Properties) yield return p; if (s is not UEClass c) continue; foreach (var f in c.Functions) { foreach (var arg in f.Parameters) yield return arg; yield return f.GetReturn(); } } } private static JsonSerializerOptions JsonOptions = new JsonSerializerOptions { Converters = { new UEMetaConverter(), new TypeReferenceBaseConverter(), new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }, WriteIndented = true, }; public static UEMeta LoadFromString(string rawMeta) { return JsonSerializer.Deserialize<UEMeta>(rawMeta, JsonOptions) ?? throw new InvalidOperationException("Json string was empty."); } } }
using Google.Apis.Services; using Google.Apis.YouTube.v3; using Newtonsoft.Json; using Organize_YT.Models; using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Organize_YT.Data { public class ChannelData { public async Task<String> Run(string ApiKey, string ChannelId) { var youtubeService = new YouTubeService(new BaseClientService.Initializer() { ApplicationName = this.GetType().ToString() }); var searchListRequest = youtubeService.PlaylistItems.List("snippet"); searchListRequest.MaxResults = 10; searchListRequest.Key = ApiKey; searchListRequest.PlaylistId = ChannelId; //ex. UU-lHJZR3Gqxm24_Vd_AJ5Yw // Call the search.list method to retrieve results matching the specified query term. var searchListResponse = await searchListRequest.ExecuteAsync(); // For getting the channel photo. var searchListRequest2 = youtubeService.Channels.List("snippet"); searchListRequest2.Key = ApiKey; searchListRequest2.Id = Regex.Replace(ChannelId, "^[U][U]", "UC"); //ex. UC-lHJZR3Gqxm24_Vd_AJ5Yw Console.WriteLine(searchListRequest2.Id); var searchListResponse2 = await searchListRequest2.ExecuteAsync(); List<ChannelDataInfo> ChannelData = new List<ChannelDataInfo>(); foreach (var item in searchListResponse.Items) { ChannelData.Add(new ChannelDataInfo { ChannelPhoto = searchListResponse2.Items[0].Snippet.Thumbnails.Default__.Url, ChannelTitle = item.Snippet.ChannelTitle, ChannelId = item.Snippet.ChannelId, VideoTitle = item.Snippet.Title, VideoThumbnail = item.Snippet.Thumbnails.Medium.Url, VideoUrlId = item.Snippet.ResourceId.VideoId }); } var jsonData = JsonConvert.SerializeObject(ChannelData); return jsonData; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Arcade.Common; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Versioning; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class CreateTrimDependencyGroups : BuildTask { private const string PlaceHolderDependency = "_._"; [Required] public ITaskItem[] Dependencies { get; set; } [Required] public ITaskItem[] Files { get; set; } /// <summary> /// Package index files used to define stable package list. /// </summary> [Required] public ITaskItem[] PackageIndexes { get; set; } [Output] public ITaskItem[] TrimmedDependencies { get; set; } /* Given a set of available frameworks ("InboxOnTargetFrameworks"), and a list of desired frameworks, reduce the set of frameworks to the minimum set of frameworks which is compatible (preferring inbox frameworks. */ public override bool Execute() { if (null == Dependencies) { Log.LogError("Dependencies argument must be specified"); return false; } if (PackageIndexes == null && PackageIndexes.Length == 0) { Log.LogError("PackageIndexes argument must be specified"); return false; } var index = PackageIndex.Load(PackageIndexes.Select(pi => pi.GetMetadata("FullPath"))); // Retrieve the list of dependency group TFM's var dependencyGroups = Dependencies .Select(dependencyItem => new TaskItemPackageDependency(dependencyItem)) .GroupBy(dependency => dependency.TargetFramework) .Select(dependencyGrouping => new TaskItemPackageDependencyGroup(dependencyGrouping.Key, dependencyGrouping)) .ToArray(); // Prepare a resolver for evaluating if candidate frameworks are actually supported by the package PackageItem[] packageItems = Files.Select(f => new PackageItem(f)).ToArray(); var packagePaths = packageItems.Select(pi => pi.TargetPath); NuGetAssetResolver resolver = new NuGetAssetResolver(null, packagePaths); // Determine all inbox frameworks which are supported by this package var supportedInboxFrameworks = index.GetAlllInboxFrameworks().Where(fx => IsSupported(fx, resolver)); var newDependencyGroups = new Queue<TaskItemPackageDependencyGroup>(); // For each inbox framework determine its best compatible dependency group and create an explicit group, trimming out any inbox dependencies foreach(var supportedInboxFramework in supportedInboxFrameworks) { var nearestDependencyGroup = dependencyGroups.GetNearest(supportedInboxFramework); // We found a compatible dependency group that is not the same as this framework if (nearestDependencyGroup != null && nearestDependencyGroup.TargetFramework != supportedInboxFramework) { // remove all dependencies which are inbox on supportedInboxFramework var filteredDependencies = nearestDependencyGroup.Packages.Where(d => !index.IsInbox(d.Id, supportedInboxFramework, d.AssemblyVersion)).ToArray(); newDependencyGroups.Enqueue(new TaskItemPackageDependencyGroup(supportedInboxFramework, filteredDependencies)); } } // Remove any redundant groups from the added set (EG: net45 and net46 with the same set of dependencies) int groupsToCheck = newDependencyGroups.Count; for(int i = 0; i < groupsToCheck; i++) { // to determine if this is a redundant group, we dequeue so that it won't be considered in the following check for nearest group. var group = newDependencyGroups.Dequeue(); // of the remaining groups, find the most compatible one var nearestGroup = newDependencyGroups.Concat(dependencyGroups).GetNearest(group.TargetFramework); // either we found no compatible group, // or the closest compatible group has different dependencies, // or the closest compatible group is portable and this is not (Portable profiles have different framework precedence, https://github.com/NuGet/Home/issues/6483), // keep it in the set of additions if (nearestGroup == null || !group.Packages.SetEquals(nearestGroup.Packages) || FrameworkUtilities.IsPortableMoniker(group.TargetFramework) != FrameworkUtilities.IsPortableMoniker(nearestGroup.TargetFramework)) { // not redundant, keep it in the queue newDependencyGroups.Enqueue(group); } } // Build the items representing added dependency groups. List<ITaskItem> trimmedDependencies = new List<ITaskItem>(); foreach (var newDependencyGroup in newDependencyGroups) { if (newDependencyGroup.Packages.Count == 0) { // no dependencies (all inbox), use a placeholder dependency. var item = new TaskItem(PlaceHolderDependency); item.SetMetadata("TargetFramework", newDependencyGroup.TargetFramework.GetShortFolderName()); trimmedDependencies.Add(item); } else { foreach(var dependency in newDependencyGroup.Packages) { var item = new TaskItem(dependency.Item); // emit CopiedFromTargetFramework to aide in debugging. item.SetMetadata("CopiedFromTargetFramework", item.GetMetadata("TargetFramework")); item.SetMetadata("TargetFramework", newDependencyGroup.TargetFramework.GetShortFolderName()); trimmedDependencies.Add(item); } } } TrimmedDependencies = trimmedDependencies.ToArray(); return !Log.HasLoggedErrors; } private bool IsSupported(NuGetFramework inboxFx, NuGetAssetResolver resolver) { var compileAssets = resolver.ResolveCompileAssets(inboxFx); // We assume that packages will only support inbox frameworks with lib/tfm assets and not runtime specific assets. // This effectively means we'll never reduce dependencies if a package happens to support an inbox framework with // a RID asset, but that is OK because RID assets can only be used by nuget3 + project.json // and we don't care about reducing dependencies for project.json because indirect dependencies are hidden. var runtimeAssets = resolver.ResolveRuntimeAssets(inboxFx, null); foreach (var compileAsset in compileAssets.Where(c => !NuGetAssetResolver.IsPlaceholder(c))) { string fileName = Path.GetFileName(compileAsset); if (!runtimeAssets.Any(r => Path.GetFileName(r).Equals(fileName, StringComparison.OrdinalIgnoreCase))) { // ref with no matching lib return false; } } // Either all compile assets had matching runtime assets, or all were placeholders, make sure we have at // least one runtime asset to cover the placeholder case return runtimeAssets.Any(); } /// <summary> /// Similar to NuGet.Packaging.Core.PackageDependency but also allows for flowing the original ITaskItem. /// </summary> class TaskItemPackageDependency : PackageDependency { public TaskItemPackageDependency(ITaskItem item) : base(item.ItemSpec, TryParseVersionRange(item.GetMetadata("Version"))) { Item = item; TargetFramework = NuGetFramework.Parse(item.GetMetadata(nameof(TargetFramework))); AssemblyVersion = GetAssemblyVersion(item); } private static VersionRange TryParseVersionRange(string versionString) { VersionRange value; return VersionRange.TryParse(versionString, out value) ? value : null; } private static Version GetAssemblyVersion(ITaskItem dependency) { // If we don't have the AssemblyVersion metadata (4 part version string), fall back and use Version (3 part version string) string versionString = dependency.GetMetadata("AssemblyVersion"); if (string.IsNullOrEmpty(versionString)) { versionString = dependency.GetMetadata("Version"); } return FrameworkUtilities.Ensure4PartVersion(versionString); } public ITaskItem Item { get; } public NuGetFramework TargetFramework { get; } public Version AssemblyVersion { get; } } /// <summary> /// An IFrameworkSpecific type that can be used with FrameworkUtilties.GetNearest. /// This differs from NuGet.Packaging.PackageDependencyGroup in that it exposes the package dependencies as an ISet which can /// undergo an unordered comparison with another ISet. /// </summary> class TaskItemPackageDependencyGroup : IFrameworkSpecific { public TaskItemPackageDependencyGroup(NuGetFramework targetFramework, IEnumerable<TaskItemPackageDependency> packages) { TargetFramework = targetFramework; Packages = new HashSet<TaskItemPackageDependency>(packages.Where(d => d.Id != PlaceHolderDependency)); } public NuGetFramework TargetFramework { get; } public ISet<TaskItemPackageDependency> Packages { get; } } } }
namespace DCET { /// <summary> /// 每个Config的基类 /// </summary> public interface IConfig { long _id { get; set; } } }
using RulesEngine.Models; using System; using System.Collections.Concurrent; using System.Linq; namespace RulesEngine { /// <summary>Maintains the cache of evaludated param.</summary> internal class ParamCache<T> where T : class { /// <summary> /// The compile rules /// </summary> private readonly ConcurrentDictionary<string, T> _evaluatedParams = new ConcurrentDictionary<string, T>(); /// <summary> /// <para></para> /// <para>Determines whether the specified parameter key name contains parameters. /// </para> /// </summary> /// <param name="paramKeyName">Name of the parameter key.</param> /// <returns> /// <c>true</c> if the specified parameter key name contains parameters; otherwise, <c>false</c>.</returns> public bool ContainsParams(string paramKeyName) { return _evaluatedParams.ContainsKey(paramKeyName); } /// <summary>Adds the or update evaluated parameter.</summary> /// <param name="paramKeyName">Name of the parameter key.</param> /// <param name="ruleParameters">The rule parameters.</param> public void AddOrUpdateParams(string paramKeyName, T ruleParameters) { _evaluatedParams.AddOrUpdate(paramKeyName, ruleParameters, (k, v) => v); } /// <summary>Clears this instance.</summary> public void Clear() { _evaluatedParams.Clear(); } /// <summary>Gets the evaluated parameters.</summary> /// <param name="paramKeyName">Name of the parameter key.</param> /// <returns>Delegate[].</returns> public T GetParams(string paramKeyName) { return _evaluatedParams[paramKeyName]; } /// <summary>Removes the specified workflow name.</summary> /// <param name="workflowName">Name of the workflow.</param> public void RemoveCompiledParams(string paramKeyName) { if (_evaluatedParams.TryRemove(paramKeyName, out T ruleParameters)) { var compiledKeysToRemove = _evaluatedParams.Keys.Where(key => key.StartsWith(paramKeyName)); foreach (var key in compiledKeysToRemove) { _evaluatedParams.TryRemove(key, out T val); } } } } }
namespace Xamarin.Android.Tasks.LLVMIR { // See: https://llvm.org/docs/LangRef.html#module-flags-metadata static class LlvmIrModuleMergeBehavior { public const int Error = 1; public const int Warning = 2; public const int Require = 3; public const int Override = 4; public const int Append = 5; public const int AppendUnique = 6; public const int Max = 7; } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.CommandLine.Binding; using System.CommandLine.Invocation; namespace System.CommandLine; public static partial class Handler { private static T? GetValueForHandlerParameter<T>( IValueDescriptor[] symbols, ref int index, InvocationContext context) { if (symbols.Length > index && symbols[index] is IValueDescriptor<T> symbol) { index++; if (symbol is IValueSource valueSource && valueSource.TryGetValue(symbol, context.BindingContext, out var boundValue) && boundValue is T value) { return value; } else { return context.ParseResult.GetValueFor(symbol); } } var service = context.BindingContext.GetService(typeof(T)); if (service is null) { throw new ArgumentException($"Service not found for type {typeof(T)}."); } return (T)service; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; using GSF.Data.Model; namespace openSPM.Model { [Table("HistoryView")] public class HistoryView { [PrimaryKey(true)] public int PatchStatusID { get; set; } public int PatchID { get; set; } public int PatchDocumentCount { get; set; } public DateTime VendorReleaseDate { get; set; } public DateTime DiscoveryDate { get; set; } public int DiscoveryDelta { get; set; } public string VendorName { get; set; } public string ProductName { get; set; } public string VendorPatchName { get; set; } public int BusinessUnitID { get; set; } public int AssessmentID { get; set; } public int AssessmentDocumentCount { get; set; } public int AssessmentResultKey { get; set; } public DateTime AssessmentDate { get; set; } public int AssessmentDelta { get; set; } public int? InstallID { get; set; } public int? InstallDocumentCount { get; set; } public DateTime? InstallDate { get; set; } public int? MitigationPlanID { get; set; } public DateTime? MitigationPlanCreatedDate { get; set; } public int? MitigationPlanDocumentCount { get; set; } public DateTime CompletionDate { get; set; } public int CompletionDelta { get; set; } public int? PlanStatus { get; set; } } }
namespace KanbanBoard.WebApi.Repositories.QueryBuilder { public interface IPatchQueryBuilder<TPatchParams> { (string query, TPatchParams queryParams) Build(); } }
using System.Threading.Tasks; using Service.Liquidity.Monitoring.Domain.Models; using Service.Liquidity.Monitoring.Domain.Services; using Service.Liquidity.Monitoring.Grpc; using Service.Liquidity.Monitoring.Grpc.Models; namespace Service.Liquidity.Monitoring.Services { public class AssetPortfolioSettingsManager : IAssetPortfolioSettingsManager { private readonly IAssetPortfolioSettingsStorage _assetPortfolioSettingsStorage; public AssetPortfolioSettingsManager(IAssetPortfolioSettingsStorage assetPortfolioSettingsStorage) { _assetPortfolioSettingsStorage = assetPortfolioSettingsStorage; } public async Task<GetAssetPortfolioSettingsResponse> GetAssetPortfolioSettingsAsync() { var settings = _assetPortfolioSettingsStorage.GetAssetPortfolioSettings(); if (settings == null || settings.Count == 0) return new GetAssetPortfolioSettingsResponse() { Success = false, ErrorMessage = "Asset settings not found" }; var response = new GetAssetPortfolioSettingsResponse() { Settings = settings, Success = true }; return response; } public Task UpdateAssetPortfolioSettingsAsync(AssetPortfolioSettings settings) { return _assetPortfolioSettingsStorage.UpdateAssetPortfolioSettingsAsync(settings); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; using System.IO; public class ReadyForExport { [MenuItem("Tools/MakeSpriteInfo")] static void MakeSpriteInfo() { var scene1file = "Assets/public/Testbed/UI/ui_work.unity"; // load EditorSceneManager.OpenScene(scene1file); // template検索 var tmplgo = HierarchyUtility.FindGameObjectByUncPath(null,"UI/template"); Debug.Log("target :" + HierarchyUtility.GetAbsoluteNodePath(tmplgo) ); HierarchyUtility.TraverseComponent<Image>(tmplgo.transform,c=> { if (c.sprite == null) { Debug.Log(c.name); return; } GameObject sprite_go = null; for(var i = 0; i < c.transform.childCount; i++) { var ct = c.transform.GetChild(i); if (ct.name.StartsWith("*sprite=" + c.name +":")) { sprite_go = ct.gameObject; break; } } if (sprite_go == null) { sprite_go = new GameObject(); } sprite_go.name = "*sprite=" + c.name +":" + c.sprite.name; sprite_go.transform.parent = c.transform; sprite_go.transform.localPosition = Vector3.zero; sprite_go.transform.localRotation = Quaternion.identity; sprite_go.transform.localScale = Vector3.one; }); } [MenuItem("Tools/Create Prefab then Pack")] static void CreatePrefab() { var scene1file = "Assets/public/Testbed/UI/ui_work.unity"; // load EditorSceneManager.OpenScene(scene1file); //念のため再度スプライト書き出し MakeSpriteInfo(); // template検索 var tmplgo = HierarchyUtility.FindGameObjectByUncPath(null,"UI/template"); Debug.Log("target :" + HierarchyUtility.GetAbsoluteNodePath(tmplgo) ); var localpath = "Assets/Public/Testbed/UI/template.prefab"; try { if (AssetDatabase.LoadAssetAtPath(localpath,typeof(GameObject))!=null) { AssetDatabase.DeleteAsset(localpath); } } catch { } var prefab = PrefabUtility.CreateEmptyPrefab(localpath); var newprefab = PrefabUtility.ReplacePrefab(tmplgo,prefab); AssetDatabase.Refresh(); var exportpath = Path.Combine(Application.dataPath,@"../template.unitypackage"); AssetDatabase.ExportPackage(localpath,exportpath,ExportPackageOptions.Recurse); Debug.Log("Exported : " + exportpath); } }
namespace LzhamWrapper { public static class LzhamConsts { public const uint MinDictionarySizeLog2 = 15; public const uint MaxDictionarySizeLog2X86 = 26; public const uint MaxDictionarySizeLog2X64 = 29; public const uint MaxHelperThreads = 64; } }
@{ ViewBag.Title = "InformationItemEdit"; Layout = "~/Views/Shared/_LayoutBlank.cshtml"; } <link rel="stylesheet" type="text/css" href="/Scripts/wangEditor/css/wangEditor.min.css"> <script type="text/javascript" src='/Scripts/wangEditor/js/wangEditor.min.js'></script> <style> .wangEditor-container .wangEditor-txt p, .wangEditor-container .wangEditor-txt h1, .wangEditor-container .wangEditor-txt h2, .wangEditor-container .wangEditor-txt h3, .wangEditor-container .wangEditor-txt h4, .wangEditor-container .wangEditor-txt h5 { margin: 0px 0; line-height: 1.8; } </style> <style type="text/css"> .divImageMaterialContainer { width: 170px; float: left; margin-right: 10px; margin-top: 0px; background-color: #FFF; } .tableImageMaterialContainer { width: 100%; border-collapse: collapse; border: solid #E7E7EB; border-width: 1px 0 0 1px; } .tableImageMaterialContainer td { border: 1px solid #E7E7EB; } </style> <script> var _informationId = getQueryString("informationId"); var _categoryId = getQueryString("categoryId"); var _mode = "create";//modify var _validator; var _data = null; var _editor; $(document).ready(function () { $("[keyenter]").keypress(function (e) { if (e.keyCode == 13) { save(); } }); $("#txtImageUrl").blur(function () { loadImage(); }); _validator = $("#form").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtName": "required" }, messages: { "txtName": "请输入信息名称;" } }); //_editor = $('#txtDescription').wangEditor({ // 'menuConfig': [ // ['viewSourceCode'], // ['bold', 'underline', 'italic', 'foreColor', 'backgroundColor', 'strikethrough'], // ['blockquote', 'fontFamily', 'fontSize', 'setHead', 'list', 'justify'], // ['createLink', 'unLink', 'insertTable'], // ['insertLocation'], // ['undo', 'redo', 'fullScreen'] // ] //}); _editor = new wangEditor('divDescriptionEditor'); _editor.config.menus = [ 'source', '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', 'bgcolor', '|', 'quote', 'fontfamily', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright', '|', 'link', 'unlink', 'table', '|', 'undo', 'redo', 'fullscreen' ]; _editor.create(); load(); }); function load() { var id = getQueryString("id"); if (id == undefined || id == "") { return; } _mode = "modify"; $("#spanTitle").html("修改"); $("#btnRemove").show(); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Information/GetInformationItem?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { _data = data.Data; $("#txtId").val(_data.Id); $("#txtName").val(_data.Name); $("#txtImageUrl").val(_data.Image); $("#txtPhoneNumber").val(_data.PhoneNumber); $("#txtIntroduction").val(_data.Introduction); _editor.$txt.html(_data.Description); loadImage(); loadDetailImageList(); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function save() { if (_validator.form() == false) { return; } var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); var url = "/Api/Information/CreateInformationItem"; if (_mode == "modify") { url = "/Api/Information/UpdateInformationItem"; } if (_data == undefined || _data == null) { _data = new Object(); } _data.Information = _informationId; _data.Category = _categoryId; _data.Name = $("#txtName").val(); _data.Image = $("#txtImageUrl").val(); _data.PhoneNumber = $("#txtPhoneNumber").val(); _data.Introduction = $("#txtIntroduction").val(); _data.Description = _editor.$txt.html(); //if (_data.ImageList == undefined || _data.ImageList == null) { // _data.ImageList = new Array(); //} $.ajax({ url: url, type: "POST", dataType: "json", data: JSON.stringify(_data), success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var index = parent.layer.getFrameIndex(window.name); if (_mode == "create") { parent.loadDataAndCloseLayer(index); } else { parent.loadDataOnPageAndCloseLayer(index); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function removeData() { var id = $("#txtId").val(); if (id == undefined || id == "") { return; } var msg = "是否确认删除?" var confirmLayerIndex = layer.confirm(msg, { btn: ['确认', '取消'], //按钮 shade: [0.4, '#393D49'], title: false, closeBtn: false, shift: _layerShift }, function () { layer.close(confirmLayerIndex); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Information/RemoveInformationItem?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { if (data.Success) { var index = parent.layer.getFrameIndex(window.name); parent.loadDataOnPageAndCloseLayer(index); } else { layer.closeAll(); layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.closeAll(); alert("Error: " + xmlHttpRequest.status); } }); }); } function cancel() { var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); } function loadImage() { $("#image").attr("src", $("#txtImageUrl").val()); } function uploadFile() { __showFileUpload(getUploadResult); } function getUploadResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; $("#txtImageUrl").val(url); loadImage(); } function removeImage() { $("#txtImageUrl").val(""); loadImage(); } //详细图片 function uploadDetailImage() { __showFileUpload(getUploadDetailImageResult); } function getUploadDetailImageResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; var imageListItem = new Object(); imageListItem.Id = result.Data.Id; imageListItem.Url = url; if (_data == undefined || _data == null) { _data = new Object(); } if (_data.ImageList == undefined || _data.ImageList == null) { _data.ImageList = new Array(); } _data.ImageList[_data.ImageList.length] = imageListItem; loadDetailImageList(); } function loadDetailImageList() { if (_data == undefined || _data == null || _data.ImageList == undefined || _data.ImageList == null) { document.getElementById('divImageListContainer').innerHTML = ""; return; } var gettpl = document.getElementById('imageListTemplate').innerHTML; laytpl(gettpl).render(_data.ImageList, function (html) { document.getElementById('divImageListContainer').innerHTML = html; }); } function removeDetailImageItem(id) { for (var i = 0; i < _data.ImageList.length; i++) { if (_data.ImageList[i].Id == id) { _data.ImageList.splice(i, 1); break; } } loadDetailImageList(); } /////// ////详细图片 function uploadDescriptionFile() { __showFileUpload(getUploadDescriptionFileResult); } function getUploadDescriptionFileResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; _editor.$txt.append("<img src='" + url + "' style='max-width:100%' />"); } function closeAllLayer() { layer.closeAll(); } </script> <script id="imageListTemplate" type="text/html"> {{# for(var i = 0, len = d.length; i < len; i++){ }} <div class="divImageMaterialContainer"> <table class="tableImageMaterialContainer"> <tr> <td height="150" align="center"><img style="max-width:166px; max-height:100%" src="{{ d[i].Url }}" /></td> </tr> <tr> <td height="30" valign="middle" bgcolor="#F4F5F9"> <div> <div style="float: right; margin-right: 10px;"> <img src="/Content/Images/ico_remove.jpg" width="20" height="20" onclick="removeDetailImageItem('{{ d[i].Id }}')"> </div> <div style="clear: both"></div> </div> </td> </tr> </table> </div> {{# } }} <div style="clear:both"></div> </script> <div style="margin-left:20px; margin-right:20px; margin-top:20px;"> <span id="spanTitle" class="font_black_24">信息</span> </div> <div style=" background-color:#ccc; margin-left:20px; margin-right:20px; margin-top:10px; height:1px;"> </div> <div style=" position:absolute; overflow:auto ;margin-top:25px;left:30px; right:30px; bottom:60px; top:50px; "> <form id="form"> <input type="hidden" id="txtId" /> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td><input id="txtName" name="txtName" type="text" class="input_16" style="width:96%; " maxlength="25" keyenter /></td> </tr> <tr> <td valign="top"> <div style="margin-top:5px;"> 封面图片: </div> </td> <td valign="top"> <div class="divBorder_gray" style="margin-bottom:5px;width:96%;"> <div style="padding:5px;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="120"><img id="image" alt="" style="max-height:100px;" /></td> <td align="right"> <input id="txtImageUrl" name="txtImageUrl" type="hidden" class="input_16" style="width:96%; " maxlength="500" keyenter /> <a href="javascript:void(0)" onclick="uploadFile()">上传新图片</a><br /> <a href="javascript:void(0)" onclick="removeImage()">删除图片</a> </td> </tr> </table> </div> </div> </td> </tr> @*<tr> <td height="36">&nbsp;</td> <td><input id="txtImageUrl" name="txtImageUrl" type="text" class="input_16" style="width:96%; " keyenter /></td> </tr>*@ <tr> <td width="110" height="36" valign="top"> <div style="margin-top:5px;"> 详细图片: </div> </td> <td> <div class="divBorder_gray" style="margin-bottom:5px;width:96%;"> <div style="padding:5px;"> <div id="divImageListContainer"> @*<div style="float:left"> <img src="http://wxcfile1.shengxunwei.com/FileStore/2a58d820-de07-4c8f-80b9-b5cb5a1028b4/eff4f12c-640d-4776-98be-0ccee007e9cf.jpg" /> </div> <div style="clear:both"></div>*@ </div> <div style="text-align:right"><a href="javascript:void(0)" onclick="uploadDetailImage()">上传新图片</a><br /></div> </div> </div> </td> </tr> <tr> <td width="110" height="36">电话:</td> <td><input id="txtPhoneNumber" name="txtPhoneNumber" type="text" class="input_16" style="width:96%; " maxlength="15" keyenter /></td> </tr> <tr> <td width="110" height="36">简要说明:</td> <td> <textarea id='txtIntroduction' rows="3" style='width:96%; ' class="input_16" maxlength="150"></textarea> </td> </tr> <tr> <td width="110" height="36" valign="top"> <div style="margin-top:10px;"> 详细说明: </div> </td> <td> <div style="width:96%; margin-top:10px;"> <div id="divDescriptionEditor" style='height:400px; '></div> </div> </td> </tr> <tr> <td width="110">&nbsp;</td> <td> <div style="width:96%;"> <div style="float:right;"> <input name="btnUpload" type="button" class="btn_white" id="btnUpload" value="上传图片" onclick="uploadDescriptionFile()" /> </div> <div style="clear:both"></div> </div> </td> </tr> </table> </form> </div> <div style=" background-color:#ccc; position:absolute; bottom:55px; left:20px;right:20px; height:1px;"> </div> <div style="position:absolute; bottom:15px; left:20px;right:20px;"> <div style="float:left;"> <input name="btnRemove" type="button" class="btn_red" id="btnRemove" value="删 除" style="display:none" onclick="removeData()" /> </div> <div style="float:right"> <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="保 存" onclick="save()" /> <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="cancel()" /> </div> <div style="clear:both"> </div> </div> @Helpers.FileUpload()
using FakeBackend; using System.Web.UI; namespace SessionDemo { public partial class ItemTr : UserControl { public Item Item { get; set; } } }
using Newtonsoft.Json; using Paribu.Net.Attributes; using System.Collections.Generic; namespace Paribu.Net.RestObjects { public class ParibuMarketData { public ParibuOrderBook OrderBook { get; set; } public IEnumerable<ParibuTrade> Trades { get; set; } public ParibuChartData ChartData { get; set; } } public class MarketData { [JsonProperty("orderBook")] public MarketDataOrderBook OrderBook { get; set; } [JsonProperty("marketMatches")] public IEnumerable<ParibuTrade> Trades { get; set; } [JsonProperty("charts")] public ChartData ChartData { get; set; } } public class MarketDataOrderBook { [JsonProperty("buy")] public MarketDataOrderBookList Bids { get; set; } [JsonProperty("sell")] public MarketDataOrderBookList Asks { get; set; } } [JsonConverter(typeof(TypedDataConverter<MarketDataOrderBookList>))] public class MarketDataOrderBookList { [TypedData] public Dictionary<decimal, decimal> Data { get; set; } } }
using System; using System.Collections; namespace RBWINDOW_SOURCE_NOV_2017 { /// <summary> /// STORAGE CLASS FOR EACH ELEMENT IN FILE /// objname REFERS TO HEADER NAME /// fieldArray REFERS TO ARRAY CONTAINING EACH VALUE AFTER /// </summary> class Fields { private string objName; public ArrayList fieldArray = new ArrayList(); // CONSTRUCTOR USED FOR FILEPARSER CLASS public Fields(string name) { objName = name; } // CONSTRUCTOR USED FOR DUPLICATE OBJ CLASS public Fields(string key, double value, int fLength) { objName = key; for (int i = 0; i < fLength - 1; i++) { fieldArray.Add("NaN"); } fieldArray.Add(value.ToString()); } public Fields(string key, double value) { objName = key; fieldArray.Add(value.ToString()); } public string getName { get { return objName; } } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; namespace consumer_lib { #pragma warning disable CS0649 public struct WeatherForecast { public DateTime date; public int temperatureC; public int temperatureF; public string summary; } public class WeatherForecastClient { #nullable enable public async Task<List<WeatherForecast>> GetForecasts(string baseUrl, HttpClient? httpClient = null) { using var client = httpClient == null ? new HttpClient() : httpClient; var response = await client.GetAsync(baseUrl + "/WeatherForecast"); response.EnsureSuccessStatusCode(); var resp = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<List<WeatherForecast>>(resp); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Titanfall2_SkinTool.Titanfall2.WeaponData.Default.Titan { class BroadSword { public struct ReallyData { public string name; public long seek; public int length; public int seeklength; } public ReallyData[] BroadSword_col; public ReallyData[] BroadSword_nml; public ReallyData[] BroadSword_gls; public ReallyData[] BroadSword_spc; public ReallyData[] BroadSword_ao; public ReallyData[] BroadSword_cav; public BroadSword() { int i = 1; BroadSword_col = new ReallyData[3]; BroadSword_nml = new ReallyData[3]; BroadSword_gls = new ReallyData[3]; BroadSword_spc = new ReallyData[3]; BroadSword_ao = new ReallyData[3]; BroadSword_cav = new ReallyData[3]; //2为2048x2048,1为1024x1024,0为512x512 //浪人大剑没有ilm,col和spc是BC7U BroadSword_col[0].name = "col"; BroadSword_col[0].seek = 9163313152; BroadSword_col[0].length = 131072; BroadSword_col[0].seeklength = 148; while (i <= 2) { BroadSword_col[i].name = "col"; BroadSword_col[i].seek = BroadSword_col[i - 1].seek + BroadSword_col[i - 1].length; BroadSword_col[i].length = BroadSword_col[i - 1].length * 4; BroadSword_col[i].seeklength = 148; i++; } i = 1; BroadSword_nml[0].name = "nml"; BroadSword_nml[0].seek = 9166065664; BroadSword_nml[0].length = 262144; BroadSword_nml[0].seeklength = 128; while (i <= 2) { BroadSword_nml[i].name = "nml"; BroadSword_nml[i].seek = BroadSword_nml[i - 1].seek + BroadSword_nml[i - 1].length; BroadSword_nml[i].length = BroadSword_nml[i - 1].length * 4; BroadSword_nml[i].seeklength = 128; i++; } i = 1; BroadSword_gls[0].name = "gls"; BroadSword_gls[0].seek = 9168818176; BroadSword_gls[0].length = 65536; BroadSword_gls[0].seeklength = 128; while (i <= 2) { BroadSword_gls[i].name = "gls"; BroadSword_gls[i].seek = BroadSword_gls[i - 1].seek + BroadSword_gls[i - 1].length; BroadSword_gls[i].length = BroadSword_gls[i - 1].length * 4; BroadSword_gls[i].seeklength = 128; i++; } i = 1; BroadSword_spc[0].name = "spc"; BroadSword_spc[0].seek = 9170194432; BroadSword_spc[0].length = 131072; BroadSword_spc[0].seeklength = 148; while (i <= 2) { BroadSword_spc[i].name = "spc"; BroadSword_spc[i].seek = BroadSword_spc[i - 1].seek + BroadSword_spc[i - 1].length; BroadSword_spc[i].length = BroadSword_spc[i - 1].length * 4; BroadSword_spc[i].seeklength = 148; i++; } i = 1; BroadSword_ao[0].name = "ao"; BroadSword_ao[0].seek = 9172946944; BroadSword_ao[0].length = 65536; BroadSword_ao[0].seeklength = 128; while (i <= 2) { BroadSword_ao[i].name = "ao"; BroadSword_ao[i].seek = BroadSword_ao[i - 1].seek + BroadSword_ao[i - 1].length; BroadSword_ao[i].length = BroadSword_ao[i - 1].length * 4; BroadSword_ao[i].seeklength = 128; i++; } i = 1; BroadSword_cav[0].name = "cav"; BroadSword_cav[0].seek = 9174323200; BroadSword_cav[0].length = 65536; BroadSword_cav[0].seeklength = 128; while (i <= 2) { BroadSword_cav[i].name = "cav"; BroadSword_cav[i].seek = BroadSword_cav[i - 1].seek + BroadSword_cav[i - 1].length; BroadSword_cav[i].length = BroadSword_cav[i - 1].length * 4; BroadSword_cav[i].seeklength = 128; i++; } i = 1; } } }
using Fusee.Engine.Common; using Fusee.Math.Core; namespace Fusee.Engine.Core { /// <summary> /// Base class for various collision shape types. /// </summary> public class CollisionShape { /// <summary> /// The implementation object. /// </summary> internal ICollisionShapeImp _collisionShapeImp; /// <summary> /// Retrieves or sets the margin. /// </summary> /// <value> /// The size of the collision shape's margin. /// </value> public virtual float Margin { get { return _collisionShapeImp.Margin; } set { var o = (CollisionShape)_collisionShapeImp.UserObject; o._collisionShapeImp.Margin = value; } } /// <summary> /// Retrieves or sets the local scaling. /// </summary> /// <value> /// The local scaling. /// </value> public virtual float3 LocalScaling { get { return _collisionShapeImp.LocalScaling; } set { var o = (CollisionShape)_collisionShapeImp.UserObject; o._collisionShapeImp.LocalScaling = value; } } } }
using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using UnityEditor.iOS.Xcode; using System; using System.IO; //============================================================================= // This PostProcessor does all annoying Xcode steps automatically for us //============================================================================= public class PostProcessor { [PostProcessBuild] public static void OnPostProcessBuild(BuildTarget target, string path) { if(target != BuildTarget.iOS) { return; } string plistPath = Path.Combine(path, "Info.plist"); PlistDocument plist = new PlistDocument(); plist.ReadFromString(File.ReadAllText(plistPath)); PlistElementDict rootDict = plist.root; rootDict.SetString("NSPhotoLibraryUsageDescription", "Requires access to the Photo Library"); rootDict.SetString("NSPhotoLibraryAddUsageDescription", "Requires access to the Photo Library"); File.WriteAllText(plistPath, plist.WriteToString()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace WeChatSDK.Model { [Serializable] [XmlRoot("xml")] public class WxReceiveMsg { public Int64 MsgId { get; set; } [XmlText] public string ToUserName { get; set; } public string FromUserName { get; set; } public int CreateTime { get; set; } public string MsgType { get; set; } public string MediaId { get; set; } /// <summary> /// 缩略图Id /// </summary> public string ThumbMediaId { get; set; } public string Location_X { get; set; } public string Location_Y { get; set; } /// <summary> /// 地图缩放大小 /// </summary> public string Scale { get; set; } /// <summary> /// 地图位置信息 /// </summary> public string Label { get; set; } /// <summary> /// 语音格式,如amr,speex等 /// </summary> public string Url { get; set; } public string Title { get; set; } public string Description { get; set; } public string Format { get; set; } } }
namespace Cortside.SqlReportApi.WebApi.Models.Responses { /// <summary> /// Configuration /// </summary> public class ConfigurationModel { /// <summary> /// HotDocs Url /// </summary> public string HotDocsUrl { get; set; } /// <summary> /// Nautilus Url /// </summary> public string NautilusUrl { get; set; } /// <summary> /// Service bus configuration /// </summary> public ServicebusModel ServiceBus { get; set; } /// <summary> /// Identity Server configuration /// </summary> public IdentityServerModel IdentityServer { get; set; } /// <summary> /// Policy Server configuration /// </summary> public PolicyServerModel PolicyServer { get; set; } } }
using UdonSharp; using UnityEngine; using VRC.SDKBase; using VRC.Udon; namespace Player { /// <summary> /// Basic gameobject toggle on key press script. /// </summary> public class KeyToggle : UdonSharpBehaviour { [Tooltip("State of game objects when scene is loaded.")] public bool initialState = false; [Tooltip("Key that toggles gameobjects.")] public KeyCode key; [Tooltip("List of game objects to toggle on/off.")] public GameObject[] toggleObject; public void Start() { for (int i = 0; i < toggleObject.Length; i++) { toggleObject[i].SetActive(initialState); } } public void Update() { if (Input.GetKeyDown(key)) { for (int i = 0; i < toggleObject.Length; i++) { toggleObject[i].SetActive(!toggleObject[i].activeSelf); } } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using M_url.Data.ResourceParameters; using M_url.Data.Helpers; using M_url.Domain.Entities; namespace M_url.Data.Repositories { public interface IMurlRepository { Task<PagedList<SlugEntity>> GetAllSlugsAsync(SlugsResourceParameters slugsResourceParameters); Task<IEnumerable<SlugEntity>> GetAllSlugsAsync(IEnumerable<string> slugs); Task<SlugEntity> GetSlugAsync(string slug); Task<SlugEntity> GetByUrlAsync(string url); void AddSlug(SlugEntity newSlug); void DeleteSlug(SlugEntity slug); Task<bool> SaveChangesAsync(); } }
using System.Windows.Forms; namespace Gma.UserActivityMonitorDemo { public partial class TestFormComponent : Form { public TestFormComponent() { InitializeComponent(); } #region Event handlers of particular events. They will be activated when an appropriate checkbox is checked. private void HookManager_KeyDown(object sender, KeyEventArgs e) { textBoxLog.AppendText(string.Format("KeyDown - {0}\n", e.KeyCode)); textBoxLog.ScrollToCaret(); } private void HookManager_KeyUp(object sender, KeyEventArgs e) { textBoxLog.AppendText(string.Format("KeyUp - {0}\n", e.KeyCode)); textBoxLog.ScrollToCaret(); } private void HookManager_KeyPress(object sender, KeyPressEventArgs e) { textBoxLog.AppendText(string.Format("KeyPress - {0}\n", e.KeyChar)); textBoxLog.ScrollToCaret(); } private void HookManager_MouseMove(object sender, MouseEventArgs e) { labelMousePosition.Text = string.Format("x={0:0000}; y={1:0000}", e.X, e.Y); } private void HookManager_MouseClick(object sender, MouseEventArgs e) { textBoxLog.AppendText(string.Format("MouseClick - {0}\n", e.Button)); textBoxLog.ScrollToCaret(); } private void HookManager_MouseUp(object sender, MouseEventArgs e) { textBoxLog.AppendText(string.Format("MouseUp - {0}\n", e.Button)); textBoxLog.ScrollToCaret(); } private void HookManager_MouseDown(object sender, MouseEventArgs e) { textBoxLog.AppendText(string.Format("MouseDown - {0}\n", e.Button)); textBoxLog.ScrollToCaret(); } private void HookManager_MouseDoubleClick(object sender, MouseEventArgs e) { textBoxLog.AppendText(string.Format("MouseDoubleClick - {0}\n", e.Button)); textBoxLog.ScrollToCaret(); } private void HookManager_MouseWheel(object sender, MouseEventArgs e) { labelWheel.Text = string.Format("Wheel={0:000}", e.Delta); } #endregion } }
using loon.action.map; using loon.utils; namespace loon.geom { public class Vector2f : XY { private static readonly Array<Vector2f> _VEC2_CACHE = new Array<Vector2f>(); public readonly static Vector2f STATIC_ZERO = new Vector2f(); public static Vector2f TMP() { Vector2f temp = _VEC2_CACHE.Pop(); if (temp == null) { _VEC2_CACHE.Add(temp = new Vector2f(0, 0)); } return temp; } public static Vector2f ZERO() { return new Vector2f(0); } public static Vector2f HALF() { return new Vector2f(0.5f, 0.5f); } public static Vector2f ONE() { return new Vector2f(1); } public static Vector2f AXIS_X() { return new Vector2f(1, 0); } public static Vector2f AXIS_Y() { return new Vector2f(0, 1); } public static float AngleTo(Vector2f pos) { float theta = MathUtils.ToDegrees(MathUtils.Atan2(pos.y, pos.x)); if ((theta < -360) || (theta > 360)) { theta %= 360; } if (theta < 0) { theta = 360 + theta; } return theta; } public static Vector2f At(float x, float y) { return new Vector2f(x, y); } public static Vector2f At(XY xy) { return new Vector2f(xy.GetX(), xy.GetY()); } public static Vector2f FromAngle(float angle) { return new Vector2f(MathUtils.Cos(angle), MathUtils.Sin(angle)); } public static Vector2f Sum(Vector2f a, Vector2f b) { Vector2f answer = new Vector2f(a); return answer.Add(b); } public static Vector2f Mult(Vector2f vector, float scalar) { Vector2f answer = new Vector2f(vector); return answer.Mul(scalar); } public static Vector2f Cpy(Vector2f pos) { Vector2f newSVector2 = new Vector2f { x = pos.x, y = pos.y }; return newSVector2; } public static float Len(Vector2f pos) { return MathUtils.Sqrt(pos.x * pos.x + pos.y * pos.y); } public static float Len2(Vector2f pos) { return pos.x * pos.x + pos.y * pos.y; } public static Vector2f Set(Vector2f pos, Vector2f vectorB) { pos.x = vectorB.x; pos.y = vectorB.y; return pos; } public static Vector2f Set(Vector2f pos, float x, float y) { pos.x = x; pos.y = y; return pos; } public Vector2f SubNew(Vector2f vectorB) { return SubNew(this, vectorB); } public static Vector2f SubNew(Vector2f pos, Vector2f vectorB) { return At(pos.x - vectorB.x, pos.y - vectorB.y); } public static Vector2f Sub(Vector2f pos, Vector2f vectorB) { pos.x -= vectorB.x; pos.y -= vectorB.y; return pos; } public static Vector2f Nor(Vector2f pos) { float len = Len(pos); if (len != 0) { pos.x /= len; pos.y /= len; } return pos; } public static Vector2f AddNew(Vector2f pos, Vector2f vectorB) { return At(pos.x + vectorB.x, pos.y + vectorB.y); } public static Vector2f Add(Vector2f pos, Vector2f vectorB) { pos.x += vectorB.x; pos.y += vectorB.y; return pos; } public static Vector2f Add(Vector2f pos, float x, float y) { pos.x += x; pos.y += y; return pos; } public static Vector2f SmoothStep(Vector2f a, Vector2f b, float amount) { return new Vector2f(MathUtils.SmoothStep(a.x, b.x, amount), MathUtils.SmoothStep(a.y, b.y, amount)); } public static Vector2f Transform(Vector2f value, Quaternion rotation) { return Transform(value, rotation, null); } public static Vector2f Transform(Vector2f value, Quaternion rotation, Vector2f result) { if (result == null) { result = new Vector2f(); } Vector3f rot1 = new Vector3f(rotation.x + rotation.x, rotation.y + rotation.y, rotation.z + rotation.z); Vector3f rot2 = new Vector3f(rotation.x, rotation.x, rotation.w); Vector3f rot3 = new Vector3f(1, rotation.y, rotation.z); Vector3f rot4 = rot1.Mul(rot2); Vector3f rot5 = rot1.Mul(rot3); Vector2f v = new Vector2f { x = (value.x * (1f - rot5.y - rot5.z) + value.y * (rot4.y - rot4.z)), y = (value.x * (rot4.y + rot4.z) + value.y * (1f - rot4.x - rot5.z)) }; result.x = v.x; result.y = v.y; return result; } public static Vector2f Abs(Vector2f a) { return new Vector2f(MathUtils.Abs(a.x), MathUtils.Abs(a.y)); } public static void AbsToOut(Vector2f a, Vector2f outs) { outs.x = MathUtils.Abs(a.x); outs.y = MathUtils.Abs(a.y); } public static float Dot(Vector2f a, Vector2f b) { return a.x * b.x + a.y * b.y; } public static float Cross(Vector2f a, Vector2f b) { return a.x * b.y - a.y * b.x; } public static Vector2f Cross(Vector2f a, float s) { return new Vector2f(s * a.y, -s * a.x); } public static void CrossToOut(Vector2f a, float s, Vector2f outs) { float tempy = -s * a.x; outs.x = s * a.y; outs.y = tempy; } public static Vector2f Cross(float s, Vector2f a) { return new Vector2f(-s * a.y, s * a.x); } public static void CrossToOut(float s, Vector2f a, Vector2f outs) { float tempY = s * a.x; outs.x = -s * a.y; outs.y = tempY; } public static void NegateToOut(Vector2f a, Vector2f outs) { outs.x = -a.x; outs.y = -a.y; } public static Vector2f Min(Vector2f a, Vector2f b) { return new Vector2f(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y); } public static Vector2f Max(Vector2f a, Vector2f b) { return new Vector2f(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y); } public static void MinToOut(Vector2f a, Vector2f b, Vector2f outs) { outs.x = a.x < b.x ? a.x : b.x; outs.y = a.y < b.y ? a.y : b.y; } public static void MaxToOut(Vector2f a, Vector2f b, Vector2f outs) { outs.x = a.x > b.x ? a.x : b.x; outs.y = a.y > b.y ? a.y : b.y; } public static Vector2f Mul(Vector2f pos, float scalar) { pos.x *= scalar; pos.y *= scalar; return pos; } public static Vector2f Direction(Vector2f v1, Vector2f v2) { Vector2f vector = v2.Sub(v1); vector.NormalizeSelf(); return vector; } public static float Dst(Vector2f pos, Vector2f vectorB) { float x_d = vectorB.x - pos.x; float y_d = vectorB.y - pos.y; return MathUtils.Sqrt(x_d * x_d + y_d * y_d); } public static float Dst(Vector2f pos, float x, float y) { float x_d = x - pos.x; float y_d = y - pos.y; return MathUtils.Sqrt(x_d * x_d + y_d * y_d); } public static float Dst2(Vector2f pos, Vector2f vectorB) { float x_d = vectorB.x - pos.x; float y_d = vectorB.y - pos.y; return x_d * x_d + y_d * y_d; } public static Vector2f Sub(Vector2f pos, float x, float y) { pos.x -= x; pos.y -= y; return pos; } public static float Crs(Vector2f pos, Vector2f vectorB) { return pos.x * vectorB.y - pos.y * vectorB.x; } public static float Crs(Vector2f pos, float x, float y) { return pos.x * y - pos.y * x; } public static Vector2f Rotate(Vector2f pos, Vector2f origin, float angle) { float rad = MathUtils.ToRadians(angle); Vector2f newVector = new Vector2f(); pos.x += -origin.x; pos.y += -origin.y; newVector.x = (pos.x * MathUtils.Cos(rad) - (pos.y * MathUtils.Sin(rad))); newVector.y = (MathUtils.Sin(rad * pos.x) + (MathUtils.Cos(rad * pos.y))); newVector.x += origin.x; newVector.y += origin.y; return newVector; } public static Vector2f Rotate(Vector2f pos, float angle) { float rad = MathUtils.ToRadians(angle); float Cos = MathUtils.Cos(rad); float Sin = MathUtils.Sin(rad); float newX = pos.x * Cos - pos.y * Sin; float newY = pos.x * Sin + pos.y * Cos; pos.x = newX; pos.y = newY; return pos; } public static Vector2f Lerp(Vector2f pos, Vector2f target, float alpha) { Vector2f r = Mul(pos, 1.0f - alpha); Add(r, Mul(Cpy(target), alpha)); return r; } public static float Dst2(float x1, float y1, float x2, float y2) { float x_d = x2 - x1; float y_d = y2 - y1; return x_d * x_d + y_d * y_d; } public static Vector2f Polar(float len, float angle) { return new Vector2f(len * MathUtils.Cos(angle / MathUtils.DEG_TO_RAD), len * MathUtils.Sin(angle / MathUtils.DEG_TO_RAD)); } public float x; public float y; public Vector2f() : this(0, 0) { } public Vector2f(float x, float y) { this.x = x; this.y = y; } public Vector2f(XY v) { Set(v); } public Vector2f Cpy() { return new Vector2f(this); } public float Length() { return MathUtils.Sqrt(x * x + y * y); } public float LengthSquared() { return (x * x + y * y); } public float Len() { return Length(); } public float Len2() { return LengthSquared(); } public Vector2f NormalizeSelf() { float l = Length(); if (l == 0 || l == 1) { return this; } return Set(x / l, y / l); } public Vector2f NormalizeNew() { return Nor(Len()); } public Vector2f NorSelf() { return NormalizeSelf(); } public Vector2f Nor() { return NormalizeNew(); } public Vector2f Nor(float n) { return new Vector2f(this.x == 0 ? 0 : this.x / n, this.y == 0 ? 0 : this.y / n); } public Vector2f Mul(float s) { return new Vector2f(this.x * s, this.y * s); } public Vector2f Mul(float sx, float sy) { return new Vector2f(this.x * sx, this.y * sy); } public Vector2f MulSelf(float scale) { return MulSelf(scale); } public Vector2f MulSelf(float sx, float sy) { this.x *= sx; this.y *= sy; return this; } public Vector2f MulSelf(Affine2f mat) { float nx = this.x * mat.m00 + this.y * mat.m01 + mat.tx; float ny = this.x * mat.m10 + this.y * mat.m11 + mat.ty; this.x = nx; this.y = ny; return this; } public Vector2f MulSelf(Matrix3 mat) { float nx = this.x * mat.val[0] + this.y * mat.val[3] + mat.val[6]; float ny = this.x * mat.val[1] + this.y * mat.val[4] + mat.val[7]; this.x = nx; this.y = ny; return this; } public Vector2f SmoothStep(Vector2f v, float amount) { return SmoothStep(this, v, amount); } public Vector2f Sub(float x, float y) { return new Vector2f(this.x - x, this.y - y); } public Vector2f Div() { return new Vector2f(x / 2, y / 2); } public Vector2f Div(float v) { return new Vector2f(x / v, y / v); } public Vector2f Div(Vector2f v) { return new Vector2f(x / v.x, y / v.y); } public Vector2f Add(float x, float y) { return new Vector2f(this.x + x, this.y + y); } public Vector2f AddSelfX(float x) { this.x += x; return this; } public Vector2f AddSelfY(float y) { this.y += y; return this; } public float Dot(Vector2f v) { return x * v.x + y * v.y; } public float Dst(Vector2f v) { float x_d = v.x - x; float y_d = v.y - y; return MathUtils.Sqrt(x_d * x_d + y_d * y_d); } public float Dst(float x, float y) { float x_d = x - this.x; float y_d = y - this.y; return MathUtils.Sqrt(x_d * x_d + y_d * y_d); } public float Dst2(Vector2f v) { float x_d = v.x - x; float y_d = v.y - y; return x_d * x_d + y_d * y_d; } public float Dst2(float x, float y) { float x_d = x - this.x; float y_d = y - this.y; return x_d * x_d + y_d * y_d; } public Vector2f Tmp() { return TMP().Set(this); } public float Crs(Vector2f v) { return this.x * v.y - this.y * v.x; } public float Crs(float x, float y) { return this.x * y - this.y * x; } public float GetAngle() { return AngleTo(this); } public float Angle() { return GetAngle(); } public float AngleRad(Vector2f v) { if (null == v) { return 0f; } return MathUtils.Atan2(v.Crs(this), v.Dot(this)); } public float AngleDeg(Vector2f v) { if (null == v) { return GetAngle(); } float theta = MathUtils.ToDegrees(MathUtils.Atan2(v.Crs(this), v.Dot(this))); if ((theta < -360) || (theta > 360)) { theta %= 360; } if (theta < 0) { theta = 360 + theta; } return theta; } public int Angle(Vector2f v) { int dx = v.X() - X(); int dy = v.Y() - Y(); int adx = MathUtils.Abs(dx); int ady = MathUtils.Abs(dy); if ((dy == 0) && (dx == 0)) { return 0; } if ((dy == 0) && (dx > 0)) { return 0; } if ((dy == 0) && (dx < 0)) { return 180; } if ((dy > 0) && (dx == 0)) { return 90; } if ((dy < 0) && (dx == 0)) { return 270; } float rwinkel = MathUtils.Atan(ady / adx); float dwinkel = 0.0f; if ((dx > 0) && (dy > 0)) { dwinkel = MathUtils.ToDegrees(rwinkel); } else if ((dx < 0) && (dy > 0)) { dwinkel = (180.0f - MathUtils.ToDegrees(rwinkel)); } else if ((dx > 0) && (dy < 0)) { dwinkel = (360.0f - MathUtils.ToDegrees(rwinkel)); } else if ((dx < 0) && (dy < 0)) { dwinkel = (180.0f + MathUtils.ToDegrees(rwinkel)); } int iwinkel = (int)dwinkel; if (iwinkel == 360) { iwinkel = 0; } return iwinkel; } public Vector2f Rotate(float angle) { return Cpy().RotateSelf(angle); } public Vector2f RotateX(float angle) { return Cpy().RotateSelfX(angle); } public Vector2f RotateY(float angle) { return Cpy().RotateSelfY(angle); } public Vector2f Rotate(float cx, float cy, float angle) { return Cpy().RotateSelf(cx, cy, angle); } public Vector2f RotateSelf(float cx, float cy, float angle) { if (angle != 0) { float rad = MathUtils.ToRadians(angle); float Cos = MathUtils.Cos(rad); float Sin = MathUtils.Sin(rad); float nx = cx + (this.x - cx) * MathUtils.Cos(rad) - (this.y - cy) * Sin; float ny = cy + (this.x - cx) * MathUtils.Sin(rad) + (this.y - cy) * Cos; return Set(nx, ny); } return this; } public Vector2f RotateSelf(float angle) { if (angle != 0) { float rad = MathUtils.ToRadians(angle); float Cos = MathUtils.Cos(rad); float Sin = MathUtils.Sin(rad); float newX = this.x * Cos - this.y * Sin; float newY = this.x * Sin + this.y * Cos; this.x = newX; this.y = newY; } return this; } public Vector2f RotateSelfX(float angle) { if (angle != 0) { float rad = MathUtils.ToRadians(angle); float Cos = MathUtils.Cos(rad); float Sin = MathUtils.Sin(rad); this.x = this.x * Cos - this.y * Sin; } return this; } public Vector2f RotateSelfY(float angle) { if (angle != 0) { float rad = MathUtils.ToRadians(angle); float Cos = MathUtils.Cos(rad); float Sin = MathUtils.Sin(rad); this.y = this.x * Sin + this.y * Cos; } return this; } public Vector2f(float value) : this(value, value) { } public Vector2f(float[] coords) { x = coords[0]; y = coords[1]; } public Vector2f Move_45D_up() { return Move_45D_up(1); } public Vector2f Move_45D_up(int multiples) { return Move_multiples(Field2D.UP, multiples); } public Vector2f Move_45D_left() { return Move_45D_left(1); } public Vector2f Move_45D_left(int multiples) { return Move_multiples(Field2D.LEFT, multiples); } public Vector2f Move_45D_right() { return Move_45D_right(1); } public Vector2f Move_45D_right(int multiples) { return Move_multiples(Field2D.RIGHT, multiples); } public Vector2f Move_45D_down() { return Move_45D_down(1); } public Vector2f Move_45D_down(int multiples) { return Move_multiples(Field2D.DOWN, multiples); } public Vector2f Move_up() { return Move_up(1); } public Vector2f Move_up(int multiples) { return Move_multiples(Field2D.TUP, multiples); } public Vector2f Move_left() { return Move_left(1); } public Vector2f Move_left(int multiples) { return Move_multiples(Field2D.TLEFT, multiples); } public Vector2f Move_right() { return Move_right(1); } public Vector2f Move_right(int multiples) { return Move_multiples(Field2D.TRIGHT, multiples); } public Vector2f Move_down() { return Move_down(1); } public Vector2f Move_down(int multiples) { return Move_multiples(Field2D.TDOWN, multiples); } public Vector2f Up(float v) { return Cpy().Set(this.x, this.y - v); } public Vector2f Down(float v) { return Cpy().Set(this.x, this.y + v); } public Vector2f Left(float v) { return Cpy().Set(this.x - v, this.y); } public Vector2f Right(float v) { return Cpy().Set(this.x + v, this.y); } public Vector2f Translate(float dx, float dy) { return Cpy().Set(this.x + dx, this.y + dy); } public Vector2f Up() { return Up(1f); } public Vector2f Down() { return Down(1f); } public Vector2f Left() { return Left(1f); } public Vector2f Right() { return Right(1f); } public Vector2f TranslateSelf(float dx, float dy) { return Move(dx, dy); } public Vector2f Move(float dx, float dy) { this.x += dx; this.y += dy; return this; } public Vector2f Move(Vector2f pos) { this.x += pos.x; this.y += pos.y; return this; } public Vector2f Move_multiples(int direction, int multiples) { if (multiples <= 0) { multiples = 1; } Vector2f v = Field2D.GetDirection(direction); return Move(v.X() * multiples, v.Y() * multiples); } public Vector2f MoveX(float x) { this.x += x; return this; } public Vector2f MoveY(float y) { this.y += y; return this; } public Vector2f MoveByAngle(int degAngle, float distance) { if (distance == 0) { return this; } float Angle = MathUtils.ToRadians(degAngle); float dX = (MathUtils.Cos(Angle) * distance); float dY = (-MathUtils.Sin(Angle) * distance); int idX = MathUtils.Round(dX); int idY = MathUtils.Round(dY); return Move(idX, idY); } public Vector2f Move(float distance) { float angle = MathUtils.ToRadians(GetAngle()); int x = MathUtils.Round(GetX() + MathUtils.Cos(angle) * distance); int y = MathUtils.Round(GetY() + MathUtils.Sin(angle) * distance); return SetLocation(x, y); } public bool NearlyCompare(Vector2f v, int range) { int dX = MathUtils.Abs(X() - v.X()); int dY = MathUtils.Abs(Y() - v.Y()); return (dX <= range) && (dY <= range); } public float[] GetCoords() { return (new float[] { x, y }); } public Vector2f SetLocation(float x, float y) { return Set(x, y); } public Vector2f SetX(float x) { this.x = x; return this; } public Vector2f SetY(float y) { this.y = y; return this; } public float GetX() { return x; } public float GetY() { return y; } public int X() { return (int)x; } public int Y() { return (int)y; } public Vector2f Reverse() { x = -x; y = -y; return this; } public Vector2f Mul(Vector2f pos) { return new Vector2f(x * pos.x, y * pos.y); } public void SetZero() { x = 0f; y = 0f; } public Vector2f Set(float v) { return Set(v, v); } public Vector2f Set(float x, float y) { this.x = x; this.y = y; return this; } public Vector2f Set(XY v) { this.x = v.GetX(); this.y = v.GetY(); return this; } public Vector2f Set(Vector2f v) { this.x = v.x; this.y = v.y; return this; } public Vector2f Add(float v) { return new Vector2f(x + v, y + v); } public Vector2f Add(Vector2f v) { return new Vector2f(x + v.x, y + v.y); } public Vector2f Sub(Vector2f v) { return new Vector2f(x - v.x, y - v.y); } public Vector2f Negate() { return new Vector2f(-x, -y); } public Vector2f NegateLocal() { x = -x; y = -y; return this; } public Vector2f SubLocal(Vector2f v) { x -= v.x; y -= v.y; return this; } public Vector2f MulLocal(float a) { x *= a; y *= a; return this; } public Vector2f SetLength(float len) { len *= len; float oldLength = LengthSquared(); return (oldLength == 0 || oldLength == len) ? this : ScaleSelf(MathUtils.Sqrt(len / oldLength)); } public Vector2f SetAngle(float radians) { this.Set(Length(), 0f); this.RotateSelf(radians); return this; } public float Normalize() { float length = Length(); if (length < MathUtils.EPSILON) { return 0f; } float invLength = 1.0f / length; x *= invLength; y *= invLength; return length; } public Vector2f Lerp(Vector2f target, float alpha) { Vector2f r = this.Mul(1f - alpha); r.Add(target.Tmp().Mul(alpha)); return r; } public Vector2f LerpSelf(Vector2f target, float alpha) { float oneMinusAlpha = 1f - alpha; float x = (this.x * oneMinusAlpha) + (target.x * alpha); float y = (this.y * oneMinusAlpha) + (target.y * alpha); return Set(x, y); } public Vector2f LerpSelf(float x, float y, float alpha) { this.x += alpha * (x - this.x); this.y += alpha * (y - this.y); return this; } public Vector2f Lerp(float x, float y, float alpha) { return Cpy().LerpSelf(x, y, alpha); } public Vector2f Abs() { return new Vector2f(MathUtils.Abs(x), MathUtils.Abs(y)); } public void AbsLocal() { x = MathUtils.Abs(x); y = MathUtils.Abs(y); } public Vector2f Random() { this.x = MathUtils.Random(0f, LSystem.viewSize.GetWidth()); this.y = MathUtils.Random(0f, LSystem.viewSize.GetHeight()); return this; } public override int GetHashCode() { uint prime = 31; uint result = 1; result = prime * result + NumberUtils.FloatToIntBits(x); result = prime * result + NumberUtils.FloatToIntBits(y); return (int)result; } public bool Equals(float x, float y) { return this.x == x && this.y == y; } public override bool Equals(object obj) { if (this == obj) return true; if (obj == null) return false; if (GetType() != obj.GetType()) return false; Vector2f other = (Vector2f)obj; if (NumberUtils.FloatToIntBits(x) != NumberUtils.FloatToIntBits(other.x)) return false; if (NumberUtils.FloatToIntBits(y) != NumberUtils.FloatToIntBits(other.y)) return false; return true; } public bool EpsilonEquals(Vector2f other, float epsilon) { if (other == null) return false; if (MathUtils.Abs(other.x - x) > epsilon) return false; if (MathUtils.Abs(other.y - y) > epsilon) return false; return true; } public bool EpsilonEquals(float x, float y, float epsilon) { if (MathUtils.Abs(x - this.x) > epsilon) return false; if (MathUtils.Abs(y - this.y) > epsilon) return false; return true; } public bool IsUnit() { return IsUnit(0.000000001f); } public bool IsUnit(float margin) { return MathUtils.Abs(Len2() - 1f) < margin; } public bool IsZero() { return x == 0 && y == 0; } public bool IsZero(float margin) { return Len2() < margin; } public bool IsOnLine(Vector2f other) { return MathUtils.IsZero(x * other.y - y * other.x); } public bool IsOnLine(Vector2f other, float epsilon) { return MathUtils.IsZero(x * other.y - y * other.x, epsilon); } public bool IsCollinear(Vector2f other, float epsilon) { return IsOnLine(other, epsilon) && Dot(other) > 0f; } public bool IsCollinear(Vector2f other) { return IsOnLine(other) && Dot(other) > 0f; } public bool IsCollinearOpposite(Vector2f other, float epsilon) { return IsOnLine(other, epsilon) && Dot(other) < 0f; } public bool IsCollinearOpposite(Vector2f other) { return IsOnLine(other) && Dot(other) < 0f; } public bool IsPerpendicular(Vector2f vector) { return MathUtils.IsZero(Dot(vector)); } public bool IsPerpendicular(Vector2f vector, float epsilon) { return MathUtils.IsZero(Dot(vector), epsilon); } public bool HasSameDirection(Vector2f vector) { return Dot(vector) > 0; } public bool HasOppositeDirection(Vector2f vector) { return Dot(vector) < 0; } public static string PointToString(float x, float y) { return MathUtils.ToString(x) + "," + MathUtils.ToString(y); } public Vector2f Inverse() { return new Vector2f(-this.x, -this.y); } public Vector2f InverseSelf() { this.x = -this.x; this.y = -this.y; return this; } public Vector2f AddSelf(Vector2f v) { this.x += v.x; this.y += v.y; return this; } public Vector2f AddSelf(float x, float y) { this.x += x; this.y += y; return this; } public Vector2f Subtract(float x, float y) { return Add(-x, -y); } public Vector2f NegateSelf() { return Set(-x, -y); } public float Zcross(float zx, float zy) { return (this.x * zy) - (this.y * zx); } public float Zcross(Vector2f v) { return (this.x * v.y) - (this.y * v.x); } public float Dot(float x, float y) { return this.x * x + this.y * y; } public float Distance(Vector2f v) { return MathUtils.Sqrt(DistanceSquared(v)); } public float DistanceSquared(Vector2f v) { return (v.x - x) * (v.x - x) + (v.y - y) * (v.y - y); } public Vector2f Perpendicular() { return new Vector2f(y, -x); } public Vector2f PerpendicularSelf() { return Set(y, x); } public Vector2f ProjectSelf(Vector2f v) { return ScaleSelf(Dot(v) / v.LengthSquared()); } public Vector2f ScaleSelf(float s) { return ScaleSelf(s, s); } public Vector2f ScaleSelf(float sx, float sy) { return Set(x * sx, y * sy); } public Vector2f Reflect(Vector2f axis) { return Project(axis).Scale(2).Subtract(this); } public Vector2f Subtract(Vector2f v) { return Add(-v.x, -v.y); } public Vector2f Scale(float s) { return Mul(s); } public Vector2f Scale(float sx, float sy) { return Mul(x * sx, y * sy); } public Vector2f Project(Vector2f v) { return Mul(Dot(v) / v.LengthSquared()); } public Vector2f ReflectSelf(Vector2f axis) { return Set(Project(axis).ScaleSelf(2).SubtractSelf(this)); } public Vector2f SubtractSelf(Vector2f v) { return SubtractSelf(v.x, v.y); } public Vector2f SubtractSelf(float x, float y) { return AddSelf(-x, -y); } public float Cross(Vector2f v) { return this.x * v.y - v.x * this.y; } public float LenManhattan() { return MathUtils.Abs(this.x) + MathUtils.Abs(this.y); } public float[] ToFloat() { return new float[] { x, y }; } public int[] ToInt() { return new int[] { X(), Y() }; } public string ToCSS() { return this.x + "px " + this.y + "px"; } public override string ToString() { return "(" + x + "," + y + ")"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Dynamic; namespace UnitTestImpromptuInterface { public class TestMethodAttribute : Attribute { } public class TestClassAttribute : Attribute { } public class TestFixtureAttribute : Attribute { } public class TestFixtureSetUpAttribute : Attribute { } public class TestInitializeAttribute : Attribute { } public class TestAttribute : Attribute { } public class CategoryAttribute : Attribute { public CategoryAttribute(string label) { } } public class AssertionException: Exception { public AssertionException() { } public AssertionException(string message) : base(message) { } public AssertionException(string message, Exception inner) : base(message, inner) { } } public class IgnoreException : Exception { public IgnoreException() { } public IgnoreException(string message) : base(message) { } public IgnoreException(string message, Exception inner) : base(message, inner) { } } public class WriteLineContext { public void WriteLine(string format, params object[] args) { Console.WriteLine(format, args); } } public class Helper { public Helper() { Assert = new AssertHelper(); } public WriteLineContext TestContext { get { return new WriteLineContext(); } } public AssertHelper Assert { get; private set; } public void AssertException<T>(Action action) where T:Exception { bool tSuccess = false; Exception tEc = null; try { action(); } catch (T ex) { tSuccess = true; tEc = ex; } catch (Exception ex) { tEc = ex; } if (!tSuccess) { throw new AssertionException(String.Format("Expected Exception {0} instead of {1}", typeof(T).ToString(), tEc == null ? "No Exception" : tEc.GetType().ToString())); } } } public class AssertHelper { public void AreEqual(dynamic expected, dynamic actual) { if(expected ==null && actual==null) return; if(expected ==null || !expected.Equals(actual)) FailExpected(expected, actual); } public void AreNotEqual(dynamic expected, dynamic actual) { if (expected == null && actual != null) return; if (expected == null || expected.Equals(actual)) FailExpected(expected, actual); } public void Less(dynamic smaller, dynamic larger) { if(smaller > larger) FailLess(smaller, larger); } public void IsTrue(bool actual,string message) { if (!actual) { throw new AssertionException(message ?? "Expected True"); } } public void IsTrue(bool actual) { IsTrue(actual, null); } public void IsFalse(bool actual) { IsFalse(actual, null); } public void IsFalse(bool actual, string message) { if (actual) { throw new AssertionException(message ?? "Expected False"); } } public void Ignore(string message) { throw new IgnoreException(message); } public void Fail() { throw new AssertionException(); } private static void FailExpected(object expected, object actual) { throw new AssertionException(String.Format("Expected {0} instead got {1}", expected,actual)); } private static void FailLess(object expected, object actual) { throw new AssertionException(String.Format("Expected {0} to be less {1}", expected,actual)); } public void Fail(string message) { throw new AssertionException(message); } public void Throws<T>(Action func) where T:Exception { var tFail = true; try { func(); } catch (T e) { tFail = false; } if (tFail) { throw new AssertionException(String.Format("Expected {0} to be Thrown", typeof(T))); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using ModestTree; using UnityEngine.TestTools; using Assert=ModestTree.Assert; using Zenject; #if ZEN_SIGNALS_ADD_UNIRX using UniRx; #endif namespace ZenjectSignalsAndSignals.Tests { public class TestSignals2 : ZenjectIntegrationTestFixture { void CommonInstall() { Container.BindInterfacesAndSelfTo<SignalManager>().AsSingle(); } [UnityTest] public IEnumerator TestToSingle1() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.Bind<Bar>().AsSingle(); Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).AsSingle(); PostInstall(); Container.Resolve<Bar>(); var cmd = Container.Resolve<DoSomethingSignal>(); Assert.IsEqual(Bar.InstanceCount, 1); Assert.IsEqual(Bar.TriggeredCount, 0); cmd.Fire(); Assert.IsEqual(Bar.TriggeredCount, 1); Assert.IsEqual(Bar.TriggeredCount, 1); yield break; } [UnityTest] [ValidateOnly] public IEnumerator TestValidationFailure() { PreInstall(); CommonInstall(); Container.Bind<Qux>().AsSingle(); Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).FromResolve(); Assert.Throws(() => PostInstall()); yield break; } [UnityTest] [ValidateOnly] public IEnumerator TestValidationSuccess() { PreInstall(); CommonInstall(); Container.Bind<Qux>().AsSingle(); Container.Bind<Bar>().AsSingle(); Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).FromResolve(); PostInstall(); yield break; } [UnityTest] public IEnumerator TestToCached1() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.Bind<Bar>().AsCached(); Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).AsCached(); PostInstall(); Container.Resolve<Bar>(); var cmd = Container.Resolve<DoSomethingSignal>(); Assert.IsEqual(Bar.InstanceCount, 1); Assert.IsEqual(Bar.TriggeredCount, 0); cmd.Fire(); Assert.IsEqual(Bar.TriggeredCount, 1); Assert.IsEqual(Bar.InstanceCount, 2); cmd.Fire(); Assert.IsEqual(Bar.InstanceCount, 2); Assert.IsEqual(Bar.TriggeredCount, 2); yield break; } [UnityTest] public IEnumerator TestNoHandlerDefault() { PreInstall(); CommonInstall(); Container.DeclareSignal<DoSomethingSignal>(); PostInstall(); var cmd = Container.Resolve<DoSomethingSignal>(); cmd.Fire(); yield break; } [UnityTest] public IEnumerator TestNoHandlerRequiredFailure() { PreInstall(); CommonInstall(); Container.DeclareSignal<DoSomethingSignal>().RequireHandler(); PostInstall(); var cmd = Container.Resolve<DoSomethingSignal>(); Assert.Throws(() => cmd.Fire()); yield break; } [UnityTest] public IEnumerator TestNoHandlerRequiredSuccess() { PreInstall(); CommonInstall(); Container.DeclareSignal<DoSomethingSignal>().RequireHandler(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).AsCached(); PostInstall(); var cmd = Container.Resolve<DoSomethingSignal>(); cmd.Fire(); yield break; } [UnityTest] public IEnumerator TestHandlerRequiredEventStyle() { PreInstall(); CommonInstall(); Container.DeclareSignal<DoSomethingSignal>().RequireHandler(); PostInstall(); var signal = Container.Resolve<DoSomethingSignal>(); Assert.Throws(() => signal.Fire()); bool received = false; Action receiveSignal = () => received = true; signal += receiveSignal; Assert.That(!received); signal.Fire(); Assert.That(received); signal -= receiveSignal; Assert.Throws(() => signal.Fire()); yield break; } #if ZEN_SIGNALS_ADD_UNIRX [UnityTest] public IEnumerator TestHandlerRequiredUniRxStyle() { PreInstall(); CommonInstall(); Container.DeclareSignal<DoSomethingSignal>().RequireHandler(); PostInstall(); var signal = Container.Resolve<DoSomethingSignal>(); Assert.Throws(() => signal.Fire()); bool received = false; var subscription = signal.AsObservable.Subscribe((x) => received = true); Assert.That(!received); signal.Fire(); Assert.That(received); subscription.Dispose(); Assert.Throws(() => signal.Fire()); yield break; } #endif [UnityTest] public IEnumerator TestToMethod() { PreInstall(); CommonInstall(); bool wasCalled = false; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To(() => wasCalled = true); PostInstall(); var cmd = Container.Resolve<DoSomethingSignal>(); Assert.That(!wasCalled); cmd.Fire(); Assert.That(wasCalled); yield break; } [UnityTest] public IEnumerator TestMultipleHandlers() { PreInstall(); CommonInstall(); bool wasCalled1 = false; bool wasCalled2 = false; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To(() => wasCalled1 = true); Container.BindSignal<DoSomethingSignal>() .To(() => wasCalled2 = true); PostInstall(); var cmd = Container.Resolve<DoSomethingSignal>(); Assert.That(!wasCalled1); Assert.That(!wasCalled2); cmd.Fire(); Assert.That(wasCalled1); Assert.That(wasCalled2); yield break; } [UnityTest] public IEnumerator TestFromNewTransient() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).AsTransient(); PostInstall(); TestBarHandlerTransient(); yield break; } [UnityTest] public IEnumerator TestFromNewCached() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).AsCached(); PostInstall(); TestBarHandlerCached(); yield break; } [UnityTest] public IEnumerator TestFromNewSingle() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).AsSingle(); PostInstall(); TestBarHandlerCached(); yield break; } [UnityTest] public IEnumerator TestFromMethod() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).FromMethod(_ => new Bar()); PostInstall(); TestBarHandlerTransient(); yield break; } [UnityTest] public IEnumerator TestFromMethodMultiple() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).FromMethodMultiple(_ => new[] { new Bar(), new Bar() }); PostInstall(); var cmd = Container.Resolve<DoSomethingSignal>(); Assert.IsEqual(Bar.TriggeredCount, 0); Assert.IsEqual(Bar.InstanceCount, 0); cmd.Fire(); Assert.IsEqual(Bar.TriggeredCount, 2); Assert.IsEqual(Bar.InstanceCount, 2); cmd.Fire(); Assert.IsEqual(Bar.TriggeredCount, 4); Assert.IsEqual(Bar.InstanceCount, 4); yield break; } [UnityTest] public IEnumerator TestFromMethodMultipleEmpty() { PreInstall(); CommonInstall(); Bar.TriggeredCount = 0; Bar.InstanceCount = 0; Container.DeclareSignal<DoSomethingSignal>(); Container.BindSignal<DoSomethingSignal>() .To<Bar>(x => x.Execute).FromMethodMultiple(_ => new Bar[] {}); PostInstall(); var signal = Container.Resolve<DoSomethingSignal>(); Assert.Throws(() => signal.Fire()); yield break; } void TestBarHandlerTransient() { var cmd = Container.Resolve<DoSomethingSignal>(); Assert.IsEqual(Bar.TriggeredCount, 0); Assert.IsEqual(Bar.InstanceCount, 0); cmd.Fire(); Assert.IsEqual(Bar.TriggeredCount, 1); Assert.IsEqual(Bar.InstanceCount, 1); cmd.Fire(); Assert.IsEqual(Bar.InstanceCount, 2); Assert.IsEqual(Bar.TriggeredCount, 2); } void TestBarHandlerCached() { var cmd = Container.Resolve<DoSomethingSignal>(); Assert.IsEqual(Bar.TriggeredCount, 0); Assert.IsEqual(Bar.InstanceCount, 0); cmd.Fire(); Assert.IsEqual(Bar.TriggeredCount, 1); Assert.IsEqual(Bar.InstanceCount, 1); cmd.Fire(); Assert.IsEqual(Bar.InstanceCount, 1); Assert.IsEqual(Bar.TriggeredCount, 2); } public class DoSomethingSignal : Signal<DoSomethingSignal> { } public class Qux { public Qux(Bar bar) { } } public class Bar { public static int InstanceCount = 0; public Bar() { InstanceCount++; } public static int TriggeredCount { get; set; } public void Execute() { TriggeredCount++; } } } }
using Microsoft.EntityFrameworkCore; using OpenHouse.Core.Services.Interfaces; using OpenHouse.Core.Web.Services.Interfaces; using OpenHouse.Model.Core.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OpenHouse.Core.Services { public class AlertService : IAlertService { private readonly OpenhouseContext _context; public AlertService(OpenhouseContext context) { _context = context; } /// <summary> /// Gets list of alerts in alert view for given tenancy ID /// </summary> /// <param name="tenancyId"></param> /// <returns></returns> public async Task<List<vwalert>> GetAlertsForTenancyAsync(int tenancyId) { var alerts = await _context.vwalert.Where(t => t.tenancyId == tenancyId).ToListAsync(); return alerts; } /// <summary> /// Gets list of all available alert types /// </summary> /// <returns></returns> public async Task<List<alerttype>> GetAlertTypesAsync() { var alertTypes = await _context.alerttype.ToListAsync(); return alertTypes; } } }
using RCommon.Configuration; using RCommon.DependencyInjection; using System; namespace RCommon.Persistence { /// <summary> /// Base interface implemented by specific data configurators that configure RCommon data providers. /// </summary> public interface IObjectAccessConfiguration : IRCommonConfiguration { } }
using Newtonsoft.Json; namespace XamarinActivator.Models { internal class XamarinUser { [JsonProperty("Company")] public string Company; [JsonProperty("Email")] public string Email; [JsonProperty("FirstName")] public string FirstName; [JsonProperty("Guid")] public string Guid; [JsonProperty("LastName")] public string LastName; [JsonProperty("Nickname")] public string Nickname; [JsonProperty("OrganizationName")] public string OrganizationName; [JsonProperty("ParentAccountGuid")] public string ParentAccountGuid; [JsonProperty("PhoneNumber")] public string PhoneNumber; [JsonProperty("TrackingGuid")] public string TrackingGuid; [JsonProperty("TwoLetterCountry")] public string TwoLetterCountry; } }
namespace FootballApp.API.Dtos { public class MatchStatusToReturnDto { public bool Checked { get; set; } public bool Confirmed { get; set; } } }
namespace _6.GraphicalWebCounterUsingDb { using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.IO; using System.Text; using System.Web; public class TextToImageHttpHandler : IHttpHandler { public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { string text = GetTextFromRequest(context); Bitmap bitmap = new Bitmap(1, 1); Font font = new Font("Arial", 25, FontStyle.Regular, GraphicsUnit.Pixel); Graphics graphics = Graphics.FromImage(bitmap); int width = (int)graphics.MeasureString(text, font).Width; int height = (int)graphics.MeasureString(text, font).Height; bitmap = new Bitmap(bitmap, new Size(width, height)); graphics = Graphics.FromImage(bitmap); graphics.Clear(Color.White); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.TextRenderingHint = TextRenderingHint.AntiAlias; graphics.DrawString(text, font, new SolidBrush(Color.FromArgb(0, 0, 0)), 0, 0); graphics.Flush(); string fileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg"; bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg); } private string GetTextFromRequest(HttpContext context) { string text = string.Empty; using (Stream receiveStream = context.Request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { text = readStream.ReadToEnd(); } } return text; } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.Generic; namespace ProjectWork { public class ProducteevTasks { public class Creator { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string email { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string timezone { get; set; } public int timezone_utc_offset { get; set; } public string avatar_path { get; set; } } public class Responsible { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string email { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string timezone { get; set; } public int timezone_utc_offset { get; set; } public string avatar_path { get; set; } } public class Follower { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string email { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string timezone { get; set; } public int timezone_utc_offset { get; set; } public string avatar_path { get; set; } } public class ProjectCreator { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string email { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string timezone { get; set; } public int timezone_utc_offset { get; set; } public string avatar_path { get; set; } } public class NetworkCreator { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string email { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string timezone { get; set; } public int timezone_utc_offset { get; set; } public string avatar_path { get; set; } } public class Network { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string title { get; set; } public NetworkCreator creator { get; set; } public string url { get; set; } } public class Project { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string title { get; set; } public ProjectCreator creator { get; set; } public Network network { get; set; } public bool locked { get; set; } public string description { get; set; } public bool restricted { get; set; } public string url { get; set; } } public class Task { public string id { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string title { get; set; } public int priority { get; set; } public int status { get; set; } public Creator creator { get; set; } public List<Responsible> responsibles { get; set; } public List<Follower> followers { get; set; } public Project project { get; set; } public List<object> labels { get; set; } public List<object> subtasks { get; set; } public int notes_count { get; set; } public bool allday { get; set; } public int reminder { get; set; } public int permissions { get; set; } public string deadline_status { get; set; } public string url { get; set; } } public class RootObject { public List<Task> tasks { get; set; } public int total_hits { get; set; } } } }
using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Database.Entities; namespace Database { public class SchoolContext : DbContext { public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) { } public DbSet<Person> Persons { get; set; } public DbSet<Student> Students { get; set; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; namespace API.ServicesConfigurations { internal static class AuthenticationConfiguration { public static void AddAuthentication(this IServiceCollection services, IConfiguration configuration) { services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.Authority = configuration["Firebase:Authority"]; options.IncludeErrorDetails = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = configuration["Firebase:Issuer"], ValidateAudience = true, ValidAudience = configuration["Firebase:Audience"], ValidateLifetime = true }; }); } public static void UseAuthentication(this IApplicationBuilder app, IConfiguration configuration) { app.UseAuthentication(); } } }
namespace MvcForum.Web.ViewModels.Post { using System; using System.Collections.Generic; using System.Web.Mvc; using Application; public class MovePostViewModel { public PostViewModel Post { get; set; } public IList<SelectListItem> LatestTopics { get; set; } [ForumMvcResourceDisplayName("Post.Move.Label.Topic")] public Guid? TopicId { get; set; } public Guid PostId { get; set; } [ForumMvcResourceDisplayName("Post.Move.Label.NewTopicTitle")] public string TopicTitle { get; set; } [ForumMvcResourceDisplayName("Post.Move.Label.ReplyToPosts")] public bool MoveReplyToPosts { get; set; } } }
using System; namespace Magic { class A { public void Method() { Foo()(); } static Action Foo() => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Reflection.Emit.Tests { public class GenericTypeParameterBuilderMakeArrayType { [Fact] public void MakeArrayType() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); string[] typeParamNames = new string[] { "TFirst" }; GenericTypeParameterBuilder[] typeParams = type.DefineGenericParameters(typeParamNames); Assert.Equal("TFirst[]", typeParams[0].MakeArrayType().Name); } [Fact] public void MakeArrayType_Int_RankOfOne() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); string[] typeParamNames = new string[] { "TFirst" }; GenericTypeParameterBuilder[] typeParams = type.DefineGenericParameters(typeParamNames); Assert.Equal("TFirst[*]", typeParams[0].MakeArrayType(1).Name); } [Fact] public void MakeArrayType_Int_RankOfTwo() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); string[] typeParamNames = new string[] { "TFirst" }; GenericTypeParameterBuilder[] typeParams = type.DefineGenericParameters(typeParamNames); Assert.Equal("TFirst[,]", typeParams[0].MakeArrayType(2).Name); } [Theory] [InlineData(0)] [InlineData(-1)] public void MakeArrayType_Int_RankLessThanOne_ThrowsIndexOutOfRangeException(int rank) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); string[] typeParamNames = new string[] { "TFirst" }; GenericTypeParameterBuilder[] typeParams = type.DefineGenericParameters(typeParamNames); Assert.Throws<IndexOutOfRangeException>(() => typeParams[0].MakeArrayType(rank)); } [Fact] public void IsArray() { GenericTypeParameterBuilder typeParam = Helpers .DynamicType(TypeAttributes.Public) .DefineGenericParameters("TFirst")[0]; Assert.False(typeParam.IsArray); Assert.False(typeParam.IsSZArray); Type asType = typeParam.AsType(); Assert.False(asType.IsArray); Assert.False(asType.IsSZArray); Type arrType = typeParam.MakeArrayType(); Assert.True(arrType.IsArray); Assert.True(arrType.IsSZArray); arrType = typeParam.MakeArrayType(1); Assert.True(arrType.IsArray); Assert.False(arrType.IsSZArray); arrType = typeParam.MakeArrayType(2); Assert.True(arrType.IsArray); Assert.False(arrType.IsSZArray); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Calendar.Dart { internal partial class JokersPanel : ThemedPanel { public JokersPanel() { InitializeComponent(); JokerControls = new List<JokerControl> { jokerControl1, jokerControl2, jokerControl3, jokerControl4, jokerControl5, jokerControl6, jokerControl7, jokerControl8 }; } private List<JokerControl> JokerControls { get; } private void JokersControlResize(object sender, EventArgs e) { ScaleText(labelCaption); ScaleText(buttonNext); } public override void Activate() { base.Activate(); labelCaption.Text = @"Jokers" + Environment.NewLine + Game.CurrentCategory; ScaleText(labelCaption); for (var i = 0; i < Game.Players.Count; i++) { JokerControls[i].Game = Game; JokerControls[i].Player = Game.Players[i]; } JokerControls.Skip(Game.Players.Count).ToList().ForEach(c => c.Visible = false); } private void ButtonNextClick(object sender, EventArgs e) { foreach (var player in Game.Players) { player.Jokers.Remove(player.Joker); } JokerControls.ForEach(c => c.Player = null); NextPanel<QuestionPanel>(); } } }
using ServiceStack.Text; using System; using System.IO; using System.Linq; namespace CsvJoin.Utilities { public static class CsvUtilities { public static string[] ReadHeader(string directory, string fileName) { string path = Path.Combine( Environment.CurrentDirectory, directory, fileName); string header = File.ReadLines(path).First(); return CsvReader.ParseFields(header).ToArray(); } } }
// HeaderSection.cs // Created by: Adam Renaud // Created on: 2018-01-05 // System Using Statements using System.Collections.Generic; using System.Linq; // Internal Using Statements namespace DxfLibrary.Parse.Sections { /// <summary> /// Class that contains all of the properties for the header of the /// Dxf file /// </summary> public class HeaderSection : IDxfParsable { /// <summary> /// The Version of the File, AutoCAD Version /// </summary> public string FileVersion {get; set;} /// <summary> /// Who the file was last saved by /// </summary> public string LastSavedBy {get; set;} /// <summary> /// Set a property in the class from the name of /// the property /// </summary> /// <param name="name">The name of the the property</param> /// <param name="value">The value of the property</param> public void SetProperty(string name, object value) { switch(name) { case nameof(FileVersion): FileVersion = value as string; break; case nameof(LastSavedBy): LastSavedBy = value as string; break; // If nothing matches then break and return default: break; } } } /// <summary> /// Enumeration of the different AutoCAD Versions /// </summary> public enum AutoCADVersion { AC1006, AC1009, AC1032 } }
using System; using System.Data; namespace Arch.Data.Orm.sql { public class SqlColumn : IColumn { public SqlColumn(ITable table, String name, IDataBridge data) { Ordinal = -1; Table = table; Name = name.ToLower(); Data = data; } public IDataBridge Data { get; set; } public Int32 Ordinal { get; set; } public ITable Table { get; private set; } public Type DataType { get { return Data.DataType; } } public Int32 Length { get; set; } public String Name { get; private set; } public DbType? ColumnType { get; set; } public Object DefaultValue { get; set; } private String alias; public String Alias { get { return String.IsNullOrEmpty(alias) ? Name : alias; } set { alias = (value == null) ? null : value.ToLower(); } } public String TimestampExpression { get; set; } public Boolean IsPK { get; set; } public Boolean IsOutPut { get; set; } public Boolean IsVersionLock { get; set; } public Boolean IsTimestampLock { get; set; } public Boolean IsReturnValue { get; set; } public Boolean IsID { get; set; } public Boolean IsReadable { get { return Data.Readable; } } public Boolean IsWriteable { get { return Data.Writeable; } } public void SetParameterValue(IDbDataParameter p, Object obj) { Object val = Data.Read(obj); p.Value = val ?? DBNull.Value; } public void SetValue(Object obj, Object val) { try { if (val == null || val == DBNull.Value) { Data.Write(obj, DefaultValue); } else { Data.Write(obj, val); } } catch (Exception ex) { throw new DalException(String.Format("Assign {0} to {1} failed,data type of property is {2}.", val, Name, DataType), ex); } } public Boolean IsIgnored { get; set; } } }
using System; namespace VinilEcommerce.Infrastructure.Data.DataBase.Disk.Services.Spotify { public class SpotifyDateDataBaseRequest { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int Page { get; set; } public int RecordsNumber { get; set; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using NUnit.Framework; using Rebus.AzureStorage.Transport; using Rebus.Messages; using Rebus.Tests; using Rebus.Tests.Contracts.Transports; using Rebus.Time; namespace Rebus.AzureStorage.Tests.Transport { [TestFixture, Category(TestCategory.Azure)] public class AzureStorageQueuesTransportBasicSendReceive : BasicSendReceive<AzureStorageQueuesTransportFactory> { [Test] public async Task GetQueueVisibilityDelayOrNull_NeverReturnsNegativeTimespans() { var sendInstant = DateTimeOffset.Now; var deferDate = sendInstant.AddMilliseconds(-350); RebusTimeMachine.FakeIt(sendInstant); var result = AzureStorageQueuesTransport.GetQueueVisibilityDelayOrNull(new Dictionary<string, string> { {Headers.DeferredUntil, deferDate.ToString("O")} }); RebusTimeMachine.Reset(); Assert.Null(result); } [Test] public async Task GetQueueVisibilityDelayOrNull_StillReturnsPositiveTimespans() { var sendInstant = DateTimeOffset.Now; var deferDate = sendInstant.AddMilliseconds(350); RebusTimeMachine.FakeIt(sendInstant); var result = AzureStorageQueuesTransport.GetQueueVisibilityDelayOrNull(new Dictionary<string, string> { {Headers.DeferredUntil, deferDate.ToString("O")} }); RebusTimeMachine.Reset(); Assert.AreEqual(result, TimeSpan.FromMilliseconds(350)); } } }
using System; using System.IO.Compression; namespace MonoGame.Imaging.Coders.Formats.Png { [Serializable] public class PngEncoderOptions : EncoderOptions { public CompressionLevel CompressionLevel { get; } public PngEncoderOptions(CompressionLevel compression) { CompressionLevel = compression; } public PngEncoderOptions() : this(CompressionLevel.Fastest) { } } }
// GENERATED AUTOMATICALLY FROM 'Assets/InputMaster.inputactions' using System; using System.Collections; using System.Collections.Generic; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Utilities; public class @InputMaster : IInputActionCollection, IDisposable { public InputActionAsset asset { get; } public @InputMaster() { asset = InputActionAsset.FromJson(@"{ ""name"": ""InputMaster"", ""maps"": [ { ""name"": ""Player"", ""id"": ""ea39f397-1621-4452-9fe9-8edb83e4d5af"", ""actions"": [ { ""name"": ""Movement"", ""type"": ""Value"", ""id"": ""2ae92ce4-4106-488d-a7ce-1b6c1c468571"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """" }, { ""name"": ""MouseMovement"", ""type"": ""PassThrough"", ""id"": ""b962a800-b1b2-4814-885a-c853d0a8d5ce"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """" }, { ""name"": ""Jump"", ""type"": ""PassThrough"", ""id"": ""0962e210-932c-4c6d-ab78-199649cf3645"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": """" }, { ""name"": ""Interact"", ""type"": ""PassThrough"", ""id"": ""62242559-c20e-41c6-bc6d-42676f909a7b"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"" }, { ""name"": ""StopInteract"", ""type"": ""PassThrough"", ""id"": ""9d2b6a42-7c45-4712-b517-f34a23d7d235"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press(behavior=1)"" }, { ""name"": ""ToggleInventory"", ""type"": ""Button"", ""id"": ""bc7f2ed5-eb43-47d5-a22f-f9946eb71797"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"" }, { ""name"": ""UIMousePosition"", ""type"": ""Value"", ""id"": ""64e527f7-6765-46e3-8a4b-d329f4cb9c36"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """" }, { ""name"": ""SecondaryInteract "", ""type"": ""Button"", ""id"": ""a11ceefe-4dbc-47c1-93ee-05bd64fb12d1"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": """" }, { ""name"": ""Drop"", ""type"": ""Button"", ""id"": ""ec6dc395-6b34-4134-8215-e0b7ce2d6e40"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": """" }, { ""name"": ""SlotChange"", ""type"": ""PassThrough"", ""id"": ""550fd130-fc88-4029-a754-020d1461ba34"", ""expectedControlType"": ""Axis"", ""processors"": """", ""interactions"": """" }, { ""name"": ""InstantSlotChange"", ""type"": ""PassThrough"", ""id"": ""03a9c8ad-5083-4ad7-85b1-9592000bfe78"", ""expectedControlType"": ""Axis"", ""processors"": """", ""interactions"": """" }, { ""name"": ""RemoveBuilding"", ""type"": ""PassThrough"", ""id"": ""89203782-9ab0-40cc-802a-92309f7c5853"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"" } ], ""bindings"": [ { ""name"": ""WASD"", ""id"": ""b3eb7a7e-5b09-49f4-814a-a1886a377380"", ""path"": ""2DVector"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Movement"", ""isComposite"": true, ""isPartOfComposite"": false }, { ""name"": ""up"", ""id"": ""e542145d-e858-4fca-aa0a-5ee1e812289c"", ""path"": ""<Keyboard>/w"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Movement"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""c559b4e6-b795-4bc4-bcc9-bb01c1485985"", ""path"": ""<Keyboard>/s"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Movement"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""3abf52b9-cdfa-43b8-b320-ff2411fa59cb"", ""path"": ""<Keyboard>/a"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Movement"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""a2dac824-05c9-422d-b76f-16239b2352df"", ""path"": ""<Keyboard>/d"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Movement"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": """", ""id"": ""3b63bf0c-7a24-4ff8-bc85-f32004f83170"", ""path"": ""<Mouse>/delta"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""MouseMovement"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""68474c9c-da52-42b2-8ec3-9c3b8efa5825"", ""path"": ""<Keyboard>/space"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Jump"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""6f4d6d79-870b-46f0-b3e3-afd708bb63e1"", ""path"": ""<Mouse>/leftButton"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Interact"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""cd36abf2-9152-42c8-b9c9-c814953c66df"", ""path"": ""<Mouse>/leftButton"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""StopInteract"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""bbca22a7-9444-4aed-a85b-8a1cd861360d"", ""path"": ""<Keyboard>/e"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""ToggleInventory"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""2a2bfd61-dd72-45f0-9b68-bc0fc30b8c30"", ""path"": ""<Mouse>/position"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""UIMousePosition"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""65892521-5895-4a28-90f5-9287077b7e75"", ""path"": ""<Mouse>/rightButton"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""SecondaryInteract "", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""f27d7604-c5c1-4ab7-84f4-a0499f88e113"", ""path"": ""<Keyboard>/q"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Drop"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""95069187-3f0b-477a-8a1b-9c33071705d2"", ""path"": ""<Mouse>/scroll/y"", ""interactions"": """", ""processors"": ""Clamp(min=-1,max=1),Normalize(min=-1,max=1)"", ""groups"": """", ""action"": ""SlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""51cace0f-5bef-4c37-92cb-5a664d66ad42"", ""path"": ""<Keyboard>/1"", ""interactions"": """", ""processors"": ""Scale"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""e17b8776-bdc7-4d07-ae32-a2410857f254"", ""path"": ""<Keyboard>/2"", ""interactions"": """", ""processors"": ""Scale(factor=2)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""36c7ae39-a216-4b71-9f12-330bd9ce8a63"", ""path"": ""<Keyboard>/3"", ""interactions"": """", ""processors"": ""Scale(factor=3)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""8958b547-3fa8-4a13-ac08-5675206ecf0e"", ""path"": ""<Keyboard>/4"", ""interactions"": """", ""processors"": ""Scale(factor=4)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""6ef1e833-776e-4457-8935-12d4eb7c3873"", ""path"": ""<Keyboard>/5"", ""interactions"": """", ""processors"": ""Scale(factor=5)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""65c43792-a115-4a2d-b0e8-1e290b2b2b10"", ""path"": ""<Keyboard>/6"", ""interactions"": """", ""processors"": ""Scale(factor=6)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""3b9cc670-95c5-48df-b77e-9be8db6a4c46"", ""path"": ""<Keyboard>/7"", ""interactions"": """", ""processors"": ""Scale(factor=7)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""050751af-1182-4b96-9401-093dc84776d2"", ""path"": ""<Keyboard>/8"", ""interactions"": """", ""processors"": ""Scale(factor=8)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""060e70a3-43ea-41b3-abff-3037aed50f80"", ""path"": ""<Keyboard>/9"", ""interactions"": """", ""processors"": ""Scale(factor=9)"", ""groups"": """", ""action"": ""InstantSlotChange"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""b5225a59-514e-4204-837f-ef9944b660d3"", ""path"": ""<Keyboard>/f"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""RemoveBuilding"", ""isComposite"": false, ""isPartOfComposite"": false } ] }, { ""name"": ""Testing"", ""id"": ""5fd5db50-da18-480b-aa0c-097e392c4f37"", ""actions"": [ { ""name"": ""MousePosition"", ""type"": ""PassThrough"", ""id"": ""e4e7a5aa-6e82-45a9-a985-9967506d8fe6"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """" }, { ""name"": ""Left Click"", ""type"": ""PassThrough"", ""id"": ""e8bac482-8ebc-4e00-bbc3-38d50d6c5d98"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"" }, { ""name"": ""Right Click"", ""type"": ""PassThrough"", ""id"": ""525fb795-7eba-4007-a3d8-f9e5db36aa39"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"" }, { ""name"": ""G"", ""type"": ""Button"", ""id"": ""b042ec12-994c-4e66-991a-39fe7aaca04e"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"" } ], ""bindings"": [ { ""name"": """", ""id"": ""215b7424-f894-4ca7-9058-9582d8200786"", ""path"": ""<Mouse>/position"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""MousePosition"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""a8204cd7-cba6-469a-91cb-5fafd70b643d"", ""path"": ""<Mouse>/leftButton"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Left Click"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""505cb326-1978-476b-9e5c-2eac4285f986"", ""path"": ""<Mouse>/rightButton"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Right Click"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""51698996-b8e2-486f-aa30-580954e37031"", ""path"": ""<Keyboard>/g"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""G"", ""isComposite"": false, ""isPartOfComposite"": false } ] } ], ""controlSchemes"": [] }"); // Player m_Player = asset.FindActionMap("Player", throwIfNotFound: true); m_Player_Movement = m_Player.FindAction("Movement", throwIfNotFound: true); m_Player_MouseMovement = m_Player.FindAction("MouseMovement", throwIfNotFound: true); m_Player_Jump = m_Player.FindAction("Jump", throwIfNotFound: true); m_Player_Interact = m_Player.FindAction("Interact", throwIfNotFound: true); m_Player_StopInteract = m_Player.FindAction("StopInteract", throwIfNotFound: true); m_Player_ToggleInventory = m_Player.FindAction("ToggleInventory", throwIfNotFound: true); m_Player_UIMousePosition = m_Player.FindAction("UIMousePosition", throwIfNotFound: true); m_Player_SecondaryInteract = m_Player.FindAction("SecondaryInteract ", throwIfNotFound: true); m_Player_Drop = m_Player.FindAction("Drop", throwIfNotFound: true); m_Player_SlotChange = m_Player.FindAction("SlotChange", throwIfNotFound: true); m_Player_InstantSlotChange = m_Player.FindAction("InstantSlotChange", throwIfNotFound: true); m_Player_RemoveBuilding = m_Player.FindAction("RemoveBuilding", throwIfNotFound: true); // Testing m_Testing = asset.FindActionMap("Testing", throwIfNotFound: true); m_Testing_MousePosition = m_Testing.FindAction("MousePosition", throwIfNotFound: true); m_Testing_LeftClick = m_Testing.FindAction("Left Click", throwIfNotFound: true); m_Testing_RightClick = m_Testing.FindAction("Right Click", throwIfNotFound: true); m_Testing_G = m_Testing.FindAction("G", throwIfNotFound: true); } public void Dispose() { UnityEngine.Object.Destroy(asset); } public InputBinding? bindingMask { get => asset.bindingMask; set => asset.bindingMask = value; } public ReadOnlyArray<InputDevice>? devices { get => asset.devices; set => asset.devices = value; } public ReadOnlyArray<InputControlScheme> controlSchemes => asset.controlSchemes; public bool Contains(InputAction action) { return asset.Contains(action); } public IEnumerator<InputAction> GetEnumerator() { return asset.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Enable() { asset.Enable(); } public void Disable() { asset.Disable(); } // Player private readonly InputActionMap m_Player; private IPlayerActions m_PlayerActionsCallbackInterface; private readonly InputAction m_Player_Movement; private readonly InputAction m_Player_MouseMovement; private readonly InputAction m_Player_Jump; private readonly InputAction m_Player_Interact; private readonly InputAction m_Player_StopInteract; private readonly InputAction m_Player_ToggleInventory; private readonly InputAction m_Player_UIMousePosition; private readonly InputAction m_Player_SecondaryInteract; private readonly InputAction m_Player_Drop; private readonly InputAction m_Player_SlotChange; private readonly InputAction m_Player_InstantSlotChange; private readonly InputAction m_Player_RemoveBuilding; public struct PlayerActions { private @InputMaster m_Wrapper; public PlayerActions(@InputMaster wrapper) { m_Wrapper = wrapper; } public InputAction @Movement => m_Wrapper.m_Player_Movement; public InputAction @MouseMovement => m_Wrapper.m_Player_MouseMovement; public InputAction @Jump => m_Wrapper.m_Player_Jump; public InputAction @Interact => m_Wrapper.m_Player_Interact; public InputAction @StopInteract => m_Wrapper.m_Player_StopInteract; public InputAction @ToggleInventory => m_Wrapper.m_Player_ToggleInventory; public InputAction @UIMousePosition => m_Wrapper.m_Player_UIMousePosition; public InputAction @SecondaryInteract => m_Wrapper.m_Player_SecondaryInteract; public InputAction @Drop => m_Wrapper.m_Player_Drop; public InputAction @SlotChange => m_Wrapper.m_Player_SlotChange; public InputAction @InstantSlotChange => m_Wrapper.m_Player_InstantSlotChange; public InputAction @RemoveBuilding => m_Wrapper.m_Player_RemoveBuilding; public InputActionMap Get() { return m_Wrapper.m_Player; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public bool enabled => Get().enabled; public static implicit operator InputActionMap(PlayerActions set) { return set.Get(); } public void SetCallbacks(IPlayerActions instance) { if (m_Wrapper.m_PlayerActionsCallbackInterface != null) { @Movement.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMovement; @Movement.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMovement; @Movement.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMovement; @MouseMovement.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMouseMovement; @MouseMovement.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMouseMovement; @MouseMovement.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMouseMovement; @Jump.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnJump; @Jump.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnJump; @Jump.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnJump; @Interact.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnInteract; @Interact.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnInteract; @Interact.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnInteract; @StopInteract.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnStopInteract; @StopInteract.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnStopInteract; @StopInteract.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnStopInteract; @ToggleInventory.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnToggleInventory; @ToggleInventory.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnToggleInventory; @ToggleInventory.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnToggleInventory; @UIMousePosition.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnUIMousePosition; @UIMousePosition.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnUIMousePosition; @UIMousePosition.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnUIMousePosition; @SecondaryInteract.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnSecondaryInteract; @SecondaryInteract.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnSecondaryInteract; @SecondaryInteract.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnSecondaryInteract; @Drop.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnDrop; @Drop.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnDrop; @Drop.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnDrop; @SlotChange.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnSlotChange; @SlotChange.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnSlotChange; @SlotChange.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnSlotChange; @InstantSlotChange.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnInstantSlotChange; @InstantSlotChange.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnInstantSlotChange; @InstantSlotChange.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnInstantSlotChange; @RemoveBuilding.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnRemoveBuilding; @RemoveBuilding.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnRemoveBuilding; @RemoveBuilding.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnRemoveBuilding; } m_Wrapper.m_PlayerActionsCallbackInterface = instance; if (instance != null) { @Movement.started += instance.OnMovement; @Movement.performed += instance.OnMovement; @Movement.canceled += instance.OnMovement; @MouseMovement.started += instance.OnMouseMovement; @MouseMovement.performed += instance.OnMouseMovement; @MouseMovement.canceled += instance.OnMouseMovement; @Jump.started += instance.OnJump; @Jump.performed += instance.OnJump; @Jump.canceled += instance.OnJump; @Interact.started += instance.OnInteract; @Interact.performed += instance.OnInteract; @Interact.canceled += instance.OnInteract; @StopInteract.started += instance.OnStopInteract; @StopInteract.performed += instance.OnStopInteract; @StopInteract.canceled += instance.OnStopInteract; @ToggleInventory.started += instance.OnToggleInventory; @ToggleInventory.performed += instance.OnToggleInventory; @ToggleInventory.canceled += instance.OnToggleInventory; @UIMousePosition.started += instance.OnUIMousePosition; @UIMousePosition.performed += instance.OnUIMousePosition; @UIMousePosition.canceled += instance.OnUIMousePosition; @SecondaryInteract.started += instance.OnSecondaryInteract; @SecondaryInteract.performed += instance.OnSecondaryInteract; @SecondaryInteract.canceled += instance.OnSecondaryInteract; @Drop.started += instance.OnDrop; @Drop.performed += instance.OnDrop; @Drop.canceled += instance.OnDrop; @SlotChange.started += instance.OnSlotChange; @SlotChange.performed += instance.OnSlotChange; @SlotChange.canceled += instance.OnSlotChange; @InstantSlotChange.started += instance.OnInstantSlotChange; @InstantSlotChange.performed += instance.OnInstantSlotChange; @InstantSlotChange.canceled += instance.OnInstantSlotChange; @RemoveBuilding.started += instance.OnRemoveBuilding; @RemoveBuilding.performed += instance.OnRemoveBuilding; @RemoveBuilding.canceled += instance.OnRemoveBuilding; } } } public PlayerActions @Player => new PlayerActions(this); // Testing private readonly InputActionMap m_Testing; private ITestingActions m_TestingActionsCallbackInterface; private readonly InputAction m_Testing_MousePosition; private readonly InputAction m_Testing_LeftClick; private readonly InputAction m_Testing_RightClick; private readonly InputAction m_Testing_G; public struct TestingActions { private @InputMaster m_Wrapper; public TestingActions(@InputMaster wrapper) { m_Wrapper = wrapper; } public InputAction @MousePosition => m_Wrapper.m_Testing_MousePosition; public InputAction @LeftClick => m_Wrapper.m_Testing_LeftClick; public InputAction @RightClick => m_Wrapper.m_Testing_RightClick; public InputAction @G => m_Wrapper.m_Testing_G; public InputActionMap Get() { return m_Wrapper.m_Testing; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public bool enabled => Get().enabled; public static implicit operator InputActionMap(TestingActions set) { return set.Get(); } public void SetCallbacks(ITestingActions instance) { if (m_Wrapper.m_TestingActionsCallbackInterface != null) { @MousePosition.started -= m_Wrapper.m_TestingActionsCallbackInterface.OnMousePosition; @MousePosition.performed -= m_Wrapper.m_TestingActionsCallbackInterface.OnMousePosition; @MousePosition.canceled -= m_Wrapper.m_TestingActionsCallbackInterface.OnMousePosition; @LeftClick.started -= m_Wrapper.m_TestingActionsCallbackInterface.OnLeftClick; @LeftClick.performed -= m_Wrapper.m_TestingActionsCallbackInterface.OnLeftClick; @LeftClick.canceled -= m_Wrapper.m_TestingActionsCallbackInterface.OnLeftClick; @RightClick.started -= m_Wrapper.m_TestingActionsCallbackInterface.OnRightClick; @RightClick.performed -= m_Wrapper.m_TestingActionsCallbackInterface.OnRightClick; @RightClick.canceled -= m_Wrapper.m_TestingActionsCallbackInterface.OnRightClick; @G.started -= m_Wrapper.m_TestingActionsCallbackInterface.OnG; @G.performed -= m_Wrapper.m_TestingActionsCallbackInterface.OnG; @G.canceled -= m_Wrapper.m_TestingActionsCallbackInterface.OnG; } m_Wrapper.m_TestingActionsCallbackInterface = instance; if (instance != null) { @MousePosition.started += instance.OnMousePosition; @MousePosition.performed += instance.OnMousePosition; @MousePosition.canceled += instance.OnMousePosition; @LeftClick.started += instance.OnLeftClick; @LeftClick.performed += instance.OnLeftClick; @LeftClick.canceled += instance.OnLeftClick; @RightClick.started += instance.OnRightClick; @RightClick.performed += instance.OnRightClick; @RightClick.canceled += instance.OnRightClick; @G.started += instance.OnG; @G.performed += instance.OnG; @G.canceled += instance.OnG; } } } public TestingActions @Testing => new TestingActions(this); public interface IPlayerActions { void OnMovement(InputAction.CallbackContext context); void OnMouseMovement(InputAction.CallbackContext context); void OnJump(InputAction.CallbackContext context); void OnInteract(InputAction.CallbackContext context); void OnStopInteract(InputAction.CallbackContext context); void OnToggleInventory(InputAction.CallbackContext context); void OnUIMousePosition(InputAction.CallbackContext context); void OnSecondaryInteract(InputAction.CallbackContext context); void OnDrop(InputAction.CallbackContext context); void OnSlotChange(InputAction.CallbackContext context); void OnInstantSlotChange(InputAction.CallbackContext context); void OnRemoveBuilding(InputAction.CallbackContext context); } public interface ITestingActions { void OnMousePosition(InputAction.CallbackContext context); void OnLeftClick(InputAction.CallbackContext context); void OnRightClick(InputAction.CallbackContext context); void OnG(InputAction.CallbackContext context); } }
using System.Collections.Generic; namespace Satsuma { public sealed class ReverseGraph : IGraph, IArcLookup { private IGraph graph; public static ArcFilter Reverse(ArcFilter filter) { return filter switch { ArcFilter.Forward => ArcFilter.Backward, ArcFilter.Backward => ArcFilter.Forward, _ => filter, }; } public ReverseGraph(IGraph graph) { this.graph = graph; } public Node U(Arc arc) { return graph.V(arc); } public Node V(Arc arc) { return graph.U(arc); } public bool IsEdge(Arc arc) { return graph.IsEdge(arc); } public IEnumerable<Node> Nodes() { return graph.Nodes(); } public IEnumerable<Arc> Arcs(ArcFilter filter = ArcFilter.All) { return graph.Arcs(filter); } public IEnumerable<Arc> Arcs(Node u, ArcFilter filter = ArcFilter.All) { return graph.Arcs(u, Reverse(filter)); } public IEnumerable<Arc> Arcs(Node u, Node v, ArcFilter filter = ArcFilter.All) { return graph.Arcs(u, v, Reverse(filter)); } public int NodeCount() { return graph.NodeCount(); } public int ArcCount(ArcFilter filter = ArcFilter.All) { return graph.ArcCount(filter); } public int ArcCount(Node u, ArcFilter filter = ArcFilter.All) { return graph.ArcCount(u, Reverse(filter)); } public int ArcCount(Node u, Node v, ArcFilter filter = ArcFilter.All) { return graph.ArcCount(u, v, Reverse(filter)); } public bool HasNode(Node node) { return graph.HasNode(node); } public bool HasArc(Arc arc) { return graph.HasArc(arc); } } }
using System; namespace Strategy { public interface IProduct { decimal SellingPrice(); bool IsOnSale(); } }
using SimPaulOnbase.Core.Boundaries.Customers; namespace SimPaulOnbase.Core.UseCases.Customers { /// <summary> /// CustomerIntegrationUseCase interface /// </summary> public interface ICustomerIncompledIntegrationUseCase { CustomerIntegrationOutput Handle(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; namespace Tohasoft.Net.Extension { public static class StaticExtensions { public static IPAddress[] GetAllSubnet(this IPAddress hostIP, IPAddress netmask) { var IPs = new List<IPAddress>(); var hostInt = hostIP.ToLong(); var netmaskInt = netmask.ToLong(); var wildCard = ~(uint)netmaskInt; var netBytesInt = hostInt & netmaskInt; for (var start = 1; start <= wildCard - 1; start++) { var ip = new IPAddress((netBytesInt + start).ToBytes()); if (!ip.Equals(hostIP)) IPs.Add(ip); } return IPs.ToArray(); } public static IPAddress Increment(this IPAddress hostIP, IPAddress netmask) { var hostInt = hostIP.ToLong(); var netmaskInt = netmask.ToLong(); var wildCard = ~(uint)netmaskInt; var netBytesInt = hostInt & netmaskInt; if (hostInt == netBytesInt + wildCard - 1) return null; return new IPAddress(hostInt + 1); } public static long ToLong(this IPAddress address) { uint ip = 0; var data = address.GetAddressBytes(); for (var i = 0; i < data.Length; i++) { ip += ((uint)data[i]) << (8 * (data.Length - i - 1)); } return ip; } public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask) { var ipAdressBytes = address.GetAddressBytes(); var subnetMaskBytes = subnetMask.GetAddressBytes(); if (ipAdressBytes.Length != subnetMaskBytes.Length) throw new ArgumentException("Lengths of IP address and subnet mask do not match."); var broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); } return new IPAddress(broadcastAddress); } public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask) { var ipAdressBytes = address.GetAddressBytes(); var subnetMaskBytes = subnetMask.GetAddressBytes(); if (ipAdressBytes.Length != subnetMaskBytes.Length) throw new ArgumentException("Lengths of IP address and subnet mask do not match."); var broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i])); } return new IPAddress(broadcastAddress); } public static IPAddress GetSubnetMask(this IPAddress address) { foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces()) { foreach (var addressInformation in adapter.GetIPProperties().UnicastAddresses) { if (addressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { if (address.ToString().Equals(addressInformation.Address.ToString())) { return addressInformation.IPv4Mask; } } } } return null; } public static bool IsInSameSubnet(this IPAddress address2, IPAddress address, IPAddress subnetMask) { IPAddress network1 = address.GetNetworkAddress(subnetMask); IPAddress network2 = address2.GetNetworkAddress(subnetMask); return network1.Equals(network2); } public static void FillZero(this byte[] data) { for (var i = 0; i < data.Length; i++) { data[i] = 0; } } public static string ToString(this byte[] data, int len) { var dString = string.Empty; if (data == null) return dString; for (var i = 0; i < len; i++) { dString += data[i].ToString("X2"); } return dString; } public static byte[] ToBytes(this long data) { var bytes = new byte[4]; for (var i = 0; i < bytes.Length; i++) { bytes[i] = (byte)(data >> (8 * (bytes.Length - i - 1))); } return bytes; } } }
namespace Masa.Framework.Admin.Service.Authentication.Application.Permissions.Queries; public class PermissionDetailQueryValidator : AbstractValidator<PermissionDetailQuery> { public PermissionDetailQueryValidator() { RuleFor(query => query) .NotNull().WithMessage($"Parameter error"); RuleFor(query => query.PermissionId) .NotEqual(Guid.Empty).WithMessage("Please select a permission id"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using CapaDatos; namespace CapaNegocio { public class NVenta { //Método insertar que llama al método insertar de la clase dcategoria //de la capadatos public static string Insertar(int idcliente, int idtrabajador, DateTime fecha, string tipo_comprobante, string serie, string correlativo, decimal igv,DataTable dtDetalles) { DVenta Obj = new DVenta(); Obj.Idcliente = idcliente; Obj.Idtrabajador = idtrabajador; Obj.Fecha = fecha; Obj.Tipo_Comprobante = tipo_comprobante; Obj.Serie = serie; Obj.Correlativo = correlativo; Obj.Igv = igv; List<DDetalle_Venta> detalles = new List<DDetalle_Venta>(); foreach (DataRow row in dtDetalles.Rows) { DDetalle_Venta detalle = new DDetalle_Venta(); detalle.Iddetalle_Ingreso = Convert.ToInt32(row["iddetalle_ingreso"].ToString()); detalle.Cantidad = Convert.ToInt32(row["cantidad"].ToString()); detalle.Precio_Venta = Convert.ToDecimal(row["precio_venta"].ToString()); detalle.Descuento = Convert.ToDecimal(row["descuento"].ToString()); detalles.Add(detalle); } return Obj.Insertar(Obj, detalles); } //Método eliminar que llama al metodo eliminar de la clase dcategoria //de la capadatos public static string Eliminar(int idventa) { DVenta Obj = new DVenta(); Obj.Idventa = idventa; return Obj.Eliminar(Obj); } //Método mostrar que llama al metodo mostrar de la clase dventas //de la capadatos public static DataTable Mostrar() { return new DVenta().Mostrar(); } //Método buscarnombre que llama al metodo buscarfecha de la clase dventa //de la capadatos public static DataTable BuscarFechas(string textobuscar, string textobuscar2) { DVenta Obj = new DVenta(); return Obj.BuscarFechas(textobuscar, textobuscar2); } public static DataTable MostrarDetalle(string textobuscar) { DVenta Obj = new DVenta(); return Obj.MostrarDetalle(textobuscar); } public static DataTable MostrarArticulo_Venta_Nombre(string textobuscar) { DVenta Obj = new DVenta(); return Obj.MostrarArticulo_Venta_Nombre(textobuscar); } public static DataTable MostrarArticulo_Venta_Codigo(string textobuscar) { DVenta Obj = new DVenta(); return Obj.MostrarArticulo_Venta_Codigo(textobuscar); } } }
using AspNet.Dev.Pkg.Infrastructure.Controller; using AspNet.Dev.Pkg.Infrastructure.Interface; using Microsoft.AspNetCore.Mvc; namespace AspNet.Dev.Pkg.Demo.Controllers { [ApiController] [Route("[controller]")] public class DemoController : CrudController<Demo, DemoGet, DemoCreate> { public DemoController() { } } }
//_______________________________________________________________ // Title : ToolStripMenuItemInfo // System : Microsoft VisualStudio 2013 / C# // $LastChangedDate$ // $Rev$ // $LastChangedBy$ // $URL$ // $Id$ // // Copyright (C) 2015, CAS LODZ POLAND. // TEL: +48 (42) 686 25 47 // mailto://techsupp@cas.eu // http://www.cas.eu //_______________________________________________________________ namespace CAS.UA.Model.Designer.ImportExport { internal class ToolStripMenuItemInfo : IToolStripMenuItemInfo { public ToolStripMenuItemInfo(string name, string text, string toolTipText) { Name = name; Text = text; ToolTipText = toolTipText; } public string Name { get; private set; } public string Text { get; private set; } public string ToolTipText { get; private set; } } }
using FluentAssertions; using NUnit.Framework; using Testing.Common.Domain.TestClasses; namespace ServiceLayer.UnitTests.Models.DataResult_2.Operators.Implicit { public class From_SuccessResult : UnitTestBase { private readonly SuccessResult<TestData> _successResult = new SuccessResult<TestData>(new TestData()); private DataResult<TestData, TestCustomResultType> _actualDataResult; private DataResult<TestData, TestCustomResultType> _expectedDataResult; protected override void Act() { _actualDataResult = _successResult; } [Test] public void Should_Be_Expected_DataResult() { _actualDataResult.Should().BeSameAs(_expectedDataResult); } protected override void Arrange() { _expectedDataResult = MockDataResultFactory.Object.Create<TestData, TestCustomResultType>(_successResult); } } }
using System.IO; using System; using System.Runtime.Serialization.Formatters.Binary; using System.Reflection; namespace DCL_Core.Wallet { class FileBinIO { public static void WriteBin(byte[] _storage, string _fileName) { //Write to wallet file String FileFolder = AppDomain.CurrentDomain.BaseDirectory + @"bin\\WalletData\\"; String FilePath = FileFolder + _fileName + ".bin"; if (!Directory.Exists(FileFolder)) { //Create directory if it does not exist Directory.CreateDirectory(FileFolder); } BinaryWriter writer = new BinaryWriter(File.Open(FilePath, FileMode.Create)); writer.Write(_storage); //Write binaries writer.Close(); } public static byte[] ReadBin(String _fileName) { String FileFolder = AppDomain.CurrentDomain.BaseDirectory + @"bin\\WalletData\\"; String FilePath = FileFolder + _fileName + ".bin"; StreamReader sr = new StreamReader(FilePath); var bytes = default(byte[]); using (var memstream = new MemoryStream()) { sr.BaseStream.CopyTo(memstream); bytes = memstream.ToArray(); } sr.Close(); //Close connection to avoid fileOpening errors return bytes; } public static Boolean Exists(String _fileName) { String FileFolder = AppDomain.CurrentDomain.BaseDirectory + @"bin\\WalletData\\"; String FilePath = FileFolder + _fileName + ".bin"; return File.Exists(FilePath); } } }
namespace Semantity { using Definitions; public class PicoSecond : Unit<Time> { public static PicoSecond Instance { get; } = new PicoSecond(); public override string Symbol => "ps"; public override double FactorToBaseUnit => 1.0e-12; } }
using AtCoderBeginnerContest127.Questions; using AtCoderBeginnerContest127.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AtCoderBeginnerContest127.Questions { public class QuestionB : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { var rdx = inputStream.ReadIntArray(); var r = rdx[0]; var d = rdx[1]; var x = rdx[2]; for (int i = 2001; i <= 2010; i++) { x = r * x - d; yield return x; } } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information namespace Elastic.Ingest { public enum ConnectionPoolType { Unknown = 0, SingleNode, Sniffing, Static, Sticky, StickySniffing, Cloud } }
using System; using System.Collections.Generic; using System.Linq; namespace Stashbox.Utils.Data { internal class Stack<TValue> : ExpandableArray<TValue> { public new static Stack<TValue> FromEnumerable(IEnumerable<TValue> enumerable) => new(enumerable); public Stack() { } public Stack(IEnumerable<TValue> initial) : base(initial.CastToArray()) { } public TValue Pop() { if (this.Length == 0) return default; var result = base.Repository[this.Length - 1]; base.Repository[--this.Length] = default; return result; } public TValue Front() => this.Length == 0 ? default : base.Repository[this.Length - 1]; public void PushBack(TValue item) { if (this.Length == 0) { this.Length = 1; this.Repository = new[] { item }; return; } this.EnsureSize(); var newArray = new TValue[this.Length]; newArray[0] = item; Array.Copy(this.Repository, 0, newArray, 1, this.Length - 1); this.Repository = newArray; } public TValue PeekBack() => this.Length == 0 ? default : this.Repository[0]; public void ReplaceBack(TValue value) => this.Repository[0] = value; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace com.bitscopic.hilleman.core.domain { [Serializable] public class Message { public String from; public String to; public String subject; public String body; public String uniqueId; public DateTime timestamp; public Message() { } } }
namespace Orc.Automation { using System; public class AutomationEventArgs : EventArgs { public string EventName { get; set; } public object Data { get; set; } } }
// // Copyright (c) XSharp B.V. All Rights Reserved. // Licensed under the Apache License, Version 2.0. // See License.txt in the project root for license information. // using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using LanguageService.CodeAnalysis.XSharp.SyntaxParser; using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal class XSharpClearSequences : XSharpBaseListener { public override void EnterEveryRule([NotNull] ParserRuleContext context) { if (context is XSharpParserRuleContext xpr) { xpr.ClearSequencePoint(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DroneVectors : MonoBehaviour { // Use this for initialization Rigidbody drone_body; LineRenderer velocity_renderer; public float velocity_scale = 0.3f; void Start () { drone_body = gameObject.GetComponent<Rigidbody>(); velocity_renderer = gameObject.GetComponent<LineRenderer>(); } // Update is called once per frame void Update () { } void FixedUpdate() { if(drone_body) { //Draw the direction vector of the drone. Vector3 velocity = drone_body.velocity; Debug.Log("Drone's velocity vector" + velocity); Vector3 vel_point = drone_body.transform.TransformDirection(velocity) * velocity_scale; velocity_renderer.SetPosition(0, gameObject.transform.position); velocity_renderer.SetPosition(1, vel_point); //Draw the velocity vector of the drone. //Draw the thrust vectors of the drone. //Draw the } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Middle.cs" company="Microsoft Corporation"> // Copyright (c) 2008, 2009, 2010 All Rights Reserved, Microsoft Corporation // // This source is subject to the Microsoft Permissive License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // </copyright> // <summary> // Provides safe character positions for the lower middle section of the UTF code tables. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace AntiLdapInjection { using System.Collections; /// <summary> /// Provides safe character positions for the middle section of the UTF code tables. /// </summary> internal static class Middle { /// <summary> /// Determines if the specified flag is set. /// </summary> /// <param name="flags">The value to check.</param> /// <param name="flagToCheck">The flag to check for.</param> /// <returns>true if the flag is set, otherwise false.</returns> internal static bool IsFlagSet(MidCodeCharts flags, MidCodeCharts flagToCheck) { return (flags & flagToCheck) != 0; } /// <summary> /// Provides the safe characters for the Greek Extended code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable GreekExtended() { return CodeChartHelper.GetRange(7936, 8190, (int i) => i == 7958 || i == 7959 || i == 7966 || i == 7967 || i == 8006 || i == 8007 || i == 8014 || i == 8015 || i == 8024 || i == 8026 || i == 8028 || i == 8030 || i == 8062 || i == 8063 || i == 8117 || i == 8133 || i == 8148 || i == 8149 || i == 8156 || i == 8176 || i == 8177 || i == 8181); } /// <summary> /// Provides the safe characters for the General Punctuation code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable GeneralPunctuation() { return CodeChartHelper.GetRange(8192, 8303, (int i) => i >= 8293 && i <= 8297); } /// <summary> /// Provides the safe characters for the Superscripts and subscripts code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable SuperscriptsAndSubscripts() { return CodeChartHelper.GetRange(8304, 8340, (int i) => i == 8306 || i == 8307 || i == 8335); } /// <summary> /// Provides the safe characters for the Currency Symbols code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable CurrencySymbols() { return CodeChartHelper.GetRange(8352, 8376); } /// <summary> /// Provides the safe characters for the Combining Diacritrical Marks for Symbols code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable CombiningDiacriticalMarksForSymbols() { return CodeChartHelper.GetRange(8400, 8432); } /// <summary> /// Provides the safe characters for the Letterlike Symbols code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable LetterlikeSymbols() { return CodeChartHelper.GetRange(8448, 8527); } /// <summary> /// Provides the safe characters for the Number Forms code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable NumberForms() { return CodeChartHelper.GetRange(8528, 8585); } /// <summary> /// Provides the safe characters for the Arrows code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable Arrows() { return CodeChartHelper.GetRange(8592, 8703); } /// <summary> /// Provides the safe characters for the Mathematical Operators code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable MathematicalOperators() { return CodeChartHelper.GetRange(8704, 8959); } /// <summary> /// Provides the safe characters for the Miscellaneous Technical code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable MiscellaneousTechnical() { return CodeChartHelper.GetRange(8960, 9192); } /// <summary> /// Provides the safe characters for the Control Pictures code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable ControlPictures() { return CodeChartHelper.GetRange(9216, 9254); } /// <summary> /// Provides the safe characters for the OCR code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable OpticalCharacterRecognition() { return CodeChartHelper.GetRange(9280, 9290); } /// <summary> /// Provides the safe characters for the Enclosed Alphanumerics code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable EnclosedAlphanumerics() { return CodeChartHelper.GetRange(9312, 9471); } /// <summary> /// Provides the safe characters for the Box Drawing code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable BoxDrawing() { return CodeChartHelper.GetRange(9472, 9599); } /// <summary> /// Provides the safe characters for the Block Elements code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable BlockElements() { return CodeChartHelper.GetRange(9600, 9631); } /// <summary> /// Provides the safe characters for the Geometric Shapes code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable GeometricShapes() { return CodeChartHelper.GetRange(9632, 9727); } /// <summary> /// Provides the safe characters for the Miscellaneous Symbols code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable MiscellaneousSymbols() { return CodeChartHelper.GetRange(9728, 9983, (int i) => i == 9934 || i == 9954 || (i >= 9956 && i <= 9959)); } /// <summary> /// Provides the safe characters for the Dingbats code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable Dingbats() { return CodeChartHelper.GetRange(9985, 10174, (int i) => i == 9989 || i == 9994 || i == 9995 || i == 10024 || i == 10060 || i == 10062 || i == 10067 || i == 10068 || i == 10069 || i == 10079 || i == 10080 || i == 10133 || i == 10134 || i == 10135 || i == 10160); } /// <summary> /// Provides the safe characters for the Miscellaneous Mathematical Symbols A code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable MiscellaneousMathematicalSymbolsA() { return CodeChartHelper.GetRange(10176, 10223, (int i) => i == 10187 || i == 10189 || i == 10190 || i == 10191); } /// <summary> /// Provides the safe characters for the Supplemental Arrows A code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable SupplementalArrowsA() { return CodeChartHelper.GetRange(10224, 10239); } /// <summary> /// Provides the safe characters for the Braille Patterns code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable BraillePatterns() { return CodeChartHelper.GetRange(10240, 10495); } /// <summary> /// Provides the safe characters for the Supplemental Arrows B code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable SupplementalArrowsB() { return CodeChartHelper.GetRange(10496, 10623); } /// <summary> /// Provides the safe characters for the Miscellaneous Mathematical Symbols B code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable MiscellaneousMathematicalSymbolsB() { return CodeChartHelper.GetRange(10624, 10751); } /// <summary> /// Provides the safe characters for the Supplemental Mathematical Operators code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable SupplementalMathematicalOperators() { return CodeChartHelper.GetRange(10752, 11007); } /// <summary> /// Provides the safe characters for the Miscellaneous Symbols and Arrows code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable MiscellaneousSymbolsAndArrows() { return CodeChartHelper.GetRange(11008, 11097, (int i) => i == 11085 || i == 11086 || i == 11087); } /// <summary> /// Provides the safe characters for the Glagolitic code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable Glagolitic() { return CodeChartHelper.GetRange(11264, 11358, (int i) => i == 11311); } /// <summary> /// Provides the safe characters for the Latin Extended C code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable LatinExtendedC() { return CodeChartHelper.GetRange(11360, 11391); } /// <summary> /// Provides the safe characters for the Coptic table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable Coptic() { return CodeChartHelper.GetRange(11392, 11519, (int i) => i >= 11506 && i <= 11512); } /// <summary> /// Provides the safe characters for the Georgian Supplement code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable GeorgianSupplement() { return CodeChartHelper.GetRange(11520, 11557); } /// <summary> /// Provides the safe characters for the Tifinagh code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable Tifinagh() { return CodeChartHelper.GetRange(11568, 11631, (int i) => i >= 11622 && i <= 11630); } /// <summary> /// Provides the safe characters for the Ethiopic Extended code table. /// </summary> /// <returns>The safe characters for the code table.</returns> internal static IEnumerable EthiopicExtended() { return CodeChartHelper.GetRange(11648, 11742, (int i) => (i >= 11671 && i <= 11679) || i == 11687 || i == 11695 || i == 11703 || i == 11711 || i == 11719 || i == 11727 || i == 11735 || i == 11743); } } }
using System.Text.Json.Serialization; namespace Dec.DiscordIPC.Entities { /// <summary> /// Used to represent a user's voice connection status. /// </summary> public class VoiceState { /// <summary>Whether this user is deafened by the server</summary> [JsonPropertyName("deaf")] public bool? Deaf { get; set; } /// <summary>Whether this user is muted by the server</summary> [JsonPropertyName("mute")] public bool? Mute { get; set; } /// <summary>Whether this user is locally deafened</summary> [JsonPropertyName("self_deaf")] public bool? SelfDeaf { get; set; } /// <summary>Whether this user is locally muted</summary> [JsonPropertyName("self_mute")] public bool? SelfMute { get; set; } /// <summary>Whether this user is streaming using "Go Live"</summary> [JsonPropertyName("self_stream")] public bool? SelfStream { get; set; } /// <summary>Whether this user's camera is enabled</summary> [JsonPropertyName("self_video")] public bool? SelfVideo { get; set; } /// <summary>Whether this user is muted by the current user</summary> [JsonPropertyName("suppress")] public bool? Suppress { get; set; } /// <summary>The time at which the user requested to speak</summary> [JsonPropertyName("request_to_speak_timestamp")] public string RequestToSpeakTimestamp { get; set; } } }
using Entities.Enums; using System; namespace Entities.Products { public class PizzaSize : Entity { public int FlvorsQty { get; set; } public string SizeRemark { get; set; } public double AdditionalPrice { get; set; } public Status SizeStatus { get; set; } public DateTime LastChangeDate { get; set; } public int LastChangeUserId { get; set; } public PizzaSize() { } public PizzaSize(int id, string description) { Id = id; Description = description; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Threading.Tasks; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Backup { public interface IBackupService { Task StartBackupAsync(Guid appId, RefToken actor); Task StartRestoreAsync(RefToken actor, Uri url, string? newAppName); Task<IRestoreJob?> GetRestoreAsync(); Task<List<IBackupJob>> GetBackupsAsync(Guid appId); Task<IBackupJob?> GetBackupAsync(Guid appId, Guid backupId); Task DeleteBackupAsync(Guid appId, Guid backupId); } }
using System; using System.IO; namespace CursoCSharp.Api { public static class ExtensaoString { public static string ParseHome(this string path) { string home = (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) ? Environment.GetEnvironmentVariable("HOME") : Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%"); return path.Replace("~", home); } } class PrimeiroArquivo { public static void Executar() { var path = @"~/primeiro_arquivo.txt".ParseHome(); if (!File.Exists(path)) { using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Esse é"); sw.WriteLine("o nosso"); sw.WriteLine("primeiro"); sw.WriteLine("arquivo!"); ; } } using (StreamWriter sw = File.AppendText(path)) { sw.WriteLine(""); sw.WriteLine("É possível"); sw.WriteLine("adicionar"); sw.WriteLine("mais texto"); } } } }
using System.Collections.Generic; using System.Linq; using ScheduledPublish.Extensions; using ScheduledPublish.Models; using Sitecore; using Sitecore.Data.Items; using Sitecore.Diagnostics; using System; using System.Net; using System.Net.Mail; using Sitecore.Security.Accounts; namespace ScheduledPublish.Smtp { /// <summary> /// Handles email notifications /// </summary> public static class MailManager { /// <summary> /// Composes and sends an email according to user-defined preferences. /// </summary> /// <param name="report">Report to append to email body.</param> /// <param name="item">Item to send information on.</param> /// <param name="sendTo">Receiver's email address.</param> public static void SendEmail(string report, Item item, string sendTo) { MailMessage message = ComposeEmail(report, item, sendTo); if (message == null) { Log.Info("Scheduled Publish: No receiver for publishing email. " + DateTime.Now, new object()); return; } if (NotificationEmailSettings.UseWebConfig) { try { MainUtil.SendMail(message); } catch (Exception ex) { Log.Error(string.Format("{0} {1}", "Scheduled Publish: Sending publish email through web.config settings failed.", ex), message); } } else { SendMailMessage(message); } } /// <summary> /// Composes email using content-managed text and placeholders. /// </summary> /// <param name="report">Report to append to email body.</param> /// <param name="item">Item to send information on.</param> /// <param name="username">Receiver.</param> /// <returns>An <see cref="T:System.Net.Mail.MailMessage"/> email message ready to send.</returns> private static MailMessage ComposeEmail(string report, Item item, string username) { NotificationEmail mail = new NotificationEmail(); string to = string.Empty; string bcc = string.Empty; string publishedBy = string.Empty; if (!string.IsNullOrWhiteSpace(username)) { var author = User.FromName(username, false); if (author.Profile != null && !string.IsNullOrWhiteSpace(author.Profile.Email)) { to = author.Profile.Email; publishedBy = !string.IsNullOrWhiteSpace(author.Profile.FullName) ? author.Profile.FullName : author.Name; } } if (!string.IsNullOrWhiteSpace(mail.EmailTo)) { if (string.IsNullOrEmpty(to)) { var index = mail.EmailTo.IndexOf(','); if (index == -1) { to = mail.EmailTo.Trim(); } else { to = mail.EmailTo.Substring(0, index); bcc = mail.EmailTo.Substring(index + 1).Trim(); } } else { bcc = mail.EmailTo; } } if (SectionsEmailSettings.Enabled) { string emailList = GetEmailsForSection(item); if (!string.IsNullOrEmpty(emailList)) { if (!string.IsNullOrWhiteSpace(bcc)) { bcc = string.Format("{0}, {1}", bcc, emailList); } else { bcc = emailList; } } to = string.IsNullOrWhiteSpace(to) && bcc.Length > 0 ? bcc.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[0] : to; } if (bcc.Contains(",")) { var uniqueBccAddresses = bcc .Replace(to, "") .Split(new[] {", "}, StringSplitOptions.RemoveEmptyEntries) .Distinct(); bcc = string.Join(", ", uniqueBccAddresses); } if (string.IsNullOrWhiteSpace(to)) { return null; } string subject = mail.Subject .Replace("[item]", item.DisplayName) .Replace("[path]", item.Paths.FullPath) .Replace("[date]", DateTime.Now.ToShortDateString()) .Replace("[time]", DateTime.Now.ToShortTimeString()) .Replace("[version]", item.Version.ToString()) .Replace("[id]", item.ID.ToString()) .Replace("[publisher]", publishedBy); string body = mail.Body .Replace("[item]", item.DisplayName) .Replace("[path]", item.Paths.FullPath) .Replace("[date]", DateTime.Now.ToShortDateString()) .Replace("[time]", DateTime.Now.ToShortTimeString()) .Replace("[version]", item.Version.ToString()) .Replace("[id]", item.ID.ToString()) .Replace("[publisher]", publishedBy); MailMessage mailMessage = new MailMessage { From = new MailAddress(mail.EmailFrom), To = { to }, Subject = subject, Body = body + Environment.NewLine + report, IsBodyHtml = true, }; if (!string.IsNullOrEmpty(bcc)) { mailMessage.Bcc.Add(bcc); } return mailMessage; } /// <summary> /// Creates an SMTP instance and sends email through it. /// </summary> /// <param name="mailMessage">An <see cref="T:System.Net.Mail.MailMessage"/> email message ready to send.</param> private static void SendMailMessage(MailMessage mailMessage) { SmtpClient client = new SmtpClient(NotificationEmailSettings.MailServer, NotificationEmailSettings.Port); NetworkCredential credentials = new NetworkCredential(NotificationEmailSettings.Username, NotificationEmailSettings.Password); client.Credentials = credentials; try { client.Send(mailMessage); } catch (Exception ex) { Log.Error("Scheduled Publish: Sending email failed: " + ex, mailMessage); } } private static string GetEmailsForSection(Item item) { const string sectionNotFoundMessage = "Item '{0}' is not in any section"; const string roleNotFoundMessage = "Could not find roles to notify for item '{0}'!"; const string usersNotFoundMessage = "Could not find users to notify for item '{0}'!"; ScheduledPublishSection section = item.GetParentSection(); if (section == null) { Log.Warn(string.Format(sectionNotFoundMessage, item.Name), typeof(MailManager)); return string.Empty; } IEnumerable<string> sectionRoleNames = section.SectionRoleNames; IList<Role> sectionRoles = sectionRoleNames.Where(Role.Exists).Select(Role.FromName).ToList(); if (sectionRoles.Count == 0) { Log.Error(string.Format(roleNotFoundMessage, item.Name), typeof(MailManager)); return string.Empty; } IList<User> users = new List<User>(); foreach (var sectionRole in sectionRoles) { users = users.Union(RolesInRolesManager.GetUsersInRole(sectionRole, true)).ToList(); } if (users.Count == 0) { Log.Warn(string.Format(usersNotFoundMessage, item.Name), typeof(MailManager)); return string.Empty; } IEnumerable<string> emailList = users .Where(x => !string.IsNullOrWhiteSpace(x.Profile.Email)) .Select(x => x.Profile.Email); return string.Join(", ", emailList); } } }