content
stringlengths
23
1.05M
using UnityEngine; using UnityEngine.Networking; // by @Bullrich namespace game { public class HostGame : MonoBehaviour { [SerializeField] private uint roomSize = 6; private string roomName; private NetworkManager networkManager; private void Start() { networkManager = NetworkManager.singleton; if (networkManager.matchMaker == null) networkManager.StartMatchMaker(); } public void SetRoomName(string _name) { roomName = _name; } public void CreateRoom() { if (!string.IsNullOrEmpty(roomName)) { Debug.Log(string.Format("Creating Room: {0} with room for {1} players.", roomName, roomSize)); // Create room networkManager.matchMaker.CreateMatch( roomName, roomSize, true, "", "", "", 0, 0, networkManager.OnMatchCreate); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AV_1 { public partial class Form2 : Form { double sl,spf,nf,sf,sb,INSS,txINSS,sind,ps; public Form2() { sl = 0; spf = 0; nf = 0; sb = 0; INSS = 0; txINSS = 0; sind = 0; ps = 0; InitializeComponent(); } private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { } private void radioButton1_CheckedChanged(object sender, EventArgs e) { checkBox1.Enabled = false; checkBox2.Enabled = false; checkBox1.Checked = true; checkBox2.Checked = true; txINSS = 10; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { checkBox1.Enabled = false; checkBox2.Enabled = true; checkBox1.Checked = true; checkBox2.Checked = false; txINSS = 9; } private void radioButton3_CheckedChanged(object sender, EventArgs e) { checkBox1.Enabled = true; checkBox2.Enabled = true; checkBox1.Checked = false; checkBox2.Checked = false; txINSS = 8; } private void radioButton4_CheckedChanged(object sender, EventArgs e) { if (radioButton4.Checked) { checkBox1.Enabled = false; } checkBox2.Enabled = true; checkBox1.Checked = false; checkBox2.Checked = false; txINSS = 0; } private void groupBox1_Enter(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { } private void checkBox2_CheckedChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { if (salarioBruto.Text.Length == 0 || numeroFilhos.Text.Length == 0 || salarioFilho.Text.Length == 0) { MessageBox.Show("Digite os valores.", "Atenção"); return; } // Sal. Fam. spf = double.Parse(salarioFilho.Text); nf = double.Parse(numeroFilhos.Text); sf = spf * nf; textBox1.Text = sf.ToString(); // Si if (checkBox1.Checked) { textBox2.Text = "30"; sind = 30; } else { textBox2.Text = ""; sind = 0; } // Pl if (checkBox2.Checked) { textBox3.Text = "50"; ps = 50; } else { textBox3.Text = ""; ps = 0; } // INSS sb = double.Parse(salarioBruto.Text); INSS = (sb * txINSS) / 100; textBox4.Text = INSS.ToString(); // Salário Líquido = (Salário Bruto - (Sindicato + Plano de Saúde + INSS)) + Salário Família sl = (sb - (sind + ps + INSS)) + sf; textBox5.Text = sl.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace EasyAbp.EzGet.NuGet.Packages { public class NuGetPackageSearchPackageListResult { public long Count { get; } public IReadOnlyList<NuGetPackageSearchResult> Packages { get; } public NuGetPackageSearchPackageListResult(long count, IReadOnlyList<NuGetPackageSearchResult> packages) { Count = count; Packages = packages; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for DataStudents /// </summary> public class DataStudents { public string label { get; set; } public int value { get; set; } }
using System; using System.Collections.Generic; using System.Linq; using TiltBrush; using UnityEngine; public sealed class GlTF_Accessor : GlTF_ReferencedObject { public enum Type { SCALAR, VEC2, VEC3, VEC4 } public enum ComponentType { BYTE = 5120, UNSIGNED_BYTE = 5121, SHORT = 5122, USHORT = 5123, UNSIGNED_INT = 5125, FLOAT = 5126 } static int GetSize(ComponentType t) { switch (t) { case ComponentType.UNSIGNED_BYTE: case ComponentType.BYTE: return 1; case ComponentType.SHORT: case ComponentType.USHORT: return 2; case ComponentType.UNSIGNED_INT: return 4; case ComponentType.FLOAT: return 4; default: throw new InvalidOperationException($"Unknown {t}"); } } // The inverse of GetTypeForNumComponents static int GetNumComponents(Type t) { switch (t) { case Type.SCALAR: return 1; case Type.VEC2: return 2; case Type.VEC3: return 3; case Type.VEC4: return 4; default: throw new InvalidOperationException($"Unknown {t}"); } } // The inverse of GetNumComponents public static Type GetTypeForNumComponents(int size) { switch (size) { case 1: return Type.SCALAR; case 2: return Type.VEC2; case 3: return Type.VEC3; case 4: return Type.VEC4; default: throw new InvalidOperationException($"Cannot convert size {size}"); } } /// Returns an accessor that uses a differenttype. /// This is useful if you want to create (for example) a VEC2 view of a buffer that holds VEC4s. /// If the type is smaller, you get a new accessor that uses the same bufferview /// If the type is the same, you get the same accessor back. /// If the type is bigger, you get an exception public static GlTF_Accessor CloneWithDifferentType( GlTF_Globals G, GlTF_Accessor fromAccessor, Type newType) { if (newType == fromAccessor.type) { return fromAccessor; } var ret = new GlTF_Accessor(G, fromAccessor, newType); G.accessors.Add(ret); return ret; } // Instance API public readonly GlTF_BufferView bufferView;// "bufferView": "bufferView_30", public int byteStride;// ": 12, // GL enum vals ": BYTE (5120), UNSIGNED_BYTE (5121), SHORT (5122), UNSIGNED_SHORT (5123), FLOAT // (5126) public readonly Type type = Type.SCALAR; public readonly ComponentType componentType; private readonly bool m_normalized; // These are only assigned in Populate(), and only the most-ancestral gets populated. // All cloned accessors inherit these from their ancestor. private int? count; private long? byteOffset; // The 2.0 spec has this to say about min/max: // "While these properties are not required for all accessor usages, there are cases when minimum // and maximum must be defined. Refer to other sections of this specification for details." // // "POSITION accessor must have min and max properties defined." // // "Animation Sampler's input accessor must have min and max properties defined." // // There are no other references to other cases where they're required) // Not changing these to nullables because it would be a total pain. private bool m_haveMinMax = false; private Vector4 maxFloat; private Vector4 minFloat; private int minInt; private int maxInt; private GlTF_Accessor m_clonedFrom; private GlTF_Accessor Ancestor { get { if (m_clonedFrom != null) { Debug.Assert(count == null && byteOffset == null, "Clone must inherit from ancestor"); return m_clonedFrom.Ancestor; } return this; } } public int Count => Ancestor.count.Value; public long ByteOffset => Ancestor.byteOffset.Value; public Vector4 MaxFloat => Ancestor.maxFloat; public Vector4 MinFloat => Ancestor.minFloat; public int MinInt => Ancestor.minInt; public int MaxInt => Ancestor.maxInt; // Private to force people to use the better-named CloneWithDifferentType() method. private GlTF_Accessor(GlTF_Globals G, GlTF_Accessor fromAccessor, Type newType) : base(G) { m_clonedFrom = fromAccessor; if (newType >= fromAccessor.type) { throw new ArgumentException("newType must be smaller than fromAccessor.type"); } this.name = $"{fromAccessor.name}_{newType}"; this.bufferView = fromAccessor.bufferView; this.byteStride = fromAccessor.byteStride; this.type = newType; this.componentType = fromAccessor.componentType; // Leave these null; at serialization time, we "inherit" a value from m_clonedFrom // this.count = fromAccessor.count; // this.byteOffset = fromAccessor.byteOffset; // These aren't nullables because the purity isn't worth the pain, but at least poison them this.maxFloat = new Vector4(float.NaN, float.NaN, float.NaN, float.NaN); this.minFloat = new Vector4(float.NaN, float.NaN, float.NaN, float.NaN); this.minInt = 0x0D00B015; this.maxInt = 0x0D00B015; SanityCheckBufferViewStride(); } // Pass: // normalized - // true if integral values are intended to be values in [0, 1] // For convenience, this parameter is ignored if the ComponentType is non-integral. public GlTF_Accessor( GlTF_Globals globals, string n, Type t, ComponentType c, GlTF_BufferView bufferView, bool isNonVertexAttributeAccessor, bool normalized) : base(globals) { name = n; type = t; componentType = c; bool isIntegral = (c != ComponentType.FLOAT); m_normalized = isIntegral && normalized; this.bufferView = bufferView; // I think (but am not sure) that we can infer whether this is a vertex attribute or some // other kind of accessor by what the "target" of the bufferview is. // All bufferviews except for ushortBufferView use kTarget.ARRAY_BUFFER. // The old code used to look at Type (SCALAR implies non-vertex-attribute), but I // think vertexId is a counterexample of a scalar vertex attribute. Debug.Assert(isNonVertexAttributeAccessor == (bufferView.target == GlTF_BufferView.kTarget_ELEMENT_ARRAY_BUFFER)); int packedSize = GetSize(componentType) * GetNumComponents(type); if (isNonVertexAttributeAccessor) { // Gltf2 rule is that bufferView.byteStride may only be set if the accessor is for // a vertex attributes. I think gltf1 is the same way. byteStride = 0; } else if (type == Type.SCALAR && !G.Gltf2) { // Old gltf1 code used to use "packed" for anything of Type.SCALAR. // I'm going to replicate that odd behavior for ease of diffing old vs new .glb1. // As long as stride == packedSize then it's mostly safe to omit the stride, at least in gltf1 Debug.Assert(byteStride == 0 || byteStride == packedSize); byteStride = 0; } else { byteStride = packedSize; } SanityCheckBufferViewStride(); } private void SanityCheckBufferViewStride() { int packedSize = GetSize(componentType) * GetNumComponents(type); // Check that all Accessors that use this bufferview agree on the stride to use. // See docs on m_byteStride and m_packedSize. if (bufferView != null) { Debug.Assert(byteStride == (bufferView.m_byteStride ?? byteStride)); bufferView.m_byteStride = byteStride; if (byteStride == 0) { // Also check for agreement on packed size -- I am not sure how gltf could // tell if a SCALAR+UNSIGNED_SHORT and a SCALAR+UNSIGNED_INT accessor both // tried to use the same bufferview. Debug.Assert(packedSize == (bufferView.m_packedSize ?? packedSize)); bufferView.m_packedSize = packedSize; } } } public static string GetNameFromObject(ObjectName o, string name) { return "accessor_" + name + "_" + o.ToGltf1Name(); } private void InitMinMaxInt() { m_haveMinMax = true; maxInt = int.MinValue; minInt = int.MaxValue; } private void InitMinMaxFloat() { m_haveMinMax = true; float min = float.MinValue; float max = float.MaxValue; maxFloat = new Vector4(min, min, min, min); minFloat = new Vector4(max, max, max, max); } // Raises exception if our type does not match private void RequireType(Type t, ComponentType c) { if (this.type != t || this.componentType != c) { throw new InvalidOperationException($"Cannot write {t} {c} to {type} {componentType}"); } } public void Populate(List<Color32> colorList) { // gltf2 spec says that only position and animation inputs _require_ min/max // so I'm going to skip it. this.byteOffset = this.bufferView.currentOffset; this.count = colorList.Count; if (componentType == ComponentType.FLOAT) { RequireType(Type.VEC4, ComponentType.FLOAT); Color[] colorArray = colorList.Select(c32 => (Color)c32).ToArray(); this.bufferView.FastPopulate(colorArray, colorArray.Length); } else { RequireType(Type.VEC4, ComponentType.UNSIGNED_BYTE); this.bufferView.FastPopulate(colorList); } } public void PopulateUshort(int[] vs) { RequireType(Type.SCALAR, ComponentType.USHORT); byteOffset = bufferView.currentOffset; bufferView.PopulateUshort(vs); count = vs.Length; // TODO: try to remove if (count > 0) { InitMinMaxInt(); for (int i = 0; i < count; ++i) { maxInt = Mathf.Max(vs[i], maxInt); minInt = Mathf.Min(vs[i], minInt); } } } // flipY - // true if value.xy is a UV, and if a UV axis convention swap is needed // glTF defines uv axis conventions to be u right, v down -- origin top-left // Ref: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0, search for "uv" // Unity defines uv axis conventions to be u right, v up -- origin bottom-left // Ref: https://docs.unity3d.com/ScriptReference/Texture2D.GetPixelBilinear.html // calculateMinMax - // gltf2 spec says that only position and animation inputs _require_ min/max. // It's safe to pass false if it's neither of those things. // It's always safe to pass true, but it wastes CPU public void Populate(List<Vector2> v2s, bool flipY, bool calculateMinMax) { if (flipY) { v2s = v2s.Select(v => new Vector2(v.x, 1f - v.y)).ToList(); } RequireType(Type.VEC2, ComponentType.FLOAT); byteOffset = bufferView.currentOffset; count = v2s.Count; bufferView.FastPopulate(v2s); if (calculateMinMax && count > 0) { InitMinMaxFloat(); for (int i = 0; i < v2s.Count; i++) { maxFloat = Vector2.Max(v2s[i], maxFloat); minFloat = Vector2.Min(v2s[i], minFloat); } } } public void Populate(List<Vector3> v3s, bool flipY, bool calculateMinMax) { if (flipY) { v3s = v3s.Select(v => new Vector3(v.x, 1f - v.y, v.z)).ToList(); } RequireType(Type.VEC3, ComponentType.FLOAT); byteOffset = bufferView.currentOffset; count = v3s.Count; bufferView.FastPopulate(v3s); if (calculateMinMax && count > 0) { InitMinMaxFloat(); for (int i = 0; i < v3s.Count; i++) { maxFloat = Vector3.Max(v3s[i], maxFloat); minFloat = Vector3.Min(v3s[i], minFloat); } } } public void Populate(List<Vector4> v4s, bool flipY, bool calculateMinMax) { if (flipY) { v4s = v4s.Select(v => new Vector4(v.x, 1f - v.y, v.z, v.w)).ToList(); } RequireType(Type.VEC4, ComponentType.FLOAT); byteOffset = bufferView.currentOffset; count = v4s.Count; bufferView.FastPopulate(v4s); if (calculateMinMax && count > 0) { InitMinMaxFloat(); for (int i = 0; i < v4s.Count; i++) { maxFloat = Vector4.Max(v4s[i], maxFloat); minFloat = Vector4.Min(v4s[i], minFloat); } } } // Writes either the integral or floating-point value(s), based on type and componentType private void WriteNamedTypedValue(string name, int i, Vector4 fs) { string val = null; if (componentType == ComponentType.FLOAT) { switch (type) { case Type.SCALAR: val = $"{fs.x:G9}"; break; case Type.VEC2: val = $"{fs.x:G9}, {fs.y:G9}"; break; case Type.VEC3: val = $"{fs.x:G9}, {fs.y:G9}, {fs.z:G9}"; break; case Type.VEC4: val = $"{fs.x:G9}, {fs.y:G9}, {fs.z:G9}, {fs.w:G9}"; break; } } else if (componentType == ComponentType.USHORT) { if (type == Type.SCALAR) { val = i.ToString(); } } if (val == null) { throw new InvalidOperationException($"Unhandled: {type} {componentType}"); } jsonWriter.Write($"\"{name}\": [ {val} ]"); } public override IEnumerable<GlTF_ReferencedObject> IterReferences() { yield return G.Lookup(bufferView); } public override void WriteTopLevel() { BeginGltfObject(); G.CNI.WriteNamedReference("bufferView", bufferView); G.CNI.WriteNamedInt("byteOffset", ByteOffset); if (!G.Gltf2) { G.CNI.WriteNamedInt("byteStride", byteStride); } G.CNI.WriteNamedInt("componentType", (int)componentType); if (G.Gltf2 && m_normalized) { G.CNI.WriteNamedBool("normalized", m_normalized); } var inheritedCount = Count; G.CNI.WriteNamedInt("count", inheritedCount); // min and max are not well-defined if count == 0 if (m_haveMinMax && inheritedCount > 0) { G.CommaNL(); G.Indent(); WriteNamedTypedValue("max", MaxInt, MaxFloat); G.CommaNL(); G.Indent(); WriteNamedTypedValue("min", MinInt, MinFloat); } G.CNI.WriteNamedString("type", type.ToString()); EndGltfObject(); } }
using UnityEngine; namespace spaar.ModLoader.UI { // This class was taken from Vapid's ModLoader with permissions. // All credit goes to VapidLinus. public class Settings { public RectOffset DefaultMargin { get; set; } public RectOffset DefaultPadding { get; set; } public RectOffset LowMargin { get; set; } public RectOffset LowPadding { get; set; } public float InspectorPanelWidth { get; set; } public float HierarchyPanelWidth { get; set; } public Vector2 ConsoleSize { get; set; } public float LogEntrySize { get; set; } public float TreeEntryIndention { get; set; } internal Settings() { DefaultMargin = new RectOffset(8, 8, 8, 8); DefaultPadding = new RectOffset(8, 8, 6, 6); LowMargin = new RectOffset(4, 4, 4, 4); LowPadding = new RectOffset(4, 4, 2, 2); HierarchyPanelWidth = 350; InspectorPanelWidth = 450; ConsoleSize = new Vector2(550, 600); LogEntrySize = 16; TreeEntryIndention = 20; } } }
using System; using System.Text; using SharpMessaging.Connection; namespace SharpMessaging.Frames { internal class ErrorFrame : IFrame { private readonly byte[] _readBuffer = new byte[2000]; private FrameFlags _flags; private int _messageLength; private int _readOffset; private ArraySegment<byte> _readPayloadBuffer; private int _receiveBytesLeft; private ErrorFrameState _state; private int _stateLength; public ErrorFrame(string errorMessage) { ErrorMessage = errorMessage; } public ErrorFrame() { } public string ErrorMessage { get; private set; } public void ResetWrite(WriterContext context) { } public bool Write(WriterContext context) { var buf = new byte[65535]; var contentLength = Encoding.UTF8.GetByteCount(ErrorMessage); var offset = 2; if (contentLength <= 512) { buf[0] = (byte)FrameFlags.ErrorFrame; buf[1] = (byte)contentLength; } else { buf[0] = (byte)(FrameFlags.ErrorFrame | FrameFlags.LargeFrame); var lenBuf = BitConverter.GetBytes(contentLength); if (BitConverter.IsLittleEndian) Array.Reverse(lenBuf); buf[1] = lenBuf[0]; buf[2] = lenBuf[1]; buf[3] = lenBuf[2]; buf[4] = lenBuf[3]; offset = 5; } Encoding.UTF8.GetBytes(ErrorMessage, 0, ErrorMessage.Length, buf, offset); context.Enqueue(buf, 0, offset + contentLength); return true; } public void ResetRead() { _receiveBytesLeft = -1; _stateLength = -1; _state = ErrorFrameState.Flags; _readPayloadBuffer = WriterContext.EmptySegment; _readOffset = 0; } public bool Read(byte[] buffer, ref int offset, ref int bytesToProcess) { var numberOfBytesTransferredFromStart = bytesToProcess; var allCompleted = false; while (bytesToProcess > 0 && !allCompleted) { bool isBufferCopyCompleted; switch (_state) { case ErrorFrameState.Flags: if (buffer[offset] == 32) { throw new BackTrackException("", offset); } _flags = (FrameFlags)buffer[offset]; _state = ErrorFrameState.Length; ++offset; --bytesToProcess; _receiveBytesLeft = 4; break; case ErrorFrameState.Length: if ((_flags & FrameFlags.LargeFrame) == 0) { _messageLength = buffer[offset]; ++offset; --bytesToProcess; } else { isBufferCopyCompleted = CopyToReadBuffer(buffer, ref offset, ref bytesToProcess); if (isBufferCopyCompleted) { if (BitConverter.IsLittleEndian) Array.Reverse(_readBuffer, 0, 4); _messageLength = BitConverter.ToInt32(_readBuffer, 0); } } _receiveBytesLeft = _messageLength; _state = ErrorFrameState.Message; break; case ErrorFrameState.Message: isBufferCopyCompleted = CopyToReadBuffer(buffer, ref offset, ref bytesToProcess); if (isBufferCopyCompleted) { ErrorMessage = Encoding.UTF8.GetString(_readBuffer, 0, _messageLength); allCompleted = true; } break; } } if (offset < 0) throw new InvalidOperationException(); return allCompleted; } public void WriteCompleted(WriterContext context) { } private bool CopyToReadBuffer(byte[] buffer, ref int offset, ref int bytesTransferred) { var bytesToCopy = Math.Min(_receiveBytesLeft, bytesTransferred); if (offset + bytesToCopy > buffer.Length) throw new ArgumentOutOfRangeException("offset", offset, "Too large: " + offset + "+" + bytesToCopy + "<" + buffer.Length); if (_readOffset + bytesToCopy > _readBuffer.Length) throw new ArgumentOutOfRangeException("offset", offset, "Too large for state buffer: " + _readOffset + "+" + bytesToCopy + "<" + _readBuffer.Length); Buffer.BlockCopy(buffer, offset, _readBuffer, _readOffset, bytesToCopy); _receiveBytesLeft -= bytesToCopy; bytesTransferred -= bytesToCopy; offset += bytesToCopy; if (_receiveBytesLeft == 0) { _readOffset = 0; return true; } _readOffset += bytesToCopy; return false; } private enum ErrorFrameState { Flags, Length, Message } } }
using UnityEngine; using System.Collections.Generic; // By @JavierBullrich namespace SimpleMainMenu { public class SimpleMenuManager : MonoBehaviour { [Header("Title Text")] public string GameName; public string CopyrightText; public Color textColor = Color.white; public Font textFont; [Header("Menu Controlls")] public string InputName = "Fire1"; public string VerticalAxisName = "Vertical", ReturnKey = "Fire3"; public static string inputKey = "Fire1", vAxis = "Vertical", returnKey = "Fire3"; [Header("Menu interaction")] public Sprite ArrowSprite; public Color SelectedColor = Color.yellow; [Header("Buttons options")] public bool canBeClicked = true; [SerializeField] public ButtonsSettings[] buttons; MenuController mController; IntroScreen intro; List<InformationText> infoTxt = new List<InformationText>(); public void Awake() { GetControllers(); foreach(ButtonsSettings b in buttons) { b.selectedColor = SelectedColor; b.selectedSprite = ArrowSprite; b.canClick = canBeClicked; b.textFont = textFont; } mController.PopulateMenu(buttons); inputKey = InputName; vAxis = VerticalAxisName; IntroStatus(false); } public void IntroStatus(bool activeIntro) { mController.transform.gameObject.SetActive(!activeIntro); foreach(InformationText txt in infoTxt) { txt.transform.gameObject.SetActive(!activeIntro); } intro.transform.gameObject.SetActive(activeIntro); } void GetControllers() { foreach(Transform t in transform) { if (t.GetComponent<MenuController>()) mController = t.GetComponent<MenuController>(); else if (t.GetComponent<InformationText>()) { infoTxt.Add(t.GetComponent<InformationText>()); SetTitleText(t.GetComponent<InformationText>()); } else if (t.GetComponent<IntroScreen>()) { intro = t.GetComponent<IntroScreen>(); intro.SetUp(this); } } } private void SetTitleText(InformationText infoText) { string infoString = ""; switch (infoText.InfoType) { case InformationText.typeOfText.Title: infoString = GameName; break; case InformationText.typeOfText.Copyright: infoString = CopyrightText; break; case InformationText.typeOfText.Version: infoString = VersionText(); break; default: break; } infoText.SetText(infoString, textColor, textFont); } string VersionText() { string version = "Version " + Application.version; return version; } } }
using System; using System.Web.Mvc; // ReSharper disable CheckNamespace namespace AMV.CQRS { /// <summary> /// Date-Time model binder that checks if dates are out of range of SQL Server /// </summary> public class SqlDateTimeModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var result = base.BindModel(controllerContext, bindingContext); var dateTime = result as DateTime?; if (dateTime != null) { if (dateTime < System.Data.SqlTypes.SqlDateTime.MinValue.Value) { var message = String.Format("{0} must be not less than 01/01/1753", bindingContext.ModelName); bindingContext.ModelState.AddModelError(bindingContext.ModelName, message); } if (dateTime > System.Data.SqlTypes.SqlDateTime.MaxValue.Value) { var message = String.Format("{0} must be not more than 31/12/9999", bindingContext.ModelName); bindingContext.ModelState.AddModelError(bindingContext.ModelName, message); } } return dateTime; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Finance { public interface ITraderBalance { string TraderId { get; } string Currency { get; } double Amount { get; } } public interface IBalanceRepository { Task<IEnumerable<ITraderBalance>> GetAsync(string traderId); Task ChangeBalanceAsync(string traderId, string currency, double delta); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using TwentyThreeNet; namespace DemoApplication { class Program { static void Main(string[] args) { string token = String.Empty; TwentyThree twentyThree = new TwentyThree("DEMOKEY", "DEMOSHARED"); if (String.IsNullOrWhiteSpace(token)) { // Getting the frob and calculate the URL string frob = twentyThree.AuthGetFrob(); string url = twentyThree.AuthCalcUrl(frob, AuthLevel.Delete); // Pointing the user to the URL with its standard browser Process p = Process.Start(url); p.WaitForExit(); // Get the authentication token to access 23, remember this for all other methods Auth auth = twentyThree.AuthGetToken(frob); token = auth.Token; } twentyThree.AuthToken = token; ContactCollection photos = twentyThree.ContactsGetList(); } } }
using HttpReports.Core.Interface; using System.Threading.Tasks; namespace HttpReports { public interface IReportsTransport { Task Write(IRequestInfo requestInfo, IRequestDetail requestDetail); Task WritePerformanceAsync(IPerformance performance); } }
using System.Collections.Generic; namespace AutoBuyer.Logic { public class BuyerPortfolio : IBuyerPortfolio { private readonly List<IPortfolioListener> _listeners = new List<IPortfolioListener>(); private readonly List<Buyer> _buyers = new List<Buyer>(); public void AddBuyer(Buyer buyer) { _buyers.Add(buyer); foreach (IPortfolioListener listener in _listeners) { listener.BuyerAdded(buyer); } } public void AddPortfolioListener(IPortfolioListener listener) { _listeners.Add(listener); } } }
using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using Steropes.UI.Annotations; namespace Steropes.UI.Bindings { internal abstract class DerivedBinding<T> : IReadOnlyObservableValue<T> { T value; protected bool AlreadyHandlingEvent { get; set; } protected DerivedBinding() { } protected DerivedBinding(T value) { this.value = value; } public abstract void Dispose(); public abstract IReadOnlyList<IBindingSubscription> Sources { get; } public event PropertyChangedEventHandler PropertyChanged; object IReadOnlyObservableValue.Value => Value; public T Value { get { return value; } protected set { if (Equals(value, this.value)) { return; } this.value = value; OnPropertyChanged(); } } protected void OnSourcePropertyChange(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(IReadOnlyObservableValue.Value)) { Value = ComputeValue(); } } protected abstract T ComputeValue(); [NotifyPropertyChangedInvocator] void OnPropertyChanged([CallerMemberName] string propertyName = null) { if (!AlreadyHandlingEvent) { try { AlreadyHandlingEvent = true; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } finally { AlreadyHandlingEvent = false; } } } } }
using VaultLib.Core.Types; namespace VaultLib.Support.World.VLT.GameCore { [VLTTypeInfo("GameCore::RewardMode")] public enum RewardMode { kRewardMode_Singleplayer = 1, kRewardMode_Multiplayer = 2, kRewardMode_PrivateMatch = 3, } }
using System; namespace Paydock_dotnet_sdk.Models { public class ResponseException : Exception { public ErrorResponse ErrorResponse { get; private set; } public ResponseException(ErrorResponse errorResponse, string error, Exception innerException = null) : base(error, innerException) { this.ErrorResponse = errorResponse; } } }
//------------------------------------------------------------------------------ // <copyright file="ScriptReference.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI { using System; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Web; using System.Web.Handlers; using System.Web.Resources; using System.Web.Util; using Debug = System.Diagnostics.Debug; [ DefaultProperty("Path"), ] public class ScriptReference : ScriptReferenceBase { // Maps Tuple<string, Assembly>(resource name, assembly) to string (partial script path) private static readonly Hashtable _scriptPathCache = Hashtable.Synchronized(new Hashtable()); private string _assembly; private bool _ignoreScriptPath; private string _name; private ScriptEffectiveInfo _scriptInfo; public ScriptReference() : base() { } public ScriptReference(string name, string assembly) : this() { Name = name; Assembly = assembly; } public ScriptReference(string path) : this() { Path = path; } internal ScriptReference(string name, IClientUrlResolver clientUrlResolver, Control containingControl) : this() { Debug.Assert(!String.IsNullOrEmpty(name), "The script's name must be specified."); Debug.Assert(clientUrlResolver != null && clientUrlResolver is ScriptManager, "The clientUrlResolver must be the ScriptManager."); Name = name; ClientUrlResolver = clientUrlResolver; IsStaticReference = true; ContainingControl = containingControl; } internal bool IsDirectRegistration { // set to true internally to disable checking for adding .debug // used when registering a script directly through SM.RegisterClientScriptResource get; set; } [ Category("Behavior"), DefaultValue(""), ResourceDescription("ScriptReference_Assembly") ] public string Assembly { get { return (_assembly == null) ? String.Empty : _assembly; } set { _assembly = value; _scriptInfo = null; } } internal Assembly EffectiveAssembly { get { return ScriptInfo.Assembly; } } internal string EffectivePath { get { return String.IsNullOrEmpty(Path) ? ScriptInfo.Path : Path; } } internal string EffectiveResourceName { get { return ScriptInfo.ResourceName; } } internal ScriptMode EffectiveScriptMode { get { if (ScriptMode == ScriptMode.Auto) { // - When a mapping.DebugPath exists, ScriptMode.Auto is equivilent to ScriptMode.Inherit, // since a debug path exists, even though it may not be an assembly based script. // - An explicitly set Path on the ScriptReference effectively ignores a DebugPath. // - When only Path is specified, ScriptMode.Auto is equivalent to ScriptMode.Release. // - When only Name is specified, ScriptMode.Auto is equivalent to ScriptMode.Inherit. // - When Name and Path are both specified, the Path is used instead of the Name, but // ScriptMode.Auto is still equivalent to ScriptMode.Inherit, since the assumption // is that if the Assembly contains both release and debug scripts, the Path should // contain both as well. return ((String.IsNullOrEmpty(EffectiveResourceName) && (!String.IsNullOrEmpty(Path) || String.IsNullOrEmpty(ScriptInfo.DebugPath))) ? ScriptMode.Release : ScriptMode.Inherit); } else { return ScriptMode; } } } [ Category("Behavior"), DefaultValue(false), ResourceDescription("ScriptReference_IgnoreScriptPath"), Obsolete("This property is obsolete. Instead of using ScriptManager.ScriptPath, set the Path property on each individual ScriptReference.") ] public bool IgnoreScriptPath { get { return _ignoreScriptPath; } set { _ignoreScriptPath = value; } } [ Category("Behavior"), DefaultValue(""), ResourceDescription("ScriptReference_Name") ] public string Name { get { return (_name == null) ? String.Empty : _name; } set { _name = value; _scriptInfo = null; } } internal ScriptEffectiveInfo ScriptInfo { get { if (_scriptInfo == null) { _scriptInfo = new ScriptEffectiveInfo(this); } return _scriptInfo; } } private string AddCultureName(ScriptManager scriptManager, string resourceName) { Debug.Assert(!String.IsNullOrEmpty(resourceName)); CultureInfo culture = (scriptManager.EnableScriptLocalization ? DetermineCulture(scriptManager) : CultureInfo.InvariantCulture); if (!culture.Equals(CultureInfo.InvariantCulture)) { return AddCultureName(culture, resourceName); } else { return resourceName; } } private static string AddCultureName(CultureInfo culture, string resourceName) { if (resourceName.EndsWith(".js", StringComparison.OrdinalIgnoreCase)) { resourceName = resourceName.Substring(0, resourceName.Length - 2) + culture.Name + ".js"; } return resourceName; } internal bool DetermineResourceNameAndAssembly(ScriptManager scriptManager, bool isDebuggingEnabled, ref string resourceName, ref Assembly assembly) { // If the assembly is the AjaxFrameworkAssembly, the resource may come from that assembly // or from the fallback assembly (SWE). if (assembly == scriptManager.AjaxFrameworkAssembly) { assembly = ApplyFallbackResource(assembly, resourceName); } // ShouldUseDebugScript throws exception if the resource name does not exist in the assembly bool isDebug = ShouldUseDebugScript(resourceName, assembly, isDebuggingEnabled, scriptManager.AjaxFrameworkAssembly); if (isDebug) { resourceName = GetDebugName(resourceName); } // returning true means the debug version is selected return isDebug; } internal CultureInfo DetermineCulture(ScriptManager scriptManager) { if ((ResourceUICultures == null) || (ResourceUICultures.Length == 0)) { // In this case we want to determine available cultures from assembly info if available if (!String.IsNullOrEmpty(EffectiveResourceName)) { return ScriptResourceHandler .DetermineNearestAvailableCulture(GetAssembly(scriptManager), EffectiveResourceName, CultureInfo.CurrentUICulture); } return CultureInfo.InvariantCulture; } CultureInfo currentCulture = CultureInfo.CurrentUICulture; while (!currentCulture.Equals(CultureInfo.InvariantCulture)) { string cultureName = currentCulture.ToString(); foreach (string uiCulture in ResourceUICultures) { if (String.Equals(cultureName, uiCulture.Trim(), StringComparison.OrdinalIgnoreCase)) { return currentCulture; } } currentCulture = currentCulture.Parent; } return currentCulture; } internal Assembly GetAssembly() { return String.IsNullOrEmpty(Assembly) ? null : AssemblyCache.Load(Assembly); } internal Assembly GetAssembly(ScriptManager scriptManager) { // normalizes the effective assembly by redirecting it to the given scriptmanager's // ajax framework assembly when it is set to SWE. // EffectiveAssembly can't do this since ScriptReference does not have access by itself // to the script manager. Debug.Assert(scriptManager != null); Assembly assembly = EffectiveAssembly; if (assembly == null) { return scriptManager.AjaxFrameworkAssembly; } else { return ((assembly == AssemblyCache.SystemWebExtensions) ? scriptManager.AjaxFrameworkAssembly : assembly); } } // Release: foo.js // Debug: foo.debug.js private static string GetDebugName(string releaseName) { // Since System.Web.Handlers.AssemblyResourceLoader treats the resource name as case-sensitive, // we must do the same when verifying the extension. // Ignore trailing whitespace. For example, "MicrosoftAjax.js " is valid (at least from // a debug/release naming perspective). if (!releaseName.EndsWith(".js", StringComparison.Ordinal)) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentUICulture, AtlasWeb.ScriptReference_InvalidReleaseScriptName, releaseName)); } return ReplaceExtension(releaseName); } internal string GetPath(ScriptManager scriptManager, string releasePath, string predeterminedDebugPath, bool isDebuggingEnabled) { // convert the release path to a debug path if: // isDebuggingEnabled && not resource based // isDebuggingEnabled && resource based && debug resource exists // ShouldUseDebugScript is called even when isDebuggingEnabled=false as it verfies // the existence of the resource. // applies the culture name to the path if appropriate string path; if (!String.IsNullOrEmpty(EffectiveResourceName)) { Assembly assembly = GetAssembly(scriptManager); string resourceName = EffectiveResourceName; isDebuggingEnabled = DetermineResourceNameAndAssembly(scriptManager, isDebuggingEnabled, ref resourceName, ref assembly); } if (isDebuggingEnabled) { // Just use predeterminedDebugPath if it is provided. This may be because // a script mapping has DebugPath set. If it is empty or null, then '.debug' is added // to the .js extension of the release path. path = String.IsNullOrEmpty(predeterminedDebugPath) ? GetDebugPath(releasePath) : predeterminedDebugPath; } else { path = releasePath; } return AddCultureName(scriptManager, path); } internal Assembly ApplyFallbackResource(Assembly assembly, string releaseName) { // fall back to SWE if the assembly does not contain the requested resource if ((assembly != AssemblyCache.SystemWebExtensions) && !WebResourceUtil.AssemblyContainsWebResource(assembly, releaseName)) { assembly = AssemblyCache.SystemWebExtensions; } return assembly; } // Format: <ScriptPath>/<AssemblyName>/<AssemblyVersion>/<ResourceName> // This function does not canonicalize the path in any way (i.e. remove duplicate slashes). // You must call ResolveClientUrl() on this path before rendering to the page. internal static string GetScriptPath( string resourceName, Assembly assembly, CultureInfo culture, string scriptPath) { return scriptPath + "/" + GetScriptPathCached(resourceName, assembly, culture); } // Cache partial script path, since Version.ToString() and HttpUtility.UrlEncode() are expensive. // Increases requests/second by 50% in ScriptManagerScriptPath.aspx test. private static string GetScriptPathCached(string resourceName, Assembly assembly, CultureInfo culture) { Tuple<string, Assembly, CultureInfo> key = Tuple.Create(resourceName, assembly, culture); string scriptPath = (string)_scriptPathCache[key]; if (scriptPath == null) { // Need to use "new AssemblyName(assembly.FullName)" instead of "assembly.GetName()", // since Assembly.GetName() requires FileIOPermission to the path of the assembly. // In partial trust, we may not have this permission. AssemblyName assemblyName = new AssemblyName(assembly.FullName); string name = assemblyName.Name; string version = assemblyName.Version.ToString(); string fileVersion = AssemblyUtil.GetAssemblyFileVersion(assembly); if (!culture.Equals(CultureInfo.InvariantCulture)) { resourceName = AddCultureName(culture, resourceName); } // Assembly name, fileVersion, and resource name may contain invalid URL characters (like '#' or '/'), // so they must be url-encoded. scriptPath = String.Join("/", new string[] { HttpUtility.UrlEncode(name), version, HttpUtility.UrlEncode(fileVersion), HttpUtility.UrlEncode(resourceName) }); _scriptPathCache[key] = scriptPath; } return scriptPath; } [SuppressMessage("Microsoft.Design", "CA1055", Justification = "Consistent with other URL properties in ASP.NET.")] protected internal override string GetUrl(ScriptManager scriptManager, bool zip) { bool hasName = !String.IsNullOrEmpty(Name); bool hasAssembly = !String.IsNullOrEmpty(Assembly); if (!hasName && String.IsNullOrEmpty(Path)) { throw new InvalidOperationException(AtlasWeb.ScriptReference_NameAndPathCannotBeEmpty); } if (hasAssembly && !hasName) { throw new InvalidOperationException(AtlasWeb.ScriptReference_AssemblyRequiresName); } return GetUrlInternal(scriptManager, zip); } internal string GetUrlInternal(ScriptManager scriptManager, bool zip) { bool enableCdn = scriptManager != null && scriptManager.EnableCdn; return GetUrlInternal(scriptManager, zip, useCdnPath: enableCdn); } internal string GetUrlInternal(ScriptManager scriptManager, bool zip, bool useCdnPath) { if (!String.IsNullOrEmpty(EffectiveResourceName) && !IsAjaxFrameworkScript(scriptManager) && AssemblyCache.IsAjaxFrameworkAssembly(GetAssembly(scriptManager))) { // it isnt an AjaxFrameworkScript but it might be from an assembly that is meant to // be an ajax script assembly, in which case we should throw an error. throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture, AtlasWeb.ScriptReference_ResourceRequiresAjaxAssembly, EffectiveResourceName, GetAssembly(scriptManager))); } if (!String.IsNullOrEmpty(Path)) { // if an explicit path is set on the SR (not on a mapping) it always // takes precedence, even when EnableCdn=true. // Also, even if a script mapping has a DebugPath, the explicitly set path // overrides all -- so path.debug.js is used instead of the mapping's DebugPath, // hence the null 3rd parameter. return GetUrlFromPath(scriptManager, Path, null); } else if (!String.IsNullOrEmpty(ScriptInfo.Path)) { // when only the mapping has a path, CDN takes first priority if (useCdnPath) { // first determine the actual resource name and assembly to be used // This is so we can (1) apply fallback logic, where ajax fx scripts can come from the // current ajax assembly or from SWE, whichever is first, and (2) the .debug resource // name is applied if appropriate. string resourceName = EffectiveResourceName; Assembly assembly = null; bool hasDebugResource = false; if (!String.IsNullOrEmpty(resourceName)) { assembly = GetAssembly(scriptManager); hasDebugResource = DetermineResourceNameAndAssembly(scriptManager, IsDebuggingEnabled(scriptManager), ref resourceName, ref assembly); } string cdnPath = GetUrlForCdn(scriptManager, resourceName, assembly, hasDebugResource); if (!String.IsNullOrEmpty(cdnPath)) { return cdnPath; } } // the mapping's DebugPath applies if it exists return GetUrlFromPath(scriptManager, ScriptInfo.Path, ScriptInfo.DebugPath); } Debug.Assert(!String.IsNullOrEmpty(EffectiveResourceName)); return GetUrlFromName(scriptManager, scriptManager.Control, zip, useCdnPath); } private string GetUrlForCdn(ScriptManager scriptManager, string resourceName, Assembly assembly, bool hasDebugResource) { // if EnableCdn, then url always comes from mapping.Cdn[Debug]Path or WRA.CdnPath, if available. // first see if the script description mapping has a cdn path defined bool isDebuggingEnabled = IsDebuggingEnabled(scriptManager); bool isAssemblyResource = !String.IsNullOrEmpty(resourceName); bool secureConnection = scriptManager.IsSecureConnection; isDebuggingEnabled = isDebuggingEnabled && (hasDebugResource || !isAssemblyResource); string cdnPath = isDebuggingEnabled ? (secureConnection ? ScriptInfo.CdnDebugPathSecureConnection : ScriptInfo.CdnDebugPath) : (secureConnection ? ScriptInfo.CdnPathSecureConnection : ScriptInfo.CdnPath); // then see if the WebResourceAttribute for the resource has one // EXCEPT when the ScriptInfo has a cdnpath but it wasn't selected due to this being a secure connection // and it does not support secure connections. Avoid having the HTTP cdn path come from the mapping and the // HTTPS path come from the WRA. if (isAssemblyResource && String.IsNullOrEmpty(cdnPath) && String.IsNullOrEmpty(isDebuggingEnabled ? ScriptInfo.CdnDebugPath : ScriptInfo.CdnPath)) { ScriptResourceInfo scriptResourceInfo = ScriptResourceInfo.GetInstance(assembly, resourceName); if (scriptResourceInfo != null) { cdnPath = secureConnection ? scriptResourceInfo.CdnPathSecureConnection : scriptResourceInfo.CdnPath; } } return String.IsNullOrEmpty(cdnPath) ? null : ClientUrlResolver.ResolveClientUrl(AddCultureName(scriptManager, cdnPath)); } private string GetUrlFromName(ScriptManager scriptManager, IControl scriptManagerControl, bool zip, bool useCdnPath) { string resourceName = EffectiveResourceName; Assembly assembly = GetAssembly(scriptManager); bool hasDebugResource = DetermineResourceNameAndAssembly(scriptManager, IsDebuggingEnabled(scriptManager), ref resourceName, ref assembly); if (useCdnPath) { string cdnPath = GetUrlForCdn(scriptManager, resourceName, assembly, hasDebugResource); if (!String.IsNullOrEmpty(cdnPath)) { return cdnPath; } } CultureInfo culture = (scriptManager.EnableScriptLocalization ? DetermineCulture(scriptManager) : CultureInfo.InvariantCulture); #pragma warning disable 618 // ScriptPath is obsolete but still functional if (IgnoreScriptPath || String.IsNullOrEmpty(scriptManager.ScriptPath)) { return ScriptResourceHandler.GetScriptResourceUrl(assembly, resourceName, culture, zip); } else { string path = GetScriptPath(resourceName, assembly, culture, scriptManager.ScriptPath); if (IsBundleReference) { return scriptManager.BundleReflectionHelper.GetBundleUrl(path); } // Always want to resolve ScriptPath urls against the ScriptManager itself, // regardless of whether the ScriptReference was declared on the ScriptManager // or a ScriptManagerProxy. return scriptManagerControl.ResolveClientUrl(path); } #pragma warning restore 618 } private string GetUrlFromPath(ScriptManager scriptManager, string releasePath, string predeterminedDebugPath) { string path = GetPath(scriptManager, releasePath, predeterminedDebugPath, IsDebuggingEnabled(scriptManager)); if (IsBundleReference) { return scriptManager.BundleReflectionHelper.GetBundleUrl(path); } return ClientUrlResolver.ResolveClientUrl(path); } private bool IsDebuggingEnabled(ScriptManager scriptManager) { // Deployment mode retail overrides all values of ScriptReference.ScriptMode. if (IsDirectRegistration || scriptManager.DeploymentSectionRetail) { return false; } switch (EffectiveScriptMode) { case ScriptMode.Inherit: return scriptManager.IsDebuggingEnabled; case ScriptMode.Debug: return true; case ScriptMode.Release: return false; default: Debug.Fail("Invalid value for ScriptReference.EffectiveScriptMode"); return false; } } protected internal override bool IsAjaxFrameworkScript(ScriptManager scriptManager) { return (GetAssembly(scriptManager) == scriptManager.AjaxFrameworkAssembly); } [Obsolete("This method is obsolete. Use IsAjaxFrameworkScript(ScriptManager) instead.")] protected internal override bool IsFromSystemWebExtensions() { return (EffectiveAssembly == AssemblyCache.SystemWebExtensions); } internal bool IsFromSystemWeb() { return (EffectiveAssembly == AssemblyCache.SystemWeb); } internal bool ShouldUseDebugScript(string releaseName, Assembly assembly, bool isDebuggingEnabled, Assembly currentAjaxAssembly) { bool useDebugScript; string debugName = null; if (isDebuggingEnabled) { debugName = GetDebugName(releaseName); // If an assembly contains a release script but not a corresponding debug script, and we // need to register the debug script, we normally throw an exception. However, we automatically // use the release script if ScriptReference.ScriptMode is Auto. This improves the developer // experience when ScriptMode is Auto, yet still gives the developer full control with the // other ScriptModes. if (ScriptMode == ScriptMode.Auto && !WebResourceUtil.AssemblyContainsWebResource(assembly, debugName)) { useDebugScript = false; } else { useDebugScript = true; } } else { useDebugScript = false; } // Verify that assembly contains required web resources. Always check for release // script before debug script. if (!IsDirectRegistration) { // Don't check if direct registration, because calls to ScriptManager.RegisterClientScriptResource // with resources that do not exist does not throw an exception until the resource is served. // This was the existing behavior and matches the behavior with ClientScriptManager.GetWebResourceUrl. WebResourceUtil.VerifyAssemblyContainsReleaseWebResource(assembly, releaseName, currentAjaxAssembly); if (useDebugScript) { Debug.Assert(debugName != null); WebResourceUtil.VerifyAssemblyContainsDebugWebResource(assembly, debugName); } } return useDebugScript; } // Improves the UI in the VS collection editor, by displaying the Name or Path (if available), or // the short type name. [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public override string ToString() { if (!String.IsNullOrEmpty(Name)) { return Name; } else if (!String.IsNullOrEmpty(Path)) { return Path; } else { return GetType().Name; } } internal class ScriptEffectiveInfo { private string _resourceName; private Assembly _assembly; private string _path; private string _debugPath; private string _cdnPath; private string _cdnDebugPath; private string _cdnPathSecureConnection; private string _cdnDebugPathSecureConnection; public ScriptEffectiveInfo(ScriptReference scriptReference) { ScriptResourceDefinition definition = ScriptManager.ScriptResourceMapping.GetDefinition(scriptReference); string name = scriptReference.Name; string path = scriptReference.Path; Assembly assembly = scriptReference.GetAssembly(); if (definition != null) { if (String.IsNullOrEmpty(path)) { // only when the SR has no path, the mapping's path and debug path, if any, apply path = definition.Path; _debugPath = definition.DebugPath; } name = definition.ResourceName; assembly = definition.ResourceAssembly; _cdnPath = definition.CdnPath; _cdnDebugPath = definition.CdnDebugPath; _cdnPathSecureConnection = definition.CdnPathSecureConnection; _cdnDebugPathSecureConnection = definition.CdnDebugPathSecureConnection; LoadSuccessExpression = definition.LoadSuccessExpression; } else if ((assembly == null) && !String.IsNullOrEmpty(name)) { // name is set and there is no mapping, default to SWE for assembly assembly = AssemblyCache.SystemWebExtensions; } _resourceName = name; _assembly = assembly; _path = path; if (assembly != null && !String.IsNullOrEmpty(name) && String.IsNullOrEmpty(LoadSuccessExpression)) { var scriptResourceInfo = ScriptResourceInfo.GetInstance(assembly, name); if (scriptResourceInfo != null) { LoadSuccessExpression = scriptResourceInfo.LoadSuccessExpression; } } } public Assembly Assembly { get { return _assembly; } } public string CdnDebugPath { get { return _cdnDebugPath; } } public string CdnPath { get { return _cdnPath; } } public string CdnDebugPathSecureConnection { get { return _cdnDebugPathSecureConnection; } } public string CdnPathSecureConnection { get { return _cdnPathSecureConnection; } } public string LoadSuccessExpression { get; private set; } public string DebugPath { get { return _debugPath; } } public string Path { get { return _path; } } public string ResourceName { get { return _resourceName; } } } } }
using App.Security.AspNet.Auth0; using App.Security.AspNet.Authentication; using App.Security.AspNet.Authorization; using App.Security.AspNet.Authorization.Extensions; using Autofac; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Security.Authorization.Model; using System.Collections.Generic; namespace SampleMvcApp { public partial class Startup { readonly SecurityServicesBuilder securityBuilder; /// <summary> /// Helper class found in partial class file Startup.Security /// </summary> private class SecurityServicesBuilder { readonly Auth0AuthenticationBuilder auth0; private AspNetCoreAuthorizationBuilder authorization; private ContainerBuilder containerBuilder; private IServiceCollection services; private IApplicationBuilder app; private OpenIdConnectOptions oidcOptions; private IContainer container; public SecurityServicesBuilder(IConfigurationRoot configuration, ContainerBuilder containerBuilder) { auth0 = new Auth0AuthenticationBuilder(configuration); authorization = new AspNetCoreAuthorizationBuilder(configuration, containerBuilder); this.containerBuilder = containerBuilder; } public SecurityServicesBuilder WithServices(IServiceCollection services) { this.services = services; return this; } public SecurityServicesBuilder WithContainer(IContainer container) { this.container = container; return this; } public SecurityServicesBuilder WithApp(IApplicationBuilder app) { this.app = app; return this; } public SecurityServicesBuilder WithOpenIdConnectOptions(OpenIdConnectOptions options) { this.oidcOptions = options; return this; } public SecurityServicesBuilder AddAuthentication() { auth0.Using(services).AddAuth0(); return this; } public SecurityServicesBuilder AddAuthorization() { authorization.AddAuthorizationServices(); var permissions = GetPermissions(); services.AddPermissionPolicies(permissions); return this; } public void UseAuth0() { var subscriber = container.Resolve<AuthorizationCookieAuthEventSubscriber>(); app.UseAuth0(this.oidcOptions, subscriber); } private IEnumerable<Permission> GetPermissions() { return new List<Permission>(); } } } }
using System.Reflection; namespace Patchwork.Engine.Utility { /// <summary> /// Commonly used combinations of the BindingFlags enum. /// </summary> public static class CommonBindingFlags { /// <summary> /// Instance, Static, Public, NonPublic /// </summary> public static BindingFlags Everything = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Categorie {Physique, Special, Statut}; public class Attaque : MonoBehaviour { public PhysicType type; public Categorie categorie; public int PP; public int puissance; public int precision; [HideInInspector]public bool isRunning = false; public Sprite spriteGUI; public Move pers; public float lastSend; // Use this for initialization void Start () { lastSend = Time.time - 1000; } // Update is called once per frame void Update () { } public virtual void Fire(string buttonPressed) { } }
namespace CoreAll.Msmq.ErrorQueue { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Messaging; using System.Text; using System.Transactions; using System.Xml.Serialization; public static class ErrorQueue { static void Usage() { #region msmq-return-to-source-queue-usage ReturnMessageToSourceQueue( errorQueueMachine: Environment.MachineName, errorQueueName: "error", msmqMessageId: @"c390a6fb-4fb5-46da-927d-a156f75739eb\15386"); #endregion } #region msmq-return-to-source-queue public static void ReturnMessageToSourceQueue(string errorQueueMachine, string errorQueueName, string msmqMessageId) { var path = $@"{errorQueueMachine}\private$\{errorQueueName}"; var errorQueue = new MessageQueue(path); { var messageReadPropertyFilter = new MessagePropertyFilter { Body = true, TimeToBeReceived = true, Recoverable = true, Id = true, ResponseQueue = true, CorrelationId = true, Extension = true, AppSpecific = true, LookupId = true, }; errorQueue.MessageReadPropertyFilter = messageReadPropertyFilter; using (var scope = new TransactionScope()) { var transactionType = MessageQueueTransactionType.Automatic; var message = errorQueue.ReceiveById(msmqMessageId, TimeSpan.FromSeconds(5), transactionType); var fullPath = ReadFailedQueueHeader(message); using (var failedQueue = new MessageQueue(fullPath)) { failedQueue.Send(message, transactionType); } scope.Complete(); } } } static string ReadFailedQueueHeader(Message message) { var headers = ExtractHeaders(message); var header = headers.Single(x => x.Key == "NServiceBus.FailedQ").Value; var queueName = header.Split('@')[0]; var machineName = header.Split('@')[1]; return $@"{machineName}\private$\{queueName}"; } public static List<HeaderInfo> ExtractHeaders(Message message) { var serializer = new XmlSerializer(typeof(List<HeaderInfo>)); var extension = Encoding.UTF8.GetString(message.Extension); using (var stringReader = new StringReader(extension)) { return (List<HeaderInfo>) serializer.Deserialize(stringReader); } } public class HeaderInfo { public string Key { get; set; } public string Value { get; set; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rainnier.DesignPattern.Builder.Structural { public class Director { public Product Construct(Builder builder) { builder.BuildPartA(); builder.BuildPartB(); return builder.GetResult(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; using Cardbooru.Application; using Cardbooru.Application.Entities; using Cardbooru.Application.Exceptions; using Cardbooru.Application.Infrastructure.Messages; using Cardbooru.Application.Interfaces; using Cardbooru.Gui.Wpf.Entities; using Cardbooru.Gui.Wpf.Infrastructure; using Cardbooru.Gui.Wpf.Interfaces; using MvvmCross.Plugins.Messenger; namespace Cardbooru.Gui.Wpf.ViewModels { class FullImageBrowsingViewModel : IUserControlViewModel { private readonly IMvxMessenger _messenger; private CancellationTokenSource _cancellationTokenSource; private BooruImageWpf _currentBooruImage; private BooruFullImageViewer _fullImageViewer; public event PropertyChangedEventHandler PropertyChanged; public List<string> TagsList => _fullImageViewer.GetTags(); public ImageSource Image { get; set; } public bool IsFullImageLoaded { get; set; } public FullImageBrowsingViewModel(IMvxMessenger messenger, IBooruFullImageViewerFactory booruFullImageViewerFactory ) { _messenger = messenger; _fullImageViewer = booruFullImageViewerFactory.Create(); } //Todo navigation param toggles nav buttons //ToDo Respect tags public void Init( BooruImageWpf openedBooruImage, BooruPostsProvider provider) { _fullImageViewer.Init(provider, openedBooruImage); _currentBooruImage = openedBooruImage; Image = openedBooruImage.BitmapImage; } public async Task ShowFullImage() { try { _cancellationTokenSource?.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; //Todo sometimes pic does not load var fullImageData = await _fullImageViewer.FetchImageAsync(_currentBooruImage, cancellationToken); BitmapImage bitmapImage = null; await Task.Run(() => bitmapImage = BitmapImageCreator.Create(fullImageData)); Image = bitmapImage; IsFullImageLoaded = true; } catch (OperationCanceledException e) { } } #region Commands private RelayCommand _closeImageCommand; public RelayCommand CloseImageCommand => _closeImageCommand ?? (_closeImageCommand = new RelayCommand(o => { _fullImageViewer = null; _messenger.Publish(new CloseFullImageMessage(this)); })); private RelayCommand _nextImage; public RelayCommand NextImage => _nextImage ?? (_nextImage = new RelayCommand(async o => { _cancellationTokenSource?.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; IsFullImageLoaded = false; BooruImage booruImage; try { booruImage = await _fullImageViewer.GetNextBooruImageAsync(SetImage, cancellationToken); } catch (OperationCanceledException e) { return; } var booruImageWpf = new BooruImageWpf(booruImage); booruImageWpf.InitializeImage(); Image = booruImageWpf.BitmapImage; IsFullImageLoaded = true; })); private RelayCommand _prevImage; public RelayCommand PrevImage => _prevImage ?? (_prevImage = new RelayCommand(async o => { _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; IsFullImageLoaded = false; BooruImage booruImage; try { booruImage = await _fullImageViewer.GetPrevBooruImageAsync(SetImage, cancellationToken); } catch (OperationCanceledException e) { return; } catch (QueryPageException e) { IsFullImageLoaded = true; return; } var booruImageWpf = new BooruImageWpf(booruImage); booruImageWpf.InitializeImage(); Image = booruImageWpf.BitmapImage; IsFullImageLoaded = true; })); #endregion private void SetImage(BooruImage booruImage) { //ToDo Probably it works not fine because sometimes it TagsList could contain tags from prev image PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TagsList")); var booruImageWpf = new BooruImageWpf(booruImage); booruImageWpf.InitializeImage(); _currentBooruImage = booruImageWpf; Image = booruImageWpf.BitmapImage; } } }
// <copyright file="RecordTidal.cs" company="Traced-Ideas, Czech republic"> // Copyright (c) 1990-2021 All Right Reserved // </copyright> // <author></author> // <email></email> // <date>2021-09-01</date> // <summary>Part of Astro Observatory</summary> namespace AstroSharedEvents.Records { using AstroSharedClasses.Calendars; using AstroSharedClasses.Computation; using AstroSharedOrbits.Systems; using System; using System.Globalization; /// <summary> /// Record Tidal. /// </summary> /// <seealso cref="AstroSharedEvents.Records.AbstractRecord" /> public class RecordTidal : AbstractRecord { /// <summary> /// Outputs the tidal excell. /// </summary> public override void OutputRecord() { var M = SolarSystem.Singleton.Mercury; var V = SolarSystem.Singleton.Venus; var E = SolarSystem.Singleton.Earth; var J = SolarSystem.Singleton.Jupiter; this.Text.AppendFormat("{0,10:F4} ", Julian.Year(this.JulianDate)); this.Text.Append("\t" + Julian.CalendarDate(this.JulianDate, false)); this.Text.AppendFormat( CultureInfo.InvariantCulture, "\tL \t{0,6:F2}\t{1,6:F2}\t{2,6:F2}\t{3,6:F2}\t", M.Longitude, V.Longitude, E.Longitude, J.Longitude); this.Text.AppendFormat( CultureInfo.InvariantCulture, "\tR \t{0,15:F1}\t{1,15:F1}\t{2,15:F1}\t{3,15:F1}\t", M.Point.RT, V.Point.RT, E.Point.RT, J.Point.RT); var gM = M.Body.Mass / M.Point.RT / M.Point.RT / M.Point.RT * 1e12; var gV = V.Body.Mass / V.Point.RT / V.Point.RT / V.Point.RT * 1e12; var gE = E.Body.Mass / E.Point.RT / E.Point.RT / E.Point.RT * 1e12; var gJ = J.Body.Mass / J.Point.RT / J.Point.RT / J.Point.RT * 1e12; this.Text.AppendFormat( CultureInfo.InvariantCulture, "\tM/R3 \t{0,12:F3}\t{1,12:F3}\t{2,12:F3}\t{3,12:F3}\t", gM, gV, gE, gJ); this.Text.AppendFormat( CultureInfo.InvariantCulture, "\tBary\t{0,5:F1}\t{1,5:F1}", Angles.Mod360(SolarSystem.Singleton.Barycentre.Longitude), SolarSystem.Singleton.Barycentre.RT); this.Text.AppendFormat( CultureInfo.InvariantCulture, "\tGravi\t{0,5:F1}\t{1,5:F1}", Angles.Mod360(SolarSystem.Singleton.Gravicentre.Longitude), SolarSystem.Singleton.Gravicentre.RT); this.Text.AppendFormat( CultureInfo.InvariantCulture, "\tIdx \t{0,6:F2} ", SolarSystem.Singleton.TotalAlignmentIndex); this.Text.AppendFormat( CultureInfo.InvariantCulture, "\t\t{0,6:F2}\t{1,6:F2}\t{2,6:F2}\t{3,6:F2}\t", M.AlignmentIndex, V.AlignmentIndex, E.AlignmentIndex, J.AlignmentIndex); //// var angle1 = Angles.CorrectAngle(V.Longitude - J.Longitude); revert var angle1 = Angles.CorrectAngle(J.Longitude - V.Longitude); var y1 = gV + gJ * Angles.Cosin(2 * angle1); var x1 = gJ * Angles.Sinus(2 * angle1); var g1 = Math.Sqrt(x1 * x1 + y1 * y1); var delta1 = Angles.ArcSinus(x1 / g1) / 2; var dip1 = V.Longitude + delta1; this.Text.AppendFormat( CultureInfo.InvariantCulture, "\t(1) \t{0,6:F2}\t{1,6:F2}\t{2,6:F2}\t{3,6:F2}\t{4,6:F2}\t{5,6:F2}\t", angle1, y1, x1, g1, delta1, dip1); //// var angle2 = Angles.CorrectAngle(dip1 - M.Longitude); revert var angle2 = Angles.CorrectAngle(M.Longitude - dip1); var y2 = g1 + gM * Angles.Cosin(2 * angle2); var x2 = gM * Angles.Sinus(2 * angle2); var g2 = Math.Sqrt(x2 * x2 + y2 * y2); var delta2 = Angles.ArcSinus(x2 / g2) / 2; var dip2 = dip1 + delta2; this.Text.AppendFormat( CultureInfo.InvariantCulture, "\t(2) \t{0,6:F2}\t{1,6:F2}\t{2,6:F2}\t{3,6:F2}\t{4,6:F2}\t{5,6:F2}\t", angle2, y2, x2, g2, delta2, dip2); //// var angle3 = Angles.CorrectAngle(dip2 - E.Longitude); revert var angle3 = Angles.CorrectAngle(E.Longitude - dip2); var y3 = g2 + gE * Angles.Cosin(2 * angle3); var x3 = gE * Angles.Sinus(2 * angle3); var g3 = Math.Sqrt(x3 * x3 + y3 * y3); var delta3 = Angles.ArcSinus(x3 / g3) / 2; var dip3 = dip2 + delta3; this.Text.AppendFormat( CultureInfo.InvariantCulture, "\t(3) \t{0,6:F2}\t{1,6:F2}\t{2,6:F2}\t{3,6:F2}\t{4,6:F2}\t{5,6:F2}\t", angle3, y3, x3, g3, delta3, dip3); this.IsFinished = true; } } }
using OnLineShop.Data.Models; using System.Linq; namespace OnLineShop.MVP.Products.Client { public class ProductsViewModel { public IQueryable<Product> Products { get; set; } } }
namespace MotiNet.Entities { public interface ITaggedEntityManager<TEntity> : IManager<TEntity> where TEntity : class { ITagProcessor TagProcessor { get; } ITaggedEntityAccessor<TEntity> TaggedEntityAccessor { get; } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Discord.Commands; namespace QuizBowlDiscordScoreTracker.Commands { [AttributeUsage(AttributeTargets.Method)] public class HumanOnlyAttribute : PreconditionAttribute { [SuppressMessage( "Design", "CA1062:Validate arguments of public methods", Justification = "Discord.Net will pass in non-null CommandContext")] public override Task<PreconditionResult> CheckPermissionsAsync( ICommandContext context, CommandInfo command, IServiceProvider services) { if (context.User.IsBot) { return Task.FromResult(PreconditionResult.FromError("Bots are not allowed to run this command.")); } return Task.FromResult(PreconditionResult.FromSuccess()); } } }
using System.Windows; namespace SlrrLib.View { public partial class FlagEditor : Window { public bool ClosedWithOK { get; private set; } = false; public FlagEditor() { InitializeComponent(); } public void SetFlagInt(int flag) { ctrlCheckBox0x01.IsChecked = (flag & 0x01) != 0; ctrlCheckBox0x02.IsChecked = (flag & 0x02) != 0; ctrlCheckBox0x04.IsChecked = (flag & 0x04) != 0; ctrlCheckBox0x08.IsChecked = (flag & 0x08) != 0; ctrlCheckBox0x10.IsChecked = (flag & 0x10) != 0; ctrlCheckBox0x20.IsChecked = (flag & 0x20) != 0; } public int GetFlagInt() { int ret = 0; if (ctrlCheckBox0x01.IsChecked.Value) ret |= 0x01; if (ctrlCheckBox0x02.IsChecked.Value) ret |= 0x02; if (ctrlCheckBox0x04.IsChecked.Value) ret |= 0x04; if (ctrlCheckBox0x08.IsChecked.Value) ret |= 0x08; if (ctrlCheckBox0x10.IsChecked.Value) ret |= 0x10; if (ctrlCheckBox0x20.IsChecked.Value) ret |= 0x20; return ret; } private void ctrlButtonOK_Click(object sender, RoutedEventArgs e) { ClosedWithOK = true; Close(); } private void ctrlButtonCancel_Click(object sender, RoutedEventArgs e) { ClosedWithOK = false; Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Search; namespace SuperMap.WinRT.Utilities { internal static class StorageHelper { public async static Task<bool> FolderExist(this StorageFolder folder, string path) { if (string.IsNullOrEmpty(path)) { return false; } try { StorageFolder childFolder = await folder.GetFolderAsync(path); if (childFolder != null) { return true; } return false; } catch { return false; } //QueryOptions options = new QueryOptions(); //options.FolderDepth = FolderDepth.Deep; //options.UserSearchFilter = "path:" + path; //StorageFolderQueryResult result = folder.CreateFolderQueryWithOptions(options); //uint count = await result.GetItemCountAsync(); //return count > 0; } public async static Task<bool> FileExist(this StorageFolder folder, string path) { if (string.IsNullOrEmpty(path)) { return false; } try { StorageFile file = await folder.GetFileAsync(path); if (file != null) { return true; } return false; } catch { return false; } } public async static Task FolderDelete(this StorageFolder storageFolder) { IReadOnlyList<StorageFile> files = await storageFolder.GetFilesAsync(); foreach (StorageFile file in files) { await file.DeleteAsync(StorageDeleteOption.PermanentDelete); } IReadOnlyList<StorageFolder> folders = await storageFolder.GetFoldersAsync(); foreach (StorageFolder folder in folders) { await folder.FolderDelete(); } await storageFolder.DeleteAsync(StorageDeleteOption.PermanentDelete); } } }
// // Copyright (c) Nick Guletskii and Arseniy Aseev. All rights reserved. // Licensed under the MIT License. See LICENSE file in the solution root for full license information. // namespace WixWPFWizardBA { using System; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Windows; using System.Windows.Markup; using System.Windows.Threading; using Microsoft.Tools.WindowsInstallerXml.Bootstrapper; using Views; public class WixBootstrapper : BootstrapperApplication { public static Dispatcher BootstrapperDispatcher { get; private set; } public static WizardWindow RootView { get; set; } public string BundleName => this.Engine.StringVariables["WixBundleName"]; protected override void Run() { #if DEBUG Debugger.Launch(); #endif var code = int.Parse(this.Engine.FormatString("[UserLanguageID]")); CultureInfo cultureInfo; try { cultureInfo = CultureInfo.GetCultureInfo(code); } catch (CultureNotFoundException) { this.Engine.Log(LogLevel.Debug, $"Unable to get culture info for '{code}'"); cultureInfo = new CultureInfo("en-US"); } Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; Localisation.Culture = cultureInfo; FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata( XmlLanguage.GetLanguage(cultureInfo.IetfLanguageTag))); try { this.Engine.CloseSplashScreen(); var rebootPending = this.Engine.StringVariables["RebootPending"]; if (!string.IsNullOrEmpty(rebootPending) && rebootPending != "0") { if (this.Command.Display == Display.Full) { MessageBox.Show( string.Format(Localisation.WixBootstrapper_RestartPendingDialogBody, this.BundleName), string.Format(Localisation.WixBootstrapper_RestartPendingDialogTitle, this.BundleName), MessageBoxButton.OK, MessageBoxImage.Error); } this.Engine.Quit(3010); } this.Engine.Log(LogLevel.Verbose, "Launching Burn frontend"); BootstrapperDispatcher = Dispatcher.CurrentDispatcher; AppDomain.CurrentDomain.UnhandledException += (sender, args) => { this.Engine.Log(LogLevel.Error, $"Critical bootstrapper exception: {args.ExceptionObject}"); }; BootstrapperDispatcher.UnhandledException += (sender, args) => { this.Engine.Log(LogLevel.Error, $"Critical bootstrapper exception: {args.Exception}"); }; RootView = new WizardWindow(this); RootView.Closed += (sender, args) => BootstrapperDispatcher.InvokeShutdown(); this.Engine.Detect(); foreach (var commandLineArg in this.Command.GetCommandLineArgs()) { if (commandLineArg.StartsWith("InstallationType=", StringComparison.InvariantCultureIgnoreCase)) { var param = commandLineArg.Split(new[] {'='}, 2); RootView.ViewModel.PackageCombinationConfiguration.InstallationType = (InstallationType) Enum.Parse(typeof(InstallationType), param[1]); } } if (this.Command.Display == Display.Passive || this.Command.Display == Display.Full) { RootView.Show(); Dispatcher.Run(); } this.Engine.Quit(RootView.ViewModel.Status); } catch (Exception e) { this.Engine.Log(LogLevel.Error, $"Critical bootstrapper exception: {e}"); throw e; } } } }
using ExtendedXmlSerializer.ContentModel.Format; using ExtendedXmlSerializer.Core.Sources; namespace ExtendedXmlSerializer.ContentModel.Content { interface IInnerContentActivator : IParameterizedSource<IFormatReader, IInnerContent> {} }
using System; using System.ComponentModel; namespace AInBox.Astove.Core.Options.EnumDomainValues { public enum BooleanEnum { [Description("Não")] Nao = 0, Sim = 1 } public enum ActionEnum { Details=0, Edit=1, Insert=2, List=3 } }
using System; namespace NuSightConsole.Commands.Options { public class CloneCommandOption { public string SourcePath { get; set; } public bool DisplayOnly { get; set; } public string TargetPath { get; set; } public bool UseLatestVersion { get; set; } } }
using FluentAssertions; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xbehave; using Xunit; using Xunit.Abstractions; namespace RelationalLock.Tests { public class RelationalLockBuilderTests : TestBase { private RelationalLockBuilder builder; private RelationalLockConfigurator configurator; #region init public RelationalLockBuilderTests(ITestOutputHelper helper) : base(helper) { Setup(); } [Background] public void Setup() { configurator = new RelationalLockConfigurator(); builder = new RelationalLockBuilder(); } #endregion init [Fact(DisplayName = "キーを追加しないとBuildでエラーになることの確認")] public void NoKeyTest() { var builder = new RelationalLockBuilder(); new Action(() => builder.Build(configurator)).Should().Throw<ArgumentException>(); } [Scenario(DisplayName = "ビルド結果と有効なキーの確認まで")] public void SuccessTest() { IRelationalLockManager manager = default; "初期化" .x(() => { configurator.RegisterRelation("key1", "key3", "key2"); configurator.RegisterRelation("key2", "key4"); manager = builder.Build(configurator); }); "nullでないこと" .x(() => manager.Should().NotBeNull()); "有効なキーがリレーションを追加したキーの昇順であること" .x(() => manager.AvailableKeys.Should().Equal("key1", "key2", "key3", "key4")); } } }
// <auto-generated /> // Built from: hl7.fhir.r4b.core version: 4.1.0 // Option: "NAMESPACE" = "fhirCsR4" using fhirCsR4.Models; namespace fhirCsR4.ValueSets { /// <summary> /// MedicationKnowledge Package Type Codes /// </summary> public static class MedicationknowledgePackageTypeCodes { /// <summary> /// /// </summary> public static readonly Coding Ampule = new Coding { Code = "amp", Display = "Ampule", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Bag = new Coding { Code = "bag", Display = "Bag", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding BlisterPack = new Coding { Code = "blstrpk", Display = "Blister Pack", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Bottle = new Coding { Code = "bot", Display = "Bottle", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Box = new Coding { Code = "box", Display = "Box", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Can = new Coding { Code = "can", Display = "Can", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Cartridge = new Coding { Code = "cart", Display = "Cartridge", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Disk = new Coding { Code = "disk", Display = "Disk", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Dosette = new Coding { Code = "doset", Display = "Dosette", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Jar = new Coding { Code = "jar", Display = "Jar", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Jug = new Coding { Code = "jug", Display = "Jug", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Minim = new Coding { Code = "minim", Display = "Minim", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding NebuleAmp = new Coding { Code = "nebamp", Display = "Nebule Amp", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Ovule = new Coding { Code = "ovul", Display = "Ovule", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Pouch = new Coding { Code = "pch", Display = "Pouch", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Packet = new Coding { Code = "pkt", Display = "Packet", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Sashet = new Coding { Code = "sash", Display = "Sashet", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Strip = new Coding { Code = "strip", Display = "Strip", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Tin = new Coding { Code = "tin", Display = "Tin", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Tub = new Coding { Code = "tub", Display = "Tub", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Tube = new Coding { Code = "tube", Display = "Tube", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// /// </summary> public static readonly Coding Vial = new Coding { Code = "vial", Display = "Vial", System = "http://terminology.hl7.org/CodeSystem/medicationknowledge-package-type" }; /// <summary> /// Literal for code: Ampule /// </summary> public const string LiteralAmpule = "amp"; /// <summary> /// Literal for code: Bag /// </summary> public const string LiteralBag = "bag"; /// <summary> /// Literal for code: BlisterPack /// </summary> public const string LiteralBlisterPack = "blstrpk"; /// <summary> /// Literal for code: Bottle /// </summary> public const string LiteralBottle = "bot"; /// <summary> /// Literal for code: Box /// </summary> public const string LiteralBox = "box"; /// <summary> /// Literal for code: Can /// </summary> public const string LiteralCan = "can"; /// <summary> /// Literal for code: Cartridge /// </summary> public const string LiteralCartridge = "cart"; /// <summary> /// Literal for code: Disk /// </summary> public const string LiteralDisk = "disk"; /// <summary> /// Literal for code: Dosette /// </summary> public const string LiteralDosette = "doset"; /// <summary> /// Literal for code: Jar /// </summary> public const string LiteralJar = "jar"; /// <summary> /// Literal for code: Jug /// </summary> public const string LiteralJug = "jug"; /// <summary> /// Literal for code: Minim /// </summary> public const string LiteralMinim = "minim"; /// <summary> /// Literal for code: NebuleAmp /// </summary> public const string LiteralNebuleAmp = "nebamp"; /// <summary> /// Literal for code: Ovule /// </summary> public const string LiteralOvule = "ovul"; /// <summary> /// Literal for code: Pouch /// </summary> public const string LiteralPouch = "pch"; /// <summary> /// Literal for code: Packet /// </summary> public const string LiteralPacket = "pkt"; /// <summary> /// Literal for code: Sashet /// </summary> public const string LiteralSashet = "sash"; /// <summary> /// Literal for code: Strip /// </summary> public const string LiteralStrip = "strip"; /// <summary> /// Literal for code: Tin /// </summary> public const string LiteralTin = "tin"; /// <summary> /// Literal for code: Tub /// </summary> public const string LiteralTub = "tub"; /// <summary> /// Literal for code: Tube /// </summary> public const string LiteralTube = "tube"; /// <summary> /// Literal for code: Vial /// </summary> public const string LiteralVial = "vial"; }; }
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; public class SavePicker : MonoBehaviour { GameObject[] pointButtons = new GameObject[6 * 2]; // Use this for initialization void Start () { for (int i = 0; i < gameObject.transform.childCount; i++) { GameObject child = gameObject.transform.GetChild(i).gameObject; PointButton pb = child.GetComponent<PointButton>(); if (pb != null) { pointButtons[pb.index] = child; pb.savePicker = this; } } updateText(); } void updateText() { foreach (GameObject go in pointButtons) { PointButton pb = go.GetComponent<PointButton>(); if (pb != null) for (int j = 0; j < pb.transform.childCount; j++) { GameObject childChild = pb.transform.GetChild(j).gameObject; TextMesh tm = childChild.GetComponent<TextMesh>(); if (tm != null) if (!isSave(pb.index) && !saveExists(pb.index)) tm.text = ""; else tm.text = "" + (getSlot(pb.index) + 1); } } } public bool saveExists(int index) { return File.Exists(string.Format("Assets/saves/save" + (getSlot(index) + 1) + ".txt")); } int getSlot(int index) { return (index / 4) * 2 + (index % 2); } public bool isSave(int index) { return index % 4 < 2; } // Update is called once per frame void Update () { } public void pressed(int index) { int slot = getSlot(index); if (isSave(index)) PropHandler.save(count: slot + 1); else PropHandler.load(count: slot + 1); updateText(); } }
using System; using System.Collections.Generic; using System.Text; namespace wfQuery { public partial class wfQueryContext { } }
using ShineEngine; /// <summary> /// (generated by shine) /// </summary> public class HMainUI:GameUIBase { /// <summary> /// 玩家对象 /// </summary> public HPlayer hme=HGameC.player; /** UI模型 */ private UIModel_mainUI _model; protected override UIModel createModel() { return _model=new UIModel_mainUI(); } protected override void registLogics() { base.registLogics(); } protected override void init() { base.init(); _model.Button_start.click=()=> { if(me.scene.isMatching()) { FuncApplyCancelMatchRequest.create(GFunctionType.Melee).send(); } else { FuncApplyMatchRequest.create(GFunctionType.Melee).send(); } }; registPlayerEventListener(GameEventType.StartMatch,onMatchChange); registPlayerEventListener(GameEventType.CancelMatch,onMatchChange); } protected override void dispose() { base.dispose(); } protected override void onEnter() { base.onEnter(); onMatchChange(); } protected override void onExit() { base.onExit(); } protected void onMatchChange() { if(me.scene.isMatching()) { _model.Button_start.setTextString("匹配中"); } else { _model.Button_start.setTextString("开始匹配"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NinjectExample.ex1 { public class TaskFinder { private readonly ExchangeService service = new ExchangeService(new Uri("http://www.someserver.com")); public IEnumerable<WorkTask> Find(string email, int minPriority) { return service.FindTasks(email).Where(x => x.Priority >= minPriority); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class CreatePanel : MonoBehaviour { public void createButton () { string nick = GameObject.Find ("Canvas/CreatePanel/NickInput/Text").GetComponent<Text> ().text; if (nick.Length < 3 || Service.db.SelectCount ("FROM characters WHERE name = ?", nick) != 0) { return; } int inicialHealth = 270; int inicialMana = 130; CharacterData character = new CharacterData { name = nick, model = "male_01", position = "", level = 1, health = inicialHealth, maxHealth = inicialHealth, mana = inicialMana, maxMana = inicialMana, money = 234670, id = Service.db.Id(1) }; bool sucess = character.create(); if (sucess) { Menu.Instance.showPanel("MainPanel"); } else { Debug.Log("Something went wrong"); } } }
using System.Collections.Generic; using Chartreuse.Today.Core.Shared.Model; using Chartreuse.Today.Core.Shared.Tools.Navigation; namespace Chartreuse.Today.App.Shared.ViewModel.Settings { public class TaskOrderSettingsPageViewModel : PageViewModelBase { private string sortOption1; private bool isAscending1; private string sortOption2; private bool isAscending2; private string sortOption3; private bool isAscending3; public IEnumerable<string> AvailableSortOptions { get { return TaskOrderingConverter.Descriptions; } } public string SortOption1 { get { return this.sortOption1; } set { if (this.sortOption1 != value) { this.sortOption1 = value; this.RaisePropertyChanged("SortOption1"); } } } public bool IsAscending1 { get { return this.isAscending1; } set { if (this.isAscending1 != value) { this.isAscending1 = value; this.RaisePropertyChanged("IsAscending1"); this.RaisePropertyChanged("IsDescending1"); } } } public string SortOption2 { get { return this.sortOption2; } set { if (this.sortOption2 != value) { this.sortOption2 = value; this.RaisePropertyChanged("SortOption2"); } } } public bool IsAscending2 { get { return this.isAscending2; } set { if (this.isAscending2 != value) { this.isAscending2 = value; this.RaisePropertyChanged("IsAscending2"); } } } public string SortOption3 { get { return this.sortOption3; } set { if (this.sortOption3 != value) { this.sortOption3 = value; this.RaisePropertyChanged("SortOption3"); } } } public bool IsAscending3 { get { return this.isAscending3; } set { if (this.isAscending3 != value) { this.isAscending3 = value; this.RaisePropertyChanged("IsAscending3"); } } } public TaskOrderSettingsPageViewModel(IWorkbook workbook, INavigationService navigationService) : base(workbook, navigationService) { TaskOrdering taskOrdering1 = this.Settings.GetValue<TaskOrdering>(CoreSettings.TaskOrderingType1); this.sortOption1 = taskOrdering1.GetDescription(); this.isAscending1 = this.Settings.GetValue<bool>(CoreSettings.TaskOrderingAscending1); TaskOrdering taskOrdering2 = this.Settings.GetValue<TaskOrdering>(CoreSettings.TaskOrderingType2); this.sortOption2 = taskOrdering2.GetDescription(); this.isAscending2 = this.Settings.GetValue<bool>(CoreSettings.TaskOrderingAscending2); TaskOrdering taskOrdering3 = this.Settings.GetValue<TaskOrdering>(CoreSettings.TaskOrderingType3); this.sortOption3 = taskOrdering3.GetDescription(); this.isAscending3 = this.Settings.GetValue<bool>(CoreSettings.TaskOrderingAscending3); } public override void Dispose() { TaskOrdering ordering1 = TaskOrderingConverter.FromDescription(this.sortOption1); if (this.Settings.GetValue<TaskOrdering>(CoreSettings.TaskOrderingType1) != ordering1) this.Settings.SetValue(CoreSettings.TaskOrderingType1, ordering1); if (this.Settings.GetValue<bool>(CoreSettings.TaskOrderingAscending1) != this.IsAscending1) this.Settings.SetValue(CoreSettings.TaskOrderingAscending1, this.IsAscending1); TaskOrdering ordering2 = TaskOrderingConverter.FromDescription(this.sortOption2); if (this.Settings.GetValue<TaskOrdering>(CoreSettings.TaskOrderingType2) != ordering2) this.Settings.SetValue(CoreSettings.TaskOrderingType2, ordering2); if (this.Settings.GetValue<bool>(CoreSettings.TaskOrderingAscending2) != this.IsAscending2) this.Settings.SetValue(CoreSettings.TaskOrderingAscending2, this.IsAscending2); TaskOrdering ordering3 = TaskOrderingConverter.FromDescription(this.sortOption3); if (this.Settings.GetValue<TaskOrdering>(CoreSettings.TaskOrderingType3) != ordering3) this.Settings.SetValue(CoreSettings.TaskOrderingType3, ordering3); if (this.Settings.GetValue<bool>(CoreSettings.TaskOrderingAscending3) != this.IsAscending3) this.Settings.SetValue(CoreSettings.TaskOrderingAscending3, this.IsAscending3); } } }
using GeometryDashAPI.Exceptions; using GeometryDashAPI.Levels.GameObjects; using System; using System.Collections.Generic; using System.Reflection; namespace GeometryDashAPI.Levels { public class BindingBlockID : Dictionary<int, ConstructorInfo> { public void Bind(int id, Type type) { if (type.GetInterface(nameof(IBlock)) == null) throw new NotImplementIBlockException(type); ConstructorInfo ctrInfo = type.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.HasThis, new Type[] { typeof(string[]) }, null); if (ctrInfo != null) Add(id, ctrInfo); else throw new ConstructorNotFoundException(type); } public T Invoke<T>(int id, string[] data) { return (T)base[id].Invoke(new object[] { data }); } } }
using System; using System.Collections.Generic; using System.Linq; using MoreLinq; using UCLouvain.KAOSTools.Core; using UCLouvain.KAOSTools.Core.SatisfactionRates; namespace UCLouvain.KAOSTools.Propagators.BDD { public class BDDBasedPropagator : IPropagator { protected KAOSModel _model; protected Dictionary<string, ObstructionSuperset> obstructionSupersets; protected HashSet<Goal> prebuilt_goal; public BDDBasedPropagator (KAOSModel model) { _model = model; prebuilt_goal = new HashSet<Goal>(); obstructionSupersets = new Dictionary<string, ObstructionSuperset>(); } public virtual ISatisfactionRate GetESR (Obstacle obstacle) { throw new NotImplementedException (); } public virtual void PreBuildObstructionSet (Goal goal) { if (prebuilt_goal.Contains(goal)) { obstructionSupersets[goal.Identifier] = new ObstructionSuperset(goal); } else { obstructionSupersets.Add(goal.Identifier, new ObstructionSuperset(goal)); prebuilt_goal.Add(goal); } } public virtual ISatisfactionRate GetESR (Goal goal) { ObstructionSuperset os; if (!obstructionSupersets.ContainsKey(goal.Identifier)) { //Console.WriteLine("Computing new OS for " + goal.Identifier); os = new ObstructionSuperset(goal); //Console.WriteLine("---"); //Console.WriteLine(os.ToDot()); //Console.WriteLine("---"); } else os = obstructionSupersets[goal.Identifier]; var vector = new SamplingVector (_model); double v = os.GetProbability(vector); //Console.WriteLine("Obstruction set probability: " + v); return new DoubleSatisfactionRate(1.0 - v); } public virtual ISatisfactionRate GetESR (Obstacle obstacle, IEnumerable<Resolution> activeResolutions) { throw new NotImplementedException (); } public virtual ISatisfactionRate GetESR (Goal goal, IEnumerable<Resolution> activeResolutions) { throw new NotImplementedException (); } public ISatisfactionRate GetESR (Goal goal, IEnumerable<Obstacle> onlyObstacles) { ObstructionSuperset os; if (!obstructionSupersets.ContainsKey(goal.Identifier)) os = new ObstructionSuperset(goal); else os = obstructionSupersets[goal.Identifier]; var vector = new SamplingVector (_model, onlyObstacles?.Select(x => x.Identifier)?.ToHashSet()); var value = 1.0 - os.GetProbability(vector); return new DoubleSatisfactionRate(value); } } }
using System; using System.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Debugging; using Serilog.Events; using Serilog.Sinks.SystemConsole.Themes; namespace lookaroond { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); return Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration(a => { a.Sources.Clear(); a .AddJsonFile("appsettings.json", true, true) .AddJsonFile($"appsettings.{environment}.json", true, true) .AddJsonFile("appsettings.local.json", true, false) .AddJsonFile("secrets.json", true, false) .AddJsonFile("/config/config.override.json", true, true) .AddEnvironmentVariables() .AddCommandLine(args) ; }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>() .UseSerilog((a, l) => { l // .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // .MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning) .Enrich.FromLogContext() .Enrich.WithProperty("env", environment) .WriteTo.Console(LogEventLevel.Information, "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext} {Message}{NewLine}{Exception}", theme: SystemConsoleTheme.Colored); if (environment != "Production") { SelfLog.Enable(msg => Debug.WriteLine(msg)); SelfLog.Enable(Console.Error); } }) .UseKestrel(k => { k.ListenAnyIP(8192); k.Limits.MaxRequestBodySize = 100 * 1024 * 1024; // or a given limit }); }); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ChompShop.Controls { public partial class TextInputForm : Form { public TextInputForm() { InitializeComponent(); } public TextInputForm(string labelText, string titleText) { InitializeComponent(); this.Text = titleText; lblName.Text = labelText; } public string TextOutput { get { return txtName.Text; } } public string LabelText { get { return lblName.Text; } set { lblName.Text = value; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; namespace Azure.Core.Tests { public class TestDiagnosticListener : IObserver<DiagnosticListener>, IDisposable { private readonly Func<DiagnosticListener, bool> _selector; private List<IDisposable> _subscriptions = new List<IDisposable>(); public Queue<(string Key, object Value, DiagnosticListener Listener)> Events { get; } = new Queue<(string Key, object Value, DiagnosticListener Listener)>(); public Queue<(string, object, object)> IsEnabledCalls { get; } = new Queue<(string, object, object)>(); public TestDiagnosticListener(string name): this(source => source.Name == name) { } public TestDiagnosticListener(Func<DiagnosticListener, bool> selector) { _selector = selector; DiagnosticListener.AllListeners.Subscribe(this); } public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(DiagnosticListener value) { List<IDisposable> subscriptions = _subscriptions; if (_selector(value) && subscriptions != null) { lock (subscriptions) { subscriptions.Add(value.Subscribe(new InternalListener(Events, value), IsEnabled)); } } } private bool IsEnabled(string arg1, object arg2, object arg3) { lock (IsEnabledCalls) { IsEnabledCalls.Enqueue((arg1, arg2, arg3)); } return true; } public void Dispose() { if (_subscriptions != null) { List<IDisposable> subscriptions = null; lock (_subscriptions) { if (_subscriptions != null) { subscriptions = _subscriptions; _subscriptions = null; } } if (subscriptions != null) { foreach (IDisposable subscription in subscriptions) { subscription.Dispose(); } } } } private class InternalListener: IObserver<KeyValuePair<string, object>> { private readonly Queue<(string, object, DiagnosticListener)> _queue; private DiagnosticListener _listener; public InternalListener( Queue<(string, object, DiagnosticListener)> queue, DiagnosticListener listener) { _queue = queue; _listener = listener; } public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(KeyValuePair<string, object> value) { lock (_queue) { _queue.Enqueue((value.Key, value.Value, _listener)); } } } } }
// Aliases Func<AppQuery, AppQuery> with Query using Query = System.Func<Xamarin.UITest.Queries.AppQuery, Xamarin.UITest.Queries.AppQuery>; namespace TailwindTraders.UITests { public class ApplianceDetailPage : BasePage { private readonly Query addCartButton; protected override PlatformQuery Trait => new PlatformQuery { Android = x => x.Marked("shellcontent.scrollview"), iOS = x => x.Class("UIImageView").Index(0), }; public ApplianceDetailPage() { addCartButton = x => x.Marked("ADD TO CART"); } public ApplianceDetailPage AddToCart() { app.ScrollDownTo(addCartButton); app.WaitForElement(addCartButton); app.Tap(addCartButton); return this; } } }
public List<string> listaArquivos(string dir) { List<string> lstDirs = Directory.GetDirectories(dir).ToList(); List<string> lstFiles = Directory.GetFiles(dir, "*.frm", SearchOption.AllDirectories).ToList(); List<string> lstFilesAux = new List<string>(); foreach(string ldir in lstDirs) lstFilesAux = listaArquivos(ldir); lstFiles.AddRange(lstFilesAux); return lstFiles; } //https://pt.stackoverflow.com/q/44010/101
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JobSite.Models { public class PostJobDetail { public string CompanyId { get; set; } public string JobTitle { get; set; } public string JobType { get; set; } public int JobExperience { get; set; } public int JobMinSalary { get; set; } public int JobMaxSalary { get; set; } public string JobRegion { get; set; } public string JobLocation { get; set; } public string Description { get; set; } public List<string> Skills { get; set; } public List<DownloadFile> DownloadUrls { get; set; } public DateTimeOffset CreateAt { get; set; } public string CompanyName { get; set; } public string PhoneNumber { get; set; } public string ContactEmail { get; set; } public string ContactCountry { get; set; } public string ContactCity { get; set; } public string Zip { get; set; } public string Address { get; set; } public string CompanyDescription { get; set; } public string FacebookLink { get; set; } public string TwitterLink { get; set; } public string GoogleLink { get; set; } public string LinkedinLink { get; set; } public string CompanyWebsiteUrl { get; set; } public DateTimeOffset EstablishmentDate { get; set; } public List<string> Images { get; set; } } }
// // doc-bootstrap.cs: Stub support for XML documentation. // // Author: // Raja R Harinath <rharinath@novell.com> // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2004 Novell, Inc. // // #if BOOTSTRAP_WITH_OLDLIB || NET_2_1 using XmlElement = System.Object; namespace Mono.CSharp { public class DocUtil { internal static void GenerateTypeDocComment (TypeContainer t, DeclSpace ds, Report r) { } internal static void GenerateDocComment (MemberCore mc, DeclSpace ds, Report r) { } public static string GetMethodDocCommentName (MemberCore mc, ParametersCompiled p, DeclSpace ds) { return ""; } internal static void OnMethodGenerateDocComment (MethodCore mc, XmlElement el, Report r) { } public static void GenerateEnumDocComment (Enum e, DeclSpace ds) { } } public class Documentation { public Documentation (string xml_output_filename) { } public bool OutputDocComment (string asmfilename, Report r) { return true; } public void GenerateDocComment () { } } } #endif
using System; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace Contoso { public static class AsyncProcessingWorkAcceptor { [FunctionName("AsyncProcessingWorkAcceptor")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] CustomerPOCO customer, [ServiceBus("outqueue", Connection = "ServiceBusConnectionAppSetting")] IAsyncCollector<Message> OutMessage, ILogger log) { if (String.IsNullOrEmpty(customer.id) || String.IsNullOrEmpty(customer.customername)) { return new BadRequestResult(); } string reqid = Guid.NewGuid().ToString(); string rqs = $"http://{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/api/RequestStatus/{reqid}"; var messagePayload = JsonConvert.SerializeObject(customer); Message m = new Message(Encoding.UTF8.GetBytes(messagePayload)); m.UserProperties["RequestGUID"] = reqid; m.UserProperties["RequestSubmittedAt"] = DateTime.Now; m.UserProperties["RequestStatusURL"] = rqs; await OutMessage.AddAsync(m); return (ActionResult) new AcceptedResult(rqs, $"Request Accepted for Processing{Environment.NewLine}ProxyStatus: {rqs}"); } } }
#region Copyright 2010-2012 by Roger Knapp, Licensed under the Apache License, Version 2.0 /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Security.Principal; namespace CSharpTest.Net.RpcLibrary { /// <summary> /// An interface that provide contextual information about the client within an Rpc server call /// </summary> public interface IRpcClientInfo { /// <summary> /// Returns true if the caller is using LRPC /// </summary> bool IsClientLocal { get; } /// <summary> /// Returns a most random set of bytes, undocumented Win32 value. /// </summary> byte[] ClientAddress { get; } /// <summary> /// Defines the type of the procol being used in the communication, unavailable on Windows XP /// </summary> RpcProtoseqType ProtocolType { get; } /// <summary> /// Returns the packet protection level of the communications /// </summary> RpcProtectionLevel ProtectionLevel { get; } /// <summary> /// Returns the authentication level of the connection /// </summary> RpcAuthentication AuthenticationLevel { get; } /// <summary> /// Returns the ProcessId of the LRPC caller, may not be valid on all platforms /// </summary> IntPtr ClientPid { get; } /// <summary> /// Returns true if the caller has authenticated as a user /// </summary> bool IsAuthenticated { get; } /// <summary> /// Returns the client user name if authenticated, not available on WinXP /// </summary> string ClientPrincipalName { get; } /// <summary> /// Returns the identity of the client user or Anonymous if unauthenticated /// </summary> WindowsIdentity ClientUser { get; } /// <summary> /// Returns true if already impersonating the caller /// </summary> bool IsImpersonating { get; } /// <summary> /// Returns a disposable context that is used to impersonate the calling user /// </summary> IDisposable Impersonate(); } }
using System.Collections.Generic; namespace HomeAutomation.Areas.MyRecipes.Models { public class RecipeResponse { public int Id { get; set; } public string Name { get; set; } public string VideoId { get; set; } public string Amount { get; set; } public string Description { get; set; } public bool Private { get; set; } public bool Favorite { get; set; } public bool Vega { get; set; } public string MainImage { get; set; } public string Instruction { get; set; } public List<IngredientResponse> Ingredients { get; set; } public List<LinkResponse> Links { get; set; } public List<RecipeInstructionResponse> RecipeInstructions { get; set; } public List<string> Images { get; set; } } }
using System.Diagnostics; namespace WestWorld1 { using System; using WestWorld1.MinerStates; public class Miner : BaseGameEntity { public const int ComfortLevel = 5; private const int MaxNuggets = 3; private const int ThirstLevel = 5; private const int TirednessThreshold = 5; private IState<Miner> _currentState; private int _goldCarried; private int _thirst; private int _fatigue; public Location Location { get; set; } public int GoldCarried { get { return _goldCarried; } set { _goldCarried = value; if (_goldCarried < 0) _goldCarried = 0; } } public bool PocketsFull { get { return _goldCarried >= MaxNuggets; } } public bool Fatigued{ get { return _fatigue > TirednessThreshold; }} public void DecreaseFatigue() { _fatigue--; } public void IncreaseFatigue() { _fatigue++; } public int Wealth { get; set; } public void AddToWealth(int val) { Wealth += val; } public bool Thirsty { get { return _thirst >= ThirstLevel; } } public void BuyAndDrinkAWhiskey() { _thirst = 0; Wealth -= 2; } public Miner(string name) : base(name) { Location = Location.Shack; GoldCarried = 0; Wealth = 0; _thirst = 0; _fatigue = 0; _currentState = GoHomeAndSleepTilRested.Instance; } public override void Update() { _thirst++; if (_currentState != null) { _currentState.Execute(this); } } public void ChangeState(IState<Miner> newState) { Debug.Assert(_currentState != null); Debug.Assert(newState != null); _currentState.Exit(this); _currentState = newState; _currentState.Enter(this); } } }
using System.Collections.Generic; using Microsoft.LiveLabs.JavaScript; namespace Ribbon { internal class TemplateManager { Dictionary<string, Template> _templates; static TemplateManager _instance; public static TemplateManager Instance { get { if (CUIUtility.IsNullOrUndefined(_instance)) _instance = new TemplateManager(); return _instance; } } public TemplateManager() { _templates = new Dictionary<string, Template>(); } public void AddTemplate(Template template, string id) { _templates[id] = template; } public void RemoveTemplate(string id) { _templates[id] = null; } public Template GetTemplate(string id) { if (!_templates.ContainsKey(id)) return null; return _templates[id]; } public void LoadTemplates(object data) { JSObject templatesNode = DataNodeWrapper.GetFirstChildNodeWithName(data, DataNodeWrapper.RIBBONTEMPLATES); JSObject[] children = DataNodeWrapper.GetNodeChildren(templatesNode); for (int i = 0; i < children.Length; i++) LoadGroupTemplate(children[i]); } private void LoadGroupTemplate(object data) { string id = DataNodeWrapper.GetAttribute(data, DataNodeWrapper.ID); string className = DataNodeWrapper.GetAttribute(data, DataNodeWrapper.CLASSNAME); // If the template is already loaded, then we don't load it again if (!CUIUtility.IsNullOrUndefined(GetTemplate(id))) return; if (string.IsNullOrEmpty(className)) AddTemplate(new DeclarativeTemplate(data), id); } } }
// Author: Prasanna V. Loganathar // Project: Liara.Hosting.Owin // Copyright (c) Launchark Technologies. All rights reserved. // See License.txt in the project root for license information. // // Created: 8:31 AM 15-02-2014 using System.Collections.Generic; namespace Liara.Extensions { public static class OwinDictionaryExtensions { public static T Get<T>(this IDictionary<string, object> dictionary, string key) { object value; return dictionary.TryGetValue(key, out value) ? (T) value : default(T); } public static T Get<T>(this IDictionary<string, object> dictionary, string key, T defaultValue) { object value; return dictionary.TryGetValue(key, out value) ? (T) value : defaultValue; } public static T Get<T>(this IDictionary<string, object> dictionary, string subDictionaryKey, string key) { var subDictionary = dictionary.Get<IDictionary<string, object>>(subDictionaryKey); if (subDictionary == null) { return default(T); } return subDictionary.Get<T>(key); } public static T Get<T>(this IDictionary<string, object> dictionary, string subDictionaryKey, string key, T defaultValue) { var subDictionary = dictionary.Get<IDictionary<string, object>>(subDictionaryKey); if (subDictionary == null) { return defaultValue; } return subDictionary.Get(key, defaultValue); } public static void Set<T>(this IDictionary<string, object> dictionary, string key, T value) { dictionary[key] = value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using UnityEngine.Events; namespace UIF { public enum SelectionInputAction { TouchOrEnter = 0, Click = 1 } public class Selectable : UIPageElementFeature, IPointerClickHandler, IPointerEnterHandler { [SerializeField] protected UIPage holderPage = null; [SerializeField] protected SelectionInputAction inputMode = SelectionInputAction.Click; bool isInputFrozen = false; public bool FreezeInput { get { return isInputFrozen; } set { isInputFrozen = value; } } protected internal override void OnInitFeature(UIPage owner, UIPageElement ownerElement) { base.OnInitFeature(owner, ownerElement); isInputFrozen = false; } public void Select(bool multiSelect = false) { if (multiSelect == false) { DeselectAnySelectedPageSelectables(); } OwnerElement.StateInfo.State = UIFState.Selected; } public void DeselectAnySelectedPageSelectables() { var allFeaturesOfPage = holderPage.GetAllFeaturesAndBelow<Selectable>(); if (allFeaturesOfPage != null && allFeaturesOfPage.Count > 0) { for (int i = 0; i < allFeaturesOfPage.Count; i++) { var feature = allFeaturesOfPage[i]; if (feature == null) { continue; } if (feature.OwnerElement.StateInfo.State == UIFState.Selected) { feature.OwnerElement.StateInfo.State = UIFState.Normal; } } } } void IPointerClickHandler.OnPointerClick(PointerEventData eventData) { if (isInputFrozen) { return; } if (inputMode == SelectionInputAction.Click && (OwnerElement.StateInfo.State == UIFState.Normal)) { Select(); } } void IPointerEnterHandler.OnPointerEnter(PointerEventData eventData) { if (isInputFrozen) { return; } if (inputMode == SelectionInputAction.TouchOrEnter && (OwnerElement.StateInfo.State == UIFState.Normal)) { Select(); } } } }
namespace Oliviann.Collections.Concurrent { /// <summary> /// Notifies listeners of dynamic changes, such as when items get enqueued /// and dequeued or the whole collection is refreshed. /// </summary> /// <typeparam name="T">The type of the item contained in the queue. /// </typeparam> public interface INotifyQueueChanged<T> { /// <summary> /// Occurs when the queue changes. /// </summary> event NotifyQueueChangedEventHandler<T> QueueChanged; } }
using System; namespace WireMock.Matchers.Request { public class MatchDetail { public Type MatcherType { get; set; } public double Score { get; set; } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using NUnit.Framework; namespace DoubleTapTest.Tests { [TestFixture] public class QueuedLockCommandTests { QueuedLock _queuedLock; [SetUp] public void Setup() { _queuedLock = new QueuedLock(); } [Test] public async Task OnlyOneCommandWillExecuteSimultaneousTests() { //Flow: A executes, B executes, A starts, B waits, A completes, B starts, B completes. int countBefore = 0; int countAfter = 0; var sw = Stopwatch.StartNew(); Func<object, Task> execute = async (obj) => { Console.WriteLine($"E: {sw.Elapsed}"); Assert.AreEqual(countBefore, countAfter); countBefore++; await Task.Delay(100); Assert.Greater(countBefore, countAfter); countAfter++; Assert.AreEqual(countBefore, countAfter); }; //Execute is async void, so this will run in the background. new QueuedLockCommand(execute, _queuedLock).Execute(null); new QueuedLockCommand(execute, _queuedLock).Execute(null); await Task.Delay(50); Assert.AreEqual(1, countBefore); //A should hav started, Assert.AreEqual(0, countAfter); //But not finished. await Task.Delay(150); Assert.AreEqual(2, countBefore); //B should have started, Assert.AreEqual(1, countAfter); //but not finished. await Task.Delay(300); Assert.AreEqual(2, countBefore); //Both should be finished. Assert.AreEqual(2, countAfter); } [Test] public async Task CommandCanExecuteStatus() { //Wapping some code: var command = new QueuedLockCommand((obj) => Task.Delay(100), _queuedLock); Assert.IsTrue(command.CanExecute(null)); command.Execute(null); await Task.Delay(50); Assert.IsTrue(command.CanExecute(null)); await Task.Delay(100); Assert.IsTrue(command.CanExecute(null)); } [Test] public void CommandCanExecuteProperty() { //Wapping some code: var commandFalse = new QueuedLockCommand((obj) => Task.FromResult(0), (obj) => false, _queuedLock); var commandTrue = new QueuedLockCommand((obj) => Task.FromResult(0), (obj) => true, _queuedLock); Assert.IsFalse(commandFalse.CanExecute(null)); Assert.IsTrue(commandTrue.CanExecute(null)); } } }
using MathEx; using System.Linq; using SystemEx; using UnityEditor; using UnityEngine; using UnityEngine.UI; using UnityEngineEx; namespace UnityEditorEx.Components { [CustomEditor(typeof(PrefabPanel))] class Inspector_PrefabPanel : Editor<PrefabPanel> { public override void OnInspectorGUI() { base.OnInspectorGUI(); PrefabPanel panel = target; if (GUILayout.Button("Rebuild")) { RebuildPrefabPanel(panel); } if (GUILayout.Button("Apply")) { ApplyPrefabPanel(panel); } } public static void RebuildPrefabPanel(PrefabPanel panel) { panel.transform.ClearImmediate(); Vector3 position = Vector3.zero; int i = 0; foreach (GameObject prefab in panel.prefabs) { GameObject go = (GameObject)PrefabUtility.InstantiatePrefab(prefab); GameObject item = new GameObject("Item{0} ({1})".format(i, go.name)); if (panel.isUIPrefabs) { Canvas canvas = item.AddComponent<Canvas>(); CanvasScaler canvasScaler = item.AddComponent<CanvasScaler>(); GraphicRaycaster graphicRaycaster = item.AddComponent<GraphicRaycaster>(); canvas.renderMode = RenderMode.WorldSpace; RectTransform rectTransform = canvas.GetComponent<RectTransform>(); rectTransform.sizeDelta = panel.uiCanvasSize; } else { if (go.GetComponentInChildren<Renderer>() == null) { item.AddComponent<MeshRenderer>(); TextMesh text = item.AddComponent<TextMesh>(); text.characterSize = 0.1f; text.fontSize = 30; text.anchor = TextAnchor.MiddleCenter; text.alignment = TextAlignment.Center; text.text = go.name; } } go.transform.SetParent(item.transform, false); panel.Add(item); Bounds itemb = item.GetBounds(); if (panel.isUIPrefabs) { itemb = new Bounds(Vector3.zero, panel.uiCanvasSize.xyz(0)); } float shift = itemb.IsEmpty() ? 0.0f : (Vector3.right.Mul(itemb.size).magnitude / 2.0f); if (i > 0) { position += Vector3.right * shift; position += Vector3.right; } item.transform.localPosition = position; position += Vector3.right * shift; i++; } } public static void ApplyPrefabPanel(PrefabPanel panel) { EditorProgressBar.ShowProgressBar("Applying prefabs ...", 0); int i = 0; foreach (GameObject item in panel.gameObject.GetEnumerator()) { GameObject prefab = item.GetEnumerator().First(); PrefabUtility.ReplacePrefab(prefab, PrefabUtility.GetCorrespondingObjectFromSource(prefab)); i++; EditorProgressBar.ShowProgressBar("Applying prefabs ...", i / (i + 1.0f)); } EditorProgressBar.ShowProgressBar("Applying prefabs ...", 1.0f); EditorProgressBar.ClearProgressBar(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; public class CommandInterpreter : ICommandInterpreter { public CommandInterpreter(IHarvesterController harvesterController, IProviderController providerController) { HarvesterController = harvesterController; ProviderController = providerController; } public IHarvesterController HarvesterController { get; private set; } public IProviderController ProviderController { get; private set; } public string ProcessCommand(IList<string> args) { Command command = this.CreateCommand(args); string result = command.Execute(); return result; } private Command CreateCommand(IList<string> args) { string commandName = args[0]; Type commandType = Assembly.GetCallingAssembly() .GetTypes() .FirstOrDefault(t=>t.Name.Equals(commandName+"Command", StringComparison.InvariantCultureIgnoreCase)); if (commandType==null) { throw new ArgumentException(string.Format(Constants.CommandNotFound, commandName)); } if (!typeof(Command).IsAssignableFrom(commandType)) { throw new InvalidOperationException(string.Format(Constants.InvalidCommand)); } var ctor = commandType.GetConstructors().First(); var paramsInfo = ctor.GetParameters(); object[] parameters = new object[paramsInfo.Length]; //this way we provide only needed parameters for (int i = 0; i < paramsInfo.Length; i++) { Type paramType = paramsInfo[i].ParameterType; if (paramType==typeof(IList<string>)) { parameters[i] = args.Skip(1).ToList(); } else { PropertyInfo paramInfo = this.GetType().GetProperties() .FirstOrDefault(p=>p.PropertyType==paramType); parameters[i] = paramInfo.GetValue(this); } } //var arguments = args.Skip(1); //var instance = (ICommand)Activator.CreateInstance(commandType, arguments); var instance = (Command)Activator.CreateInstance(commandType, parameters); return instance; } }
namespace MrRobot.Core.Boundaries.Clean { public sealed class Command { public int StepsCount { get; } public Direction Direction { get; } public Command(int stepsCount, Direction direction) { StepsCount = stepsCount; Direction = direction; } } }
namespace SkyCommerce.Site.Models { public class AtualizarQuantidadeCarrinhoViewModel { public string NomeUnico { get; set; } public int Quantidade { get; set; } } }
using System; namespace Conreign.LoadTest.Core { public class BotFarmOptions { public BotFarmOptions() { BotStartInterval = TimeSpan.FromSeconds(2); GracefulStopPeriod = TimeSpan.FromSeconds(10); } public TimeSpan BotStartInterval { get; set; } public TimeSpan GracefulStopPeriod { get; set; } } }
using System.Windows.Media.Imaging; namespace TotoBook.ViewModel { public interface IFileListItemViewModel { bool IsDisplayed { get; set; } BitmapSource Icon { get; set; } } }
using System; using Autofac.Features.AttributeFilters; using Microsoft.Azure.WebJobs.Extensions.Timers; using ModernSlavery.BusinessDomain.Admin; using ModernSlavery.BusinessDomain.Shared; using ModernSlavery.BusinessDomain.Shared.Interfaces; using ModernSlavery.BusinessDomain.Viewing; using ModernSlavery.Core; using ModernSlavery.Core.Extensions; using ModernSlavery.Core.Interfaces; using ModernSlavery.Core.Models; using ModernSlavery.Hosts.Webjob.Classes; using ModernSlavery.Infrastructure.Storage; namespace ModernSlavery.Hosts.Webjob.Jobs { public partial class Functions { #region Dependencies private readonly StorageOptions _StorageOptions; private readonly IEventLogger _CustomLogger; private readonly IAuditLogger _BadSicLog; private readonly IAuditLogger _ManualChangeLog; private readonly IMessenger _Messenger; private readonly ISharedBusinessLogic _SharedBusinessLogic; private readonly ISearchRepository<EmployerSearchModel> _EmployerSearchRepository; private readonly ISearchRepository<SicCodeSearchModel> _SicCodeSearchRepository; private readonly IScopeBusinessLogic _ScopeBusinessLogic; private readonly ISubmissionBusinessLogic _SubmissionBusinessLogic; private readonly IOrganisationBusinessLogic _OrganisationBusinessLogic; public readonly ISearchBusinessLogic SearchBusinessLogic; private readonly IGovNotifyAPI govNotifyApi; private readonly UpdateFromCompaniesHouseService _updateFromCompaniesHouseService; private readonly ISnapshotDateHelper _snapshotDateHelper; private readonly IAuthorisationBusinessLogic _authorisationBusinessLogic; #endregion public Functions( StorageOptions storageOptions, IEventLogger customLogger, [KeyFilter(Filenames.BadSicLog)] IAuditLogger badSicLog, [KeyFilter(Filenames.ManualChangeLog)] IAuditLogger manualChangeLog, IMessenger messenger, ISharedBusinessLogic sharedBusinessLogic, ISearchRepository<EmployerSearchModel> employerSearchRepository, ISearchRepository<SicCodeSearchModel> sicCodeSearchRepository, ISubmissionBusinessLogic submissionBusinessLogic, IOrganisationBusinessLogic organisationBusinessLogic, ISearchBusinessLogic searchBusinessLogic, IGovNotifyAPI govNotifyApi, UpdateFromCompaniesHouseService updateFromCompaniesHouseService, IAuthorisationBusinessLogic authorisationBusinessLogic) { _StorageOptions = storageOptions; _CustomLogger = customLogger; _BadSicLog = badSicLog; _ManualChangeLog = manualChangeLog; _Messenger = messenger; _SharedBusinessLogic = sharedBusinessLogic; _EmployerSearchRepository = employerSearchRepository; _SicCodeSearchRepository = sicCodeSearchRepository; _SubmissionBusinessLogic = submissionBusinessLogic; _OrganisationBusinessLogic = organisationBusinessLogic; SearchBusinessLogic = searchBusinessLogic; _updateFromCompaniesHouseService = updateFromCompaniesHouseService; _authorisationBusinessLogic = authorisationBusinessLogic; this.govNotifyApi = govNotifyApi; } #region Properties public static readonly ConcurrentSet<string> RunningJobs = new ConcurrentSet<string>(); public static readonly ConcurrentSet<string> StartedJobs = new ConcurrentSet<string>(); #endregion #region Timer Trigger Schedules public class EveryWorkingHourSchedule : WeeklySchedule { public EveryWorkingHourSchedule() { // Every hour on Monday 8am-7pm Add(DayOfWeek.Monday, new TimeSpan(8, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(9, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(10, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(11, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(12, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(13, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(14, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(15, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(16, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(17, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(18, 0, 0)); Add(DayOfWeek.Monday, new TimeSpan(19, 0, 0)); // Every hour on Tuesday 8am-7pm Add(DayOfWeek.Tuesday, new TimeSpan(8, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(9, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(10, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(11, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(12, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(13, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(14, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(15, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(16, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(17, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(18, 0, 0)); Add(DayOfWeek.Tuesday, new TimeSpan(19, 0, 0)); // Every hour on Wednesday 8am-7pm Add(DayOfWeek.Wednesday, new TimeSpan(8, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(9, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(10, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(11, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(12, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(13, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(14, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(15, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(16, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(17, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(18, 0, 0)); Add(DayOfWeek.Wednesday, new TimeSpan(19, 0, 0)); // Every hour on Thursday 8am-7pm Add(DayOfWeek.Thursday, new TimeSpan(8, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(9, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(10, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(11, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(12, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(13, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(14, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(15, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(16, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(17, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(18, 0, 0)); Add(DayOfWeek.Thursday, new TimeSpan(19, 0, 0)); // Every hour on Friday 8am-7pm Add(DayOfWeek.Friday, new TimeSpan(8, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(9, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(10, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(11, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(12, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(13, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(14, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(15, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(16, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(17, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(18, 0, 0)); Add(DayOfWeek.Friday, new TimeSpan(19, 0, 0)); } } public class OncePerWeekendRandomSchedule : WeeklySchedule { public OncePerWeekendRandomSchedule() { switch (Numeric.Rand(0, 59)) { case 0: Add(DayOfWeek.Friday, new TimeSpan(20, 0, 0)); break; case 1: Add(DayOfWeek.Friday, new TimeSpan(21, 0, 0)); break; case 2: Add(DayOfWeek.Friday, new TimeSpan(22, 0, 0)); break; case 3: Add(DayOfWeek.Friday, new TimeSpan(23, 0, 0)); break; case 4: Add(DayOfWeek.Saturday, new TimeSpan(0, 0, 0)); break; case 5: Add(DayOfWeek.Saturday, new TimeSpan(1, 0, 0)); break; case 6: Add(DayOfWeek.Saturday, new TimeSpan(2, 0, 0)); break; case 7: Add(DayOfWeek.Saturday, new TimeSpan(3, 0, 0)); break; case 8: Add(DayOfWeek.Saturday, new TimeSpan(4, 0, 0)); break; case 9: Add(DayOfWeek.Saturday, new TimeSpan(5, 0, 0)); break; case 10: Add(DayOfWeek.Saturday, new TimeSpan(5, 0, 0)); break; case 11: Add(DayOfWeek.Saturday, new TimeSpan(7, 0, 0)); break; case 12: Add(DayOfWeek.Saturday, new TimeSpan(8, 0, 0)); break; case 13: Add(DayOfWeek.Saturday, new TimeSpan(9, 0, 0)); break; case 14: Add(DayOfWeek.Saturday, new TimeSpan(10, 0, 0)); break; case 15: Add(DayOfWeek.Saturday, new TimeSpan(11, 0, 0)); break; case 16: Add(DayOfWeek.Saturday, new TimeSpan(12, 0, 0)); break; case 17: Add(DayOfWeek.Saturday, new TimeSpan(13, 0, 0)); break; case 18: Add(DayOfWeek.Saturday, new TimeSpan(14, 0, 0)); break; case 19: Add(DayOfWeek.Saturday, new TimeSpan(15, 0, 0)); break; case 20: Add(DayOfWeek.Saturday, new TimeSpan(16, 0, 0)); break; case 21: Add(DayOfWeek.Saturday, new TimeSpan(17, 0, 0)); break; case 22: Add(DayOfWeek.Saturday, new TimeSpan(18, 0, 0)); break; case 23: Add(DayOfWeek.Saturday, new TimeSpan(19, 0, 0)); break; case 24: Add(DayOfWeek.Saturday, new TimeSpan(20, 0, 0)); break; case 25: Add(DayOfWeek.Saturday, new TimeSpan(21, 0, 0)); break; case 26: Add(DayOfWeek.Saturday, new TimeSpan(22, 0, 0)); break; case 27: Add(DayOfWeek.Saturday, new TimeSpan(23, 0, 0)); break; case 28: Add(DayOfWeek.Sunday, new TimeSpan(0, 0, 0)); break; case 29: Add(DayOfWeek.Sunday, new TimeSpan(1, 0, 0)); break; case 30: Add(DayOfWeek.Sunday, new TimeSpan(2, 0, 0)); break; case 31: Add(DayOfWeek.Sunday, new TimeSpan(3, 0, 0)); break; case 32: Add(DayOfWeek.Sunday, new TimeSpan(4, 0, 0)); break; case 33: Add(DayOfWeek.Sunday, new TimeSpan(5, 0, 0)); break; case 34: Add(DayOfWeek.Sunday, new TimeSpan(6, 0, 0)); break; case 35: Add(DayOfWeek.Sunday, new TimeSpan(7, 0, 0)); break; case 36: Add(DayOfWeek.Sunday, new TimeSpan(8, 0, 0)); break; case 37: Add(DayOfWeek.Sunday, new TimeSpan(9, 0, 0)); break; case 38: Add(DayOfWeek.Sunday, new TimeSpan(10, 0, 0)); break; case 39: Add(DayOfWeek.Sunday, new TimeSpan(11, 0, 0)); break; case 40: Add(DayOfWeek.Sunday, new TimeSpan(12, 0, 0)); break; case 41: Add(DayOfWeek.Sunday, new TimeSpan(13, 0, 0)); break; case 42: Add(DayOfWeek.Sunday, new TimeSpan(14, 0, 0)); break; case 43: Add(DayOfWeek.Sunday, new TimeSpan(15, 0, 0)); break; case 44: Add(DayOfWeek.Sunday, new TimeSpan(16, 0, 0)); break; case 45: Add(DayOfWeek.Sunday, new TimeSpan(17, 0, 0)); break; case 46: Add(DayOfWeek.Sunday, new TimeSpan(18, 0, 0)); break; case 47: Add(DayOfWeek.Sunday, new TimeSpan(19, 0, 0)); break; case 48: Add(DayOfWeek.Sunday, new TimeSpan(20, 0, 0)); break; case 49: Add(DayOfWeek.Sunday, new TimeSpan(21, 0, 0)); break; case 50: Add(DayOfWeek.Sunday, new TimeSpan(22, 0, 0)); break; case 51: Add(DayOfWeek.Sunday, new TimeSpan(23, 0, 0)); break; case 52: Add(DayOfWeek.Monday, new TimeSpan(0, 0, 0)); break; case 53: Add(DayOfWeek.Monday, new TimeSpan(1, 0, 0)); break; case 54: Add(DayOfWeek.Monday, new TimeSpan(2, 0, 0)); break; case 55: Add(DayOfWeek.Monday, new TimeSpan(3, 0, 0)); break; case 56: Add(DayOfWeek.Monday, new TimeSpan(4, 0, 0)); break; case 57: Add(DayOfWeek.Monday, new TimeSpan(5, 0, 0)); break; case 58: Add(DayOfWeek.Monday, new TimeSpan(6, 0, 0)); break; case 59: Add(DayOfWeek.Monday, new TimeSpan(7, 0, 0)); break; } } } public class MidnightSchedule : DailySchedule { public MidnightSchedule() : base("00:00:00") { } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MozJpegSharp { public static class MozJpeg { public static byte[] Recompress( ReadOnlySpan<byte> jpegBytes, int quality = 70, TJSubsamplingOption subsampling = TJSubsamplingOption.Chrominance420, TJFlags flags = TJFlags.None) { var pixelFormat = TJPixelFormat.BGRA; using var decr = new TJDecompressor(); var raw = decr.Decompress(jpegBytes, pixelFormat, flags, out var width, out var height, out var stride); decr.Dispose(); using var compr = new TJCompressor(); var compressed = compr.Compress(raw, stride, width, height, pixelFormat, subsampling, quality, flags); return compressed; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Security; using System.Security.Permissions; using MS.Internal; using MS.Internal.PresentationCore; // SecurityHelper using MS.Win32; using System.Windows.Threading; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Input { /// <summary> /// The object which input providers use to report input to the input /// manager. /// </summary> internal class InputProviderSite : IDisposable { /// <SecurityNote> /// Critical: This code creates critical data in the form of InputManager and InputProvider /// </SecurityNote> [SecurityCritical] internal InputProviderSite(InputManager inputManager, IInputProvider inputProvider) { _inputManager = new SecurityCriticalDataClass<InputManager>(inputManager); _inputProvider = new SecurityCriticalDataClass<IInputProvider>(inputProvider); } /// <summary> /// Returns the input manager that this site is attached to. /// </summary> /// <SecurityNote> /// Critical: We do not want to expose the Input manager in the SEE /// TreatAsSafe: This code has a demand in it /// </SecurityNote> public InputManager InputManager { [SecurityCritical,SecurityTreatAsSafe] get { SecurityHelper.DemandUnrestrictedUIPermission(); return CriticalInputManager; } } /// <summary> /// Returns the input manager that this site is attached to. /// </summary> /// <SecurityNote> /// Critical: We do not want to expose the Input manager in the SEE /// </SecurityNote> internal InputManager CriticalInputManager { [SecurityCritical] get { return _inputManager.Value; } } /// <summary> /// Unregisters this input provider. /// </summary> /// <SecurityNote> /// Critical: This code accesses critical data (InputManager and InputProvider). /// TreatAsSafe: The critical data is not exposed outside this call /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] public void Dispose() { GC.SuppressFinalize(this); if (!_isDisposed) { _isDisposed = true; if (_inputManager != null && _inputProvider != null) { _inputManager.Value.UnregisterInputProvider(_inputProvider.Value); } _inputManager = null; _inputProvider = null; } } /// <summary> /// Returns true if the CompositionTarget is disposed. /// </summary> public bool IsDisposed { get { return _isDisposed; } } /// <summary> /// Reports input to the input manager. /// </summary> /// <returns> /// Whether or not any event generated as a consequence of this /// event was handled. /// </returns> /// <remarks> /// Do we really need this? Make the "providers" call InputManager.ProcessInput themselves. /// we currently need to map back to providers for other reasons. /// </remarks> /// <SecurityNote> /// Critical:This code is critical and can be used in event spoofing. It also accesses /// InputManager and calls into ProcessInput which is critical. /// </SecurityNote> [SecurityCritical ] [UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted = true)] public bool ReportInput(InputReport inputReport) { if(IsDisposed) { throw new ObjectDisposedException(SR.Get(SRID.InputProviderSiteDisposed)); } bool handled = false; InputReportEventArgs input = new InputReportEventArgs(null, inputReport); input.RoutedEvent=InputManager.PreviewInputReportEvent; if(_inputManager != null) { handled = _inputManager.Value.ProcessInput(input); } return handled; } private bool _isDisposed; /// <SecurityNote> /// Critical: This object should not be exposed in the SEE as it can be /// used for input spoofing /// </SecurityNote> private SecurityCriticalDataClass<InputManager> _inputManager; /// <SecurityNote> /// Critical: This object should not be exposed in the SEE as it can be /// used for input spoofing /// </SecurityNote> private SecurityCriticalDataClass<IInputProvider> _inputProvider; } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UserService.Core.PolindromHasher.Tests { [TestClass] public class PolinomialHasher_Tests { private const string UserName = "testerUser"; private const string Password = "testPassword"; private readonly PolinomialHasher _polinomialHasher = new(); [TestMethod] public void PolinomialHasher_HashPassword_Test() { string hash = _polinomialHasher.HashPassword(UserName, Password); Assert.IsTrue(!string.IsNullOrWhiteSpace(hash)); } [TestMethod] [DataRow(true)] [DataRow(false)] public void PolinomialHasher_ComparePassword_Test(bool valid) { string hash = _polinomialHasher.HashPassword(UserName, Password); bool result = _polinomialHasher.ComparePassword(UserName, hash, valid ? UserName : Password); Assert.IsTrue(valid == result); } [TestMethod] [DataRow(true)] [DataRow(false)] public void PolinomialHasher_VerifyHashedPassword_Test(bool valid) { string hash = _polinomialHasher.HashPassword(UserName, Password); if (!valid) { hash += hash; } PasswordVerificationResult result = _polinomialHasher.VerifyHashedPassword(UserName, hash, Password); Assert.IsTrue(result == PasswordVerificationResult.Success == valid); } } }
namespace Platform.Validation { public enum SizeFlexibility { Variable, Fixed, LargeVariable } }
using Multiplatformer.Helpers; using Multiplatformer.Model; using Multiplatformer.ViewModel; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Multiplatformer.UWP.Views { public sealed partial class AddItems : Page { ItemsViewModel BrowseViewModel { get; set; } public AddItems() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); BrowseViewModel = (ItemsViewModel)e.Parameter; } private async void SaveItem_Click(object sender, RoutedEventArgs e) { var _item = new Item(); _item.Text = txtText.Text; _item.Description = txtDesc.Text; await BrowseViewModel.AddItem(_item); this.Frame.GoBack(); } } }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming // ReSharper disable MemberCanBePrivate.Global // ReSharper disable StringLiteralTypo // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnusedMember.Global // ReSharper disable UnusedParameter.Local // ReSharper disable UnusedType.Global /* ListFilesCommand.cs -- список файлов * Ars Magna project, http://arsmagna.ru */ #region Using directives using System; using System.Collections.Generic; using System.IO; using System.Linq; using AM; using AM.IO; using AM.Linq; using ManagedIrbis.Infrastructure; #endregion #nullable enable namespace ManagedIrbis.Server.Commands { /// <summary> /// Список файлов. /// </summary> public class ListFilesCommand : ServerCommand { #region Construction /// <summary> /// Конструктор. /// </summary> public ListFilesCommand ( WorkData data ) : base(data) { } // constructor #endregion #region Private members private string? _ResolveSpecification ( FileSpecification specification ) { Sure.NotNull(specification, nameof(specification)); var engine = Data.Engine.ThrowIfNull(nameof(Data.Engine)); var fileName = specification.FileName.ThrowIfNull(nameof(specification.FileName)); if (string.IsNullOrEmpty(fileName)) { return null; } string? result; var database = specification.Database; var path = (int)specification.Path; if (path == 0) { result = Path.Combine(engine.SystemPath, fileName); } else if (path == 1) { result = Path.Combine(engine.DataPath, fileName); } else { if (string.IsNullOrEmpty(database)) { return null; } var parPath = Path.Combine(engine.DataPath, database + ".par"); if (!File.Exists(parPath)) { result = null; } else { Dictionary<int, string> dictionary; using (var reader = TextReaderUtility.OpenRead(parPath, IrbisEncoding.Ansi)) { dictionary = ParFile.ReadDictionary(reader); } if (!dictionary.ContainsKey(path)) { result = null; } else { result = Path.Combine ( engine.SystemPath, dictionary[path], fileName ); } } } return result; } // method _ResolveSpecification private string[] _ListFiles ( string? template ) { if (string.IsNullOrEmpty(template)) { return Array.Empty<string>(); } var directory = Path.GetDirectoryName(template); if (string.IsNullOrEmpty(directory)) { return Array.Empty<string>(); } var pattern = Path.GetFileName(template); if (string.IsNullOrEmpty(pattern)) { return Array.Empty<string>(); } var result = Directory.GetFiles ( directory, pattern, SearchOption.TopDirectoryOnly ); result = result .Select(Path.GetFileName) .NonEmptyLines() .OrderBy(_ => _) .ToArray(); return result; } // method _ListFiles #endregion #region ServerCommand members /// <inheritdoc cref="ServerCommand.Execute" /> public override void Execute() { var engine = Data.Engine.ThrowIfNull(nameof(Data.Engine)); engine.OnBeforeExecute(Data); try { var context = engine.RequireContext(Data); Data.Context = context; UpdateContext(); var request = Data.Request.ThrowIfNull(nameof(Data.Request)); var lines = request.RemainingAnsiStrings(); var response = Data.Response.ThrowIfNull(nameof(Data.Response)); foreach (var line in lines) { var specification = FileSpecification.Parse(line); var template = _ResolveSpecification(specification); var files = _ListFiles(template); var text = string.Join(IrbisText.IrbisDelimiter, files); response.WriteAnsiString(text).NewLine(); } SendResponse(); } catch (IrbisException exception) { SendError(exception.ErrorCode); } catch (Exception exception) { Magna.TraceException(nameof(ListFilesCommand) + "::" + nameof(Execute), exception); SendError(-8888); } engine.OnAfterExecute(Data); } // method Execute #endregion } // class ListFilesCommand } // namespace ManagedIrbis.Server.Commands
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Linq.Mapping; using System.Data.SqlTypes; [Table(Name = "Players")] public class Players { [Column(IsPrimaryKey = true)] public int PlayerID; [Column] public string Name; [Column] public string LName; [Column] public string FName; [Column] public string Hcp; [Column] public string MemberID; [Column] public int Sex; [Column] public string Title; [Column] public DateTime HDate; [Column] public int Delete; }
namespace Multilang; using Raven.Client.Documents.Indexes; public class Search : AbstractIndexCreationTask<Article> { public class Entry { public string Text_en { get; set; } public string Text_fr { get; set; } public Dictionary<string, object> Text { get; set; } } public Search() { Map = articles => from article in articles let lang = string.IsNullOrWhiteSpace(article.Language) ? "en" : article.Language.ToLower() select new { _ = CreateField("Text_" + lang, article.Text) }; AnalyzersStrings = new Dictionary<string, string> { {"Text_en", "StandardAnalyzer"}, {"Text_fr", "FrenchAnalyzer"} }; } }
// Copyright 2015 The Minibench Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace Minibench.Framework { /// <summary> /// Attribute applied to any benchmark method or class to specify that it belongs /// in a particular category. Categories can then be explicitly included or /// excluded at execution time. When applied to a class, all benchmarks within that /// class are implicitly in that category. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class CategoryAttribute : Attribute { public string Category { get; } public CategoryAttribute(string category) { Category = category; } } }
namespace School.Web.Areas.Administration.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web.Mvc; using School.Services.Interfaces; public class SchoolClassEditViewModel : IValidatableObject { public Guid Id { get; set; } [Required] [Display(Name = "Class Letter")] [RegularExpression(@"[A-Za-z]", ErrorMessage = "The selected class letter should be a single alphabet character")] public string ClassLetter { get; set; } [Required] [Display(Name = "Grade Year")] public int GradeYear { get; set; } public Guid AcademicYearId { get; set; } public IEnumerable<SelectListItem> Grades { get { IGradeService gradeService = DependencyResolver.Current.GetService<IGradeService>(); List<int> grades = gradeService .All() .Where(g => g.AcademicYearId == this.AcademicYearId) .Select(g => g.GradeYear).ToList(); IEnumerable<SelectListItem> gradesList = grades.Select( gradeYear => new SelectListItem { Value = gradeYear.ToString(), Text = gradeYear.ToString() }); return gradesList; } } [Required] [Display(Name = "School Theme")] public int SchoolThemeId { get; set; } public IEnumerable<SelectListItem> SchoolThemes { get { ISchoolThemeService schoolThemeService = DependencyResolver.Current.GetService<ISchoolThemeService>(); var schoolThemes = schoolThemeService .All() .Select(st => new { st.Id, st.Name } ).ToList(); IEnumerable<SelectListItem> schoolThemesList = schoolThemes.Select( schoolTheme => new SelectListItem { Value = schoolTheme.Id.ToString(), Text = schoolTheme.Name.ToString() }); return schoolThemesList; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { ISchoolClassService schoolClassService = DependencyResolver.Current.GetService<ISchoolClassService>(); var currentGradeAcademicYearId = schoolClassService.GetById(this.Id).Grade.AcademicYearId; bool letterExists = schoolClassService .All() .Any( sc => sc.ClassLetter == this.ClassLetter && sc.Id != this.Id && sc.Grade.GradeYear == this.GradeYear && sc.Grade.AcademicYearId == currentGradeAcademicYearId); if (letterExists) { yield return new ValidationResult( "There is already another class with the same letter in this grade."); } } } }
namespace Prototype { public enum State { Run, Freeze, Catch }; }
using System.Collections.Generic; namespace CoreBoy.Avalonia { public class MainWindowViewModel { public IReadOnlyList<MenuItemViewModel> MenuItems { get; set; } } }
using System; using System.IO; namespace LiteDB.Issues.Tests.Common { public sealed class LiteRepositoryFixture : IDisposable { private readonly MemoryStream _stream; public LiteDB.LiteRepository Instance { get; } public LiteRepositoryFixture() { _stream = new MemoryStream(); Instance = new LiteDB.LiteRepository(_stream); } public void Dispose() { Instance.Dispose(); _stream.Dispose(); } } }
using System.Globalization; namespace YuriyGuts.RegexBuilder { public class RegexNodeGroupReference : RegexNode { public int? GroupIndex { get; set; } public string GroupName { get; set; } protected override bool AllowQuantifier { get { return true; } } public RegexNodeGroupReference(int? groupIndex) { GroupIndex = groupIndex; } public RegexNodeGroupReference(string groupName) { GroupName = groupName; } public override string ToRegexPattern() { string result; if (GroupIndex.HasValue) { result = "\\" + GroupIndex; } else { result = string.Format(CultureInfo.InvariantCulture, "\\k<{0}>", GroupName); } if (HasQuantifier) { result += Quantifier.ToRegexPattern(); } return result; } } }
using GW2_Win10.Services; using Template10.Mvvm; namespace GW2_Win10.ViewModels { public class CharactersPageViewModel : ViewModelBase { public AccountPartViewModel AccountPart { get; } = new AccountPartViewModel(); public bool CanViewCharacters => AccountPart?.Session?.HasPermission("characters") ?? false; } }
namespace Interpreter; public class Comma : Expression { public Comma(string value) : base(",") { } public override int Precedence => 1; public override Value Evaluate(Context context) => Value.Empty; }
using Fap.Core.DataAccess; using Fap.Workflow.Engine.Common; using Fap.Workflow.Engine.Core; using Fap.Workflow.Engine.Enums; using Fap.Workflow.Engine.Event; using Fap.Workflow.Engine.Exceptions; using Fap.Workflow.Engine.Manager; using Fap.Workflow.Engine.Xpdl; using Fap.Workflow.Engine.Xpdl.Entity; using Fap.Workflow.Engine.Xpdl.Node; using Fap.Workflow.Model; using Microsoft.Extensions.Logging; using System; namespace Fap.Workflow.Engine.Node { /// <summary> /// 子流程节点执行器 /// </summary> internal class NodeMediatorSubProcess : NodeMediator { internal NodeMediatorSubProcess(ActivityForwardContext forwardContext, WfAppRunner runner, IServiceProvider serviceProvider) : base(forwardContext, runner,serviceProvider) { } internal NodeMediatorSubProcess(WfAppRunner runner, IServiceProvider serviceProvider) : base(runner,serviceProvider) { } /// <summary> /// 执行子流程节点 /// </summary> internal override void ExecuteWorkItem() { try { if (base.Linker.FromActivity.ActivityType == ActivityTypeEnum.SubProcessNode) { //检查子流程是否结束 var pim = new ProcessInstanceManager(_serviceProvider); bool isCompleted = pim.CheckSubProcessInstanceCompleted( base.Linker.FromActivityInstance.Fid, base.Linker.FromActivityInstance.NodeId); if (isCompleted == false) { throw new WfRuntimeException(string.Format("当前子流程:[{0}]并没有到达结束状态,主流程无法向下执行。", base.Linker.FromActivity.ActivityName)); } } //完成当前的任务节点 bool canContinueForwardCurrentNode = CompleteWorkItem(ActivityForwardContext.TaskView.Fid); if (canContinueForwardCurrentNode) { //获取下一步节点列表:并继续执行 ContinueForwardCurrentNode(false); } } catch { throw; } } /// <summary> /// 完成任务实例 /// </summary> /// <param name="taskID">任务ID</param> /// <param name="activityResource">活动资源</param> /// <param name="session">会话</param> internal bool CompleteWorkItem(string taskUid) { bool canContinueForwardCurrentNode = true; //完成本任务,返回任务已经转移到下一个会签任务,不继续执行其它节点 base.TaskManager.Complete(taskUid, AppRunner); //设置活动节点的状态为完成状态 base.ActivityInstanceManager.Complete(base.Linker.FromActivityInstance.Fid, AppRunner); base.Linker.FromActivityInstance.ActivityState = ActivityStateEnum.Completed.ToString(); return canContinueForwardCurrentNode; } /// <summary> /// 创建活动任务转移数据 /// </summary> /// <param name="toActivity">目的活动</param> /// <param name="processInstance">流程实例</param> /// <param name="fromActivityInstance">来源活动实例</param> /// <param name="transitionGUID">转移GUID</param> /// <param name="transitionType">转移类型</param> /// <param name="flyingType">飞跃类型</param> /// <param name="activityResource">活动资源</param> /// <param name="session">会话</param> internal override void CreateActivityTaskTransitionInstance(ActivityEntity toActivity, WfProcessInstance processInstance, WfActivityInstance fromActivityInstance, string transitionGUID, TransitionTypeEnum transitionType, TransitionFlyingTypeEnum flyingType) { //实例化Activity var toActivityInstance = CreateActivityInstanceObject(toActivity, processInstance, AppRunner); //进入运行状态 toActivityInstance.ActivityState = ActivityStateEnum.Ready.ToString(); toActivityInstance.AssignedToUserIds = GenerateActivityAssignedUserIDs( toActivity.Performers); toActivityInstance.AssignedToUserNames = GenerateActivityAssignedUserNames( toActivity.Performers); //插入活动实例数据 base.ActivityInstanceManager.Insert(toActivityInstance); //插入任务数据 base.CreateNewTask(toActivityInstance,toActivity); //插入转移数据 InsertTransitionInstance(processInstance, transitionGUID, fromActivityInstance, toActivityInstance, transitionType, flyingType,AppRunner); //启动子流程 WfExecutedResult startedResult = null; var subProcessNode = (SubProcessNode)toActivity.Node; subProcessNode.ActivityInstance = fromActivityInstance; WfAppRunner subRunner = CopyActivityForwardRunner(AppRunner, new Performer() { UserId = AppRunner.UserId, UserName = AppRunner.UserName },subProcessNode ); var runtimeInstance = WfRuntimeManagerFactory.CreateRuntimeInstanceStartup(subRunner,_serviceProvider, processInstance, subProcessNode, ref startedResult); runtimeInstance.OnWfProcessExecuted += runtimeInstance_OnWfProcessStarted; runtimeInstance.Execute(); } private WfExecutedResult _startedResult = null; private void runtimeInstance_OnWfProcessStarted(object sender, WfEventArgs args) { _startedResult = args.WfExecutedResult; } /// <summary> /// 创建子流程时,重新生成runner信息 /// </summary> /// <param name="runner">运行者</param> /// <param name="performer">下一步执行者</param> /// <param name="subProcessNode">子流程节点</param> /// <returns></returns> private WfAppRunner CopyActivityForwardRunner(WfAppRunner runner, Performer performer, SubProcessNode subProcessNode) { WfAppRunner subRunner = new WfAppRunner(); subRunner.BillData = runner.BillData; subRunner.BillUid = runner.BillUid; subRunner.AppName = runner.AppName; subRunner.UserId = performer.UserId; subRunner.UserName = performer.UserName; subRunner.ProcessUid = subProcessNode.SubProcessId; return subRunner; } } }
using System; namespace Dyes { [AttributeUsage(AttributeTargets.Class)] public class UsageAttribute : Attribute { public string CmdWithArgs; public string Description; public string Example; public UsageAttribute(string cmdWithArgs, string description, string example = "") { CmdWithArgs = cmdWithArgs; Description = description; Example = example; } } }
namespace Sancho.Web { /// <summary> /// Represents a message exchanged between server/client parts of a plugin. /// </summary> public class Message { public string command { get; set; } public object data { get; set; } public MessageMetadata metadata { get; set; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using EF2OR.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace EF2OR.Controllers.Tests { [TestClass()] public class TemplatesControllerTests { [TestMethod()] public void TemplatesController_IndexTest() { TemplatesController controller = new TemplatesController(); ViewResult result = controller.Index() as ViewResult; Assert.IsNotNull(result, "Invalid Result"); Assert.IsNotNull(result.Model, "Invalid Model"); List<EF2OR.ViewModels.TemplateViewModel> model = result.Model as List<EF2OR.ViewModels.TemplateViewModel>; Assert.IsNotNull(model, "Unable to cast model"); if (model.Count > 0) { var firstItem = model.First(); Assert.IsTrue(firstItem.NumberOfDownloads >0 ,"Incorrect Number of Downloads"); Assert.IsTrue(!string.IsNullOrWhiteSpace(firstItem.AccessToken), "Empty Access Token"); Assert.IsTrue(!string.IsNullOrWhiteSpace(firstItem.AccessUrl), "Empty Access Token"); Assert.IsTrue(!string.IsNullOrWhiteSpace(firstItem.TemplateName), "Empty Template Name"); Assert.IsTrue(!string.IsNullOrWhiteSpace(firstItem.VendorName), "Empty Vendor Name"); } } } }
using DataDynamics.PageFX.Common.NUnit; namespace DataDynamics.PageFX.Common.TypeSystem { public static class TypeMemberExtensions { public static string BuildFullName(this ITypeMember member) { var declType = member.DeclaringType; return declType != null ? declType.FullName + "." + member.Name : member.Name; } public static bool IsVisible(this ITypeMember member) { var declType = member.DeclaringType; if (declType != null && !declType.IsVisible()) { return false; } var type = member as IType; if (type != null) { if (type.ElementType != null) return type.ElementType.IsVisible(); if (type.IsGenericInstance()) return type.Type == null || type.Type.IsVisible(); } switch (member.Visibility) { case Visibility.Public: case Visibility.NestedPublic: return true; } return false; } public static bool IsExposed(this ITypeMember member) { if (member == null) return false; var type = member as IType; if (type != null) { if (type.HasGenericParams()) return false; if (type.IsTestFixture()) return true; } var method = member as IMethod; if (method != null) { if (method.DeclaringType.IsTestFixture()) { if (method.IsConstructor) return true; if (method.IsNUnitMethod()) return true; } if (method.Association != null && method.Association.IsExposed()) return true; } return member.HasAttribute("ExposeAttribute"); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using DumpStackToCSharpCode.ObjectInitializationGeneration.CodeGeneration; using DumpStackToCSharpCode.ObjectInitializationGeneration.Type; namespace DumpStackToCSharpCode.ObjectInitializationGeneration.Initialization { public class ArrayInitializationGenerator { private readonly TypeAnalyzer _typeAnalyzer; public ArrayInitializationGenerator(TypeAnalyzer typeAnalyzer) { _typeAnalyzer = typeAnalyzer; } public ExpressionSyntax Generate(ExpressionData expressionData, SeparatedSyntaxList<ExpressionSyntax> expressionsSyntax, TypeCode typeCode) { var enterAfterEachElement = new SyntaxTriviaList(); if (!_typeAnalyzer.IsPrimitiveType(typeCode)) { enterAfterEachElement = SyntaxFactory.TriviaList(SyntaxFactory.LineFeed); } return SyntaxFactory.ObjectCreationExpression( SyntaxFactory.IdentifierName(expressionData.Type)) .WithNewKeyword( SyntaxFactory.Token( SyntaxFactory.TriviaList(), SyntaxKind.NewKeyword, SyntaxFactory.TriviaList( SyntaxFactory.Space))).WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.ObjectInitializerExpression, expressionsSyntax)); } } }
#nullable disable namespace PasPasPas.Globals.Types { /// <summary> /// short string type definition /// </summary> public interface IShortStringType : IStringType { /// <summary> /// string size /// </summary> byte Size { get; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; using Telerik.DataSource; namespace CustomSerializer.Server.JsonConverters { /// <summary> /// Handles serialization and deserialization of the Telerik DataSourceRequest filter descriptors for Newtonsoft.Json /// </summary> public class FilterDescriptorJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(IFilterDescriptor); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject filterDescriptor = JObject.Load(reader); if (filterDescriptor.ContainsKey("logicalOperator")) { return filterDescriptor.ToObject<CompositeFilterDescriptor>(serializer); } else { return filterDescriptor.ToObject<FilterDescriptor>(serializer); } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is CompositeFilterDescriptor) { serializer.Serialize(writer, (CompositeFilterDescriptor)value); } else if (value is FilterDescriptor) { serializer.Serialize(writer, (FilterDescriptor)value); } } } }
using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; using NuGetSearch.Common; namespace NuGetSearch.IOS { /// <summary> /// Version history table view cell. /// </summary> public class VersionHistoryTableViewCell : UITableViewCell { public const float RowHeight = 23f; private static readonly UIFont Font = UIFont.FromName("HelveticaNeue", 14f); private UILabel versionLabel; private UILabel downloadCountLabel; private UILabel lastUpdatedLabel; /// <summary> /// Initializes a new instance of the <see cref="NuGetSearch.IOS.VersionHistoryTableViewCell"/> class. /// </summary> /// <param name="reuseIdentifier">Reuse identifier.</param> public VersionHistoryTableViewCell(string reuseIdentifier) : this(new NSString(reuseIdentifier)) { this.SelectionStyle = UITableViewCellSelectionStyle.None; } /// <summary> /// Initializes a new instance of the <see cref="NuGetSearch.IOS.VersionHistoryTableViewCell"/> class. /// </summary> /// <param name="reuseIdentifier">Reuse identifier.</param> public VersionHistoryTableViewCell(NSString reuseIdentifier) : base(UITableViewCellStyle.Default, reuseIdentifier) { this.ContentView.BackgroundColor = UIColor.White; this.ContentView.Add(this.versionLabel = new UILabel() { Font = Font, }); this.ContentView.Add(this.downloadCountLabel = new UILabel() { Font = Font, TextColor = UIColor.Gray, TextAlignment = UITextAlignment.Right }); this.ContentView.Add(this.lastUpdatedLabel = new UILabel() { Font = Font, TextColor = UIColor.Gray, TextAlignment = UITextAlignment.Right }); } /// <summary> /// Displays the specified history item in the cell /// </summary> /// <param name="historyItem">History item.</param> public void UpdateCell(HistoryItem historyItem) { this.versionLabel.Text = historyItem.Version; this.downloadCountLabel.Text = historyItem.VersionDownloadCount.ToString("n0"); this.lastUpdatedLabel.Text = historyItem.Published.ToShortDateString(); } /// <summary> /// Defines the layout of the controls in this cell /// </summary> public override void LayoutSubviews() { base.LayoutSubviews(); const float pad = 8; float w = this.ContentView.Bounds.Width - (pad * 2); float w1 = (w / 3) - pad; float w2 = (w / 3) - pad; float w3 = w / 3; const float y = 0; float x1 = pad; float x2 = x1 + w1 + pad; float x3 = x2 + w2 + pad; this.versionLabel.Frame = new RectangleF(x1, y, w1, RowHeight); this.downloadCountLabel.Frame = new RectangleF(x2, y, w2, RowHeight); this.lastUpdatedLabel.Frame = new RectangleF(x3, y, w3, RowHeight); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Threading; public class TaskDropdown : MonoBehaviour { public Dropdown task_dropdown; //操作するオブジェクトの設定 public Dropdown user_dropdown; private Connect2MySQL sql; private bool isSelecting = false; private List<string> TaskList = new List<string>(); // Use this for initialization void Start () { sql = FindObjectOfType<Connect2MySQL>(); if (task_dropdown) { task_dropdown.ClearOptions(); List<string> list = new List<string>(); list.Insert(0, "----"); task_dropdown.AddOptions(list); //新しく要素のリストを設定する task_dropdown.value = 0; //デフォルトを設定 task_dropdown.interactable = false; } } public void OnValueChanged(int value) { task_dropdown.interactable = false; task_dropdown.ClearOptions(); StartCoroutine(SelectTaskInfo(user_dropdown.options[value].text)); } private IEnumerator SelectTaskInfo(string username) { isSelecting = true; Thread threadSelectTask = new Thread(new ParameterizedThreadStart(SetTaskDropdownList)); threadSelectTask.Start(username); while (isSelecting) { yield return new WaitForSeconds(0.1f); task_dropdown.interactable = false; user_dropdown.interactable = false; } TaskList.Insert(0, "----"); task_dropdown.AddOptions(TaskList); //新しく要素のリストを設定する task_dropdown.value = 0; //デフォルトを設定 task_dropdown.interactable = true; user_dropdown.interactable = true; isSelecting = false; } private void SetTaskDropdownList(object o) { string username = (string)o; TaskList = sql.GetFinishTaskList(username); isSelecting = false; } }
using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; namespace FileHelpers.Tests.CommonTests { [TestFixture] public class ReflectionOrder { [Test] public void ReadFile() { typeof (SampleType).GetField("Field2"); //typeof(SampleType).GetFields(); //typeof(SampleType).GetFields(); //typeof(SampleType).GetFields(); for (int i = 0; i < 10; i++) { typeof (SampleType).GetField("Field2"); var engine = new FileHelperEngine<SampleType>(); typeof (SampleType).GetField("Field2"); Assert.AreEqual("Field1", engine.Options.FieldsNames[0]); Assert.AreEqual("Field2", engine.Options.FieldsNames[1]); Assert.AreEqual("Field3", engine.Options.FieldsNames[2]); SampleType[] res; res = TestCommon.ReadTest<SampleType>(engine, "Good", "Test1.txt"); Assert.AreEqual(4, res.Length); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } } [Test] public void ReadFileBulk() { var temp = new ArrayList(); for (int i = 0; i < 10000; i++) { temp.Add(typeof (SampleType).GetField("Field2")); temp.Add(typeof (SampleType).GetField("Field3")); } //typeof(SampleType).GetFields(); //typeof(SampleType).GetFields(); //typeof(SampleType).GetFields(); for (int i = 0; i < 10; i++) { typeof (SampleType).GetField("Field2"); var engine = new FileHelperEngine<SampleType>(); typeof (SampleType).GetField("Field2"); Assert.AreEqual("Field1", engine.Options.FieldsNames[0]); Assert.AreEqual("Field2", engine.Options.FieldsNames[1]); Assert.AreEqual("Field3", engine.Options.FieldsNames[2]); SampleType[] res; res = TestCommon.ReadTest<SampleType>(engine, "Good", "Test1.txt"); Assert.AreEqual(4, res.Length); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } } [Test] public void FirstOrder() { typeof (SampleType).GetField("Field1"); typeof (SampleType).GetField("Field2"); typeof (SampleType).GetField("Field3"); for (int i = 0; i < 10; i++) { var engine = new FileHelperEngine<SampleType>(); Assert.AreEqual("Field1", engine.Options.FieldsNames[0]); Assert.AreEqual("Field2", engine.Options.FieldsNames[1]); Assert.AreEqual("Field3", engine.Options.FieldsNames[2]); SampleType[] res; res = TestCommon.ReadTest<SampleType>(engine, "Good", "Test1.txt"); Assert.AreEqual(4, res.Length); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } } [Test] public void ReadFileGenerics() { typeof (SampleType).GetField("Field2"); for (int i = 0; i < 10; i++) { var engine = new FileHelperEngine<SampleType>(); SampleType[] res; res = engine.ReadFile(FileTest.Good.Test1.Path); Assert.AreEqual(4, res.Length); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } } } }
using System.Threading.Tasks; using QuizApp.Core.DTOs; using Refit; namespace QuizApp.Core.Services { public interface ITriviaServiceClient { [Get("/api.php?type=multiple&amount={amount}&category={category}&difficulty={difficulty}&token={token}")] Task<TriviaRootDTO> GetTriviaQuestionsAsync(int amount, int category, string difficulty, string token); [Get("/api_token.php?command=request")] Task<TokenRequestDTO> GetTokenAsync(); [Get("/api_token.php?command=reset&token={token}")] Task<TokenResetDTO> ResetTokenAsync(string token); } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Microsoft.UI; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Media; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace AppUIBasics.ControlPages { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class RadioButtonPage : Page { public RadioButtonPage() { this.InitializeComponent(); } private void BGRadioButton_Checked(object sender, RoutedEventArgs e) { RadioButton rb = sender as RadioButton; if (rb != null && Control2Output != null) { string colorName = rb.Tag.ToString(); switch (colorName) { case "Yellow": Control2Output.Background = new SolidColorBrush(Colors.Yellow); break; case "Green": Control2Output.Background = new SolidColorBrush(Colors.Green); break; case "Blue": Control2Output.Background = new SolidColorBrush(Colors.Blue); break; case "White": Control2Output.Background = new SolidColorBrush(Colors.White); break; } } } private void BorderRadioButton_Checked(object sender, RoutedEventArgs e) { RadioButton rb = sender as RadioButton; if (rb != null && Control2Output != null) { string colorName = rb.Tag.ToString(); switch (colorName) { case "Yellow": Control2Output.BorderBrush = new SolidColorBrush(Colors.Gold); break; case "Green": Control2Output.BorderBrush = new SolidColorBrush(Colors.DarkGreen); break; case "Blue": Control2Output.BorderBrush = new SolidColorBrush(Colors.DarkBlue); break; case "White": Control2Output.BorderBrush = new SolidColorBrush(Colors.White); break; } } } private void Option1RadioButton_Checked(object sender, RoutedEventArgs e) { Control1Output.Text = "You selected option 1."; } private void Option2RadioButton_Checked(object sender, RoutedEventArgs e) { Control1Output.Text = "You selected option 2."; } private void Option3RadioButton_Checked(object sender, RoutedEventArgs e) { Control1Output.Text = "You selected option 3."; } } }
using CursoCore.Domain.Entities; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace CursoCore.Domain.Interfaces.Services { /// <summary> /// Junção do repositorio e especializada /// </summary> public interface IServiceProduto : IDisposable { void Adicionar(Produto obj); void Atualizar(Produto obj); void Remover(Produto obj); IEnumerable<Produto> ObterTodos(); IEnumerable<Produto> Buscar(Expression<Func<Produto, bool>> predicado); Produto ObterPorNome(string nome); Produto ObterPorApelido(string apelido); Produto ObterPorId(int id); } }
using System.Threading.Tasks; using Microsoft.Extensions.Logging; using TrackApartments.Contracts.Models; using TrackApartments.User.Domain.Queue.Contracts; using TrackApartments.User.Domain.Sinks.Abstract; using TrackApartments.User.Domain.Sinks.Conditions.Interfaces; namespace TrackApartments.User.Domain.Sinks { public sealed class EmailSink : Sink { private readonly IEmailQueueWriter<Order> writer; private readonly IEmailCondition condition; private readonly ILogger logger; public EmailSink(IEmailQueueWriter<Order> writer, IEmailCondition condition, ILogger logger) { this.writer = writer; this.condition = condition; this.logger = logger; } public override async Task WriteAsync(Order message) { if (condition.IsValid(message)) { await writer.WriteAsync(message); logger.LogDebug("Email message has been added to queue.", message); } else { logger.LogDebug("Email message has been declined.", message, condition); } } } }
using System.Collections.Generic; using System.Threading.Tasks; using EventSourcing.Poc.Messages; namespace EventSourcing.Poc.EventSourcing.Command { public interface ICommandHandler<in TCommand> where TCommand : ICommand { Task<IReadOnlyCollection<IEvent>> Handle(TCommand command); } }
/* Generated by QSI Date: 2020-08-12 Span: 56:1 - 61:14 File: src/postgres/include/nodes/parsenodes.h */ namespace Qsi.PostgreSql.Internal.PG10.Types { internal enum SortByNulls { SORTBY_NULLS_DEFAULT = 0, SORTBY_NULLS_FIRST = 1, SORTBY_NULLS_LAST = 2 } }