text
stringlengths
13
6.01M
namespace MyForum.Web.Extensions { using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using MyForum.Domain; using MyForum.Infrastructure; using MyForum.Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public static class ServiceCollectionExtensions { public static IServiceCollection AddIdentity(this IServiceCollection services) { services .AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = GlobalConstants.PasswordMinLength; options.Password.RequireLowercase = false; options.Password.RequiredUniqueChars = GlobalConstants.UniqueChars; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.SignIn.RequireConfirmedEmail = false; options.User.AllowedUserNameCharacters = GlobalConstants.AllowedChars; options.User.RequireUniqueEmail = true; }) .AddDefaultUI() .AddRoles<IdentityRole>() .AddRoleManager<RoleManager<IdentityRole>>() .AddDefaultTokenProviders() .AddEntityFrameworkStores<MyForumDbContext>(); return services; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrainEngine; namespace TrainConsole { public interface ITrainRunner { void Start(Station startStaion, Station endStaion); void Stop(); } }
using System; using System.Collections.Generic; namespace Core.Entities { public partial class RFreeTip { public int RFreeTipId { get; set; } public DateTime Date { get; set; } public string Description { get; set; } public string Match { get; set; } public string Tip { get; set; } public string Odd { get; set; } public string Result { get; set; } public string WinLose { get; set; } public bool? FirstPage { get; set; } public int? Code { get; set; } } }
using UnityEngine; using System.Collections; using AlmenaraGames; #if UNITY_EDITOR using UnityEditor; #endif namespace AlmenaraGames{ [HelpURL("https://almenaragames.github.io/#CSharpClass:AlmenaraGames.MultiReverbZone")] [AddComponentMenu("Almenara Games/MLPAS/Multi Reverb Zone",1)] [ExecuteInEditMode] [DisallowMultipleComponent] public class MultiReverbZone : MonoBehaviour { [Tooltip("The reverb preset applied to the listeners inside this Multi Reverb Zone")] /// <summary> /// The reverb preset applied to the listeners inside this <see cref="MultiReverbZone"/>. /// </summary> public AudioReverbPreset ReverbPreset=AudioReverbPreset.Generic; [Tooltip("The shape of the collider that this Multi Reverb Zone will going to use")] /// <summary> /// The shape of the collider that this <see cref="MultiReverbZone"/> will going to use. /// </summary> public ZoneType shape=ZoneType.Sphere; [Tooltip("The order of this Multi Reverb Zone, useful when placing a Multi Reverb Zone inside of another (Higher values stays on top)")] /// <summary> /// The order of this <see cref="MultiReverbZone"/>, useful when placing a <see cref="MultiReverbZone"/> inside of another (Higher values stays on top). /// </summary> public int order=0; public enum ZoneType { Sphere, Box } [HideInInspector] public Collider col; BoxCollider boxCol; SphereCollider sphereCol; Vector3 center; Vector3 size; float radius; #if UNITY_EDITOR bool added=false; #endif private bool isApplicationQuitting = false; void Awake() { if (Application.isPlaying) { col = GetComponent<Collider> (); boxCol = col as BoxCollider; sphereCol = col as SphereCollider; if (shape == ZoneType.Box) { size = boxCol.size; center = boxCol.center; boxCol.size = Vector3.zero; boxCol.center = new Vector3(-9999,9999,-9999); } if (shape == ZoneType.Sphere) { radius = sphereCol.radius; center = sphereCol.center; sphereCol.radius = 0f; sphereCol.center = new Vector3(-9999,9999,-9999); } if (col != null) { col.isTrigger = true; col.enabled = true; } } else { #if UNITY_EDITOR if (!added && GetComponent<Collider> () != null && Selection.activeObject==gameObject && GetComponents<MultiReverbZone> ().Length==1) { Event e = Event.current; if(e.commandName == "Duplicate"){ return; } if (!EditorUtility.DisplayDialog("Are you sure to Add this Component?", "The Multi Reverb Zone Component will remove any Collider that exists in this Game Object", "Add", "Cancel")) { DestroyImmediate (this); return; } } added = true; #endif UpdateCollider (); } } void OnApplicationQuit () { isApplicationQuitting = true; } void OnDestroy() { if (isApplicationQuitting || Application.isPlaying) return; } void OnDisable() { if (!Application.isPlaying) return; if (isApplicationQuitting) return; if (MultiPoolAudioSystem.audioManager != null && MultiPoolAudioSystem.audioManager.reverbZones != null) { MultiPoolAudioSystem.audioManager.reverbZones.Remove (this); MultiPoolAudioSystem.audioManager.reverbZonesCount--; } MultiAudioManager.Instance.reverbZones.Sort((p1,p2)=>p1.order.CompareTo(p2.order)); } void OnEnable() { if (!Application.isPlaying) return; if (MultiPoolAudioSystem.audioManager != null) { MultiPoolAudioSystem.audioManager.reverbZones.Add (this); MultiPoolAudioSystem.audioManager.reverbZonesCount++; } else { MultiAudioManager.Instance.reverbZones.Add (this); MultiPoolAudioSystem.audioManager.reverbZonesCount++; } MultiAudioManager.Instance.reverbZones.Sort((p1,p2)=>p1.order.CompareTo(p2.order)); } void UpdateCollider() { if (shape == ZoneType.Box && (GetComponent<BoxCollider> () == null || GetComponents<Collider>().Length>1)) { foreach (var item in GetComponents<Collider>()) { DestroyImmediate (item); } col = gameObject.AddComponent<BoxCollider> (); } if (shape == ZoneType.Sphere && (GetComponent<SphereCollider> () == null || GetComponents<Collider>().Length>1)) { foreach (var item in GetComponents<Collider>()) { DestroyImmediate (item); } col = gameObject.AddComponent<SphereCollider> (); } boxCol = col as BoxCollider; sphereCol = col as SphereCollider; } void Update() { if (Application.isPlaying) return; #if UNITY_2017_1_OR_NEWER UpdateCollider (); #else shape=ZoneType.Sphere; UpdateCollider(); #endif if (shape == ZoneType.Box && boxCol!=null) { size = boxCol.size; center = boxCol.center; } if (shape == ZoneType.Sphere && sphereCol!=null) { radius = sphereCol.radius; center = sphereCol.center; } if (col != null) { col.isTrigger = true; col.enabled = true; } if (ReverbPreset == AudioReverbPreset.User) ReverbPreset = AudioReverbPreset.Generic; if (col == null) { col = GetComponent<Collider> (); } } public bool IsInside(Vector3 position) { if (shape == ZoneType.Box) { boxCol.size = size; boxCol.center = center; } if (shape == ZoneType.Sphere) { sphereCol.radius = radius; sphereCol.center = center; } #if UNITY_2017_1_OR_NEWER Vector3 closestPoint = col.ClosestPoint(position); #else Vector3 thisPosition = transform.position+transform.TransformVector(center); Vector3 directionToPosition = new Vector3 (position.x - thisPosition.x, position.y - thisPosition.y, position.z - thisPosition.z); float distance = directionToPosition.magnitude; #endif if (shape == ZoneType.Box) { size = boxCol.size; center = boxCol.center; boxCol.size = Vector3.zero; boxCol.center = new Vector3(-9999,9999,-9999); } if (shape == ZoneType.Sphere) { radius = sphereCol.radius; center = sphereCol.center; sphereCol.radius = 0f; sphereCol.center = new Vector3(-9999,9999,-9999); } #if UNITY_2017_1_OR_NEWER if (closestPoint==position) { return true; } #else if (distance<=radius*GetSphereSize(transform.localScale)) { return true; } #endif return false; } void OnDrawGizmos() { Gizmos.DrawIcon (transform.position+transform.TransformVector(center), "AlmenaraGames/MLPAS/ReverbZoneNoCenterIco"); if (!Application.isEditor || col==null) return; #if UNITY_EDITOR if (Selection.activeGameObject == gameObject && !Application.isPlaying) return; #endif Color blueGizmos = new Color (0.69f, 0.89f, 1f, 1); Gizmos.color = blueGizmos; #if UNITY_EDITOR if (shape == ZoneType.Sphere) { //SphereCollider volume = col as SphereCollider; Matrix4x4 oldHandleMatrix = Handles.matrix; Color oldHandleColor = Handles.color; //Matrix4x4 localMatrix = Matrix4x4.TRS(volume.transform.position,volume.transform.rotation,GetSphereSize(volume.transform.localScale)*Vector3.one); //Handles.matrix = localMatrix; blueGizmos.a = 0.5f; Handles.color = blueGizmos; Vector3 position = transform.position+transform.TransformVector(center); if (Camera.current.orthographic) { Vector3 normal = position - Handles.inverseMatrix.MultiplyVector (Camera.current.transform.forward); float sqrMagnitude = normal.sqrMagnitude; float num0 = radius*GetSphereSize(transform.localScale) * radius*GetSphereSize(transform.localScale); Handles.DrawWireDisc (position - num0 * normal / sqrMagnitude, normal, radius*GetSphereSize(transform.localScale)); } else { Vector3 normal = position - Handles.inverseMatrix.MultiplyPoint (Camera.current.transform.position); float sqrMagnitude = normal.sqrMagnitude; float num0 = radius*GetSphereSize(transform.localScale) * radius*GetSphereSize(transform.localScale); float num1 = num0 * num0 / sqrMagnitude; float num2 = Mathf.Sqrt (num0 - num1); Handles.DrawWireDisc (position - num0 * normal / sqrMagnitude, normal, num2); } Handles.matrix=oldHandleMatrix; Handles.color=oldHandleColor; } #endif if (shape == ZoneType.Box && boxCol!=null) { Gizmos.matrix = Matrix4x4.TRS (transform.position, transform.rotation, transform.localScale); Gizmos.DrawWireCube (center, size); } if (shape == ZoneType.Sphere && sphereCol!=null) { //Gizmos.matrix = Matrix4x4.TRS(transform.position,transform.rotation,transform.localScale); Gizmos.DrawWireSphere (transform.position+transform.TransformVector(center), radius*GetSphereSize(transform.localScale)); } } float GetSphereSize(Vector3 size) { Vector3 absSize = new Vector3 (Mathf.Abs(size.x),Mathf.Abs(size.y),Mathf.Abs(size.z)); if (absSize.x > absSize.y && absSize.x > absSize.z) return size.x; else if (absSize.y > absSize.x && absSize.y > absSize.z) return size.y; else if (absSize.z > absSize.y && absSize.z > absSize.x) return size.z; else return size.x; } void OnDrawGizmosSelected() { Gizmos.DrawIcon (transform.position, "AlmenaraGames/MLPAS/ReverbZoneNoCenterIco"); Gizmos.DrawIcon (transform.position+transform.TransformVector(center), "AlmenaraGames/MLPAS/ReverbZoneIco"); } } #if UNITY_EDITOR [CustomEditor(typeof(MultiReverbZone)), CanEditMultipleObjects] public class ReverbZoneEditor : Editor { SerializedObject reverbZoneObj; private static readonly string[] _dontIncludeMePlaying = new string[]{"m_Script","shape","order"}; #if UNITY_2017_1_OR_NEWER private static readonly string[] _dontIncludeMe = new string[]{"m_Script"}; #else private static readonly string[] _dontIncludeMeOld = new string[]{"m_Script","shape"}; #endif void OnEnable() { reverbZoneObj = new SerializedObject (targets); } public override void OnInspectorGUI() { reverbZoneObj.Update(); #if UNITY_2017_1_OR_NEWER EditorGUILayout.HelpBox("The Reverb Zone Component uses the collider's size and position to know whether a listener is inside of the reverb zone.", MessageType.Info); #else EditorGUILayout.HelpBox("The Reverb Zone Component uses the collider's size and position to know whether a listener is inside of the reverb zone.", MessageType.Info); EditorGUILayout.HelpBox("Box Shape is only available for Unity 2017.1 and newer versions.", MessageType.Info); #endif if ((target as MultiReverbZone).ReverbPreset == AudioReverbPreset.User) { (target as MultiReverbZone).ReverbPreset = AudioReverbPreset.Off; } if (!Application.isPlaying) { #if UNITY_2017_1_OR_NEWER DrawPropertiesExcluding (reverbZoneObj, _dontIncludeMe); #else DrawPropertiesExcluding (reverbZoneObj, _dontIncludeMeOld); EditorGUILayout.LabelField ("Shape", (target as MultiReverbZone).shape.ToString ()); #endif } else { DrawPropertiesExcluding (reverbZoneObj, _dontIncludeMePlaying); EditorGUILayout.LabelField ("Shape", (target as MultiReverbZone).shape.ToString ()); EditorGUILayout.LabelField ("Order", (target as MultiReverbZone).order.ToString ()); } reverbZoneObj.ApplyModifiedProperties(); } } #endif }
using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Stagehand; using UnityEngine; using Debug = UnityEngine.Debug; public class Sandbox : MonoBehaviour { public class Config { public readonly Queue<long> times = new Queue<long>(); public void Time() { times.Enqueue(Stopwatch.GetTimestamp()); } public string Times() { return string.Join(", ", times.Select(x => x.ToString()).ToArray()); } } public static IEnumerator Sleep(float durationInSeconds) { var endTime = Stopwatch.GetTimestamp() + (long) (10000000L * durationInSeconds); while (Stopwatch.GetTimestamp() < endTime) yield return null; } private class Main { public string MainName; } private class A { public string str = "A"; } private class B { public string str = "B"; } private class C { public string str = "C"; } private class D { public string str = "D"; } private class E { public string str = "E"; } private class F { public string str = "F"; } static Sandbox() { IEnumerator _noop() { yield break; } IEnumerator _log(string message) { Debug.Log(message); yield break; } IEnumerator _watchFile(string filename) { yield return _log($"beg_watchFile({filename})"); yield return Sleep(0.1f); yield return _log($"end_watchFile({filename})"); } IEnumerator _downloadUri(string uri) { yield return _log($"beg_downloadUri({uri})"); yield return _watchFile(uri); yield return _log($"end_downloadUri({uri})"); } IEnumerator _skipJsonWhitespace(IEnumerator<char> reader) { do { switch (reader.Current) { case ' ': case '\t': case '\n': case '\r': #if STAGEHAND_VERY_VERBOSE Debug.Log("WHITESPACE"); #endif break; default: yield break; } } while (reader.MoveNext()); } string _parseJsonString(IEnumerator<char> reader) { var stringBuilder = new StringBuilder(); reader.MoveNext(); do { switch (reader.Current) { case '"': #if STAGEHAND_VERY_VERBOSE Debug.Log("STRING_END: \""); #endif reader.MoveNext(); return stringBuilder.ToString(); case '\\': reader.MoveNext(); #if STAGEHAND_VERY_VERBOSE Debug.Log($"STRING_LITERAL: \\{reader.Current}"); #endif stringBuilder.Append(reader.Current); break; default: #if STAGEHAND_VERY_VERBOSE Debug.Log($"STRING: {reader.Current}"); #endif stringBuilder.Append(reader.Current); break; } } while (reader.MoveNext()); return null; } IEnumerator<object> _parseJsonObject(IEnumerator<char> reader) { do { yield return _skipJsonWhitespace(reader); switch (reader.Current) { case '"': #if STAGEHAND_VERY_VERBOSE Debug.Log("STRING_START: \""); #endif yield return _parseJsonString(reader); yield return _skipJsonWhitespace(reader); if (reader.Current != ':') throw new SyntaxErrorException($"Suspicious character encountered while looking for your colon: {reader.Current}"); #if STAGEHAND_VERY_VERBOSE Debug.Log("OBJECT_PAIR: :"); #endif reader.MoveNext(); yield return _parseJsonValue(reader); break; case ',': #if STAGEHAND_VERY_VERBOSE Debug.Log("OBJECT_ELEMENT"); #endif break; case '}': #if STAGEHAND_VERY_VERBOSE Debug.Log("OBJECT_END: }"); #endif reader.MoveNext(); yield break; } } while (reader.MoveNext()); } IEnumerator<object> _parseJsonValue(IEnumerator<char> reader) { yield return _skipJsonWhitespace(reader); switch (reader.Current) { case '"': #if STAGEHAND_VERY_VERBOSE Debug.Log("STRING_START: \""); #endif yield return _parseJsonString(reader); yield break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // TODO: I really dislike the redundancy of double checking, here and inside _parseJsonNumber. #if STAGEHAND_VERY_VERBOSE Debug.Log($"NUMBER_START: {reader.Current}"); #endif yield return _parseJsonNumber(reader); yield break; case '{': reader.MoveNext(); #if STAGEHAND_VERY_VERBOSE Debug.Log("OBJECT_START: {"); #endif yield return _parseJsonObject(reader); yield break; case '[': reader.MoveNext(); #if STAGEHAND_VERY_VERBOSE Debug.Log("ARRAY_START: ["); #endif yield return _parseJsonArray(reader); yield break; case 't': #if STAGEHAND_VERY_VERBOSE Debug.Log("TRUE_START"); #endif reader.MoveNext(); if (reader.Current == 'r') reader.MoveNext(); else throw new SyntaxErrorException($"Expected the 'r' in 'true' but found the following instead: {reader.Current}"); if (reader.Current == 'u') reader.MoveNext(); else throw new SyntaxErrorException($"Expected the 'u' in 'true' but found the following instead: {reader.Current}"); if (reader.Current != 'e') throw new SyntaxErrorException($"Expected the 'e' in 'true' but found the following instead: {reader.Current}"); #if STAGEHAND_VERY_VERBOSE Debug.Log("TRUE_END"); #endif yield break; case 'f': #if STAGEHAND_VERY_VERBOSE Debug.Log("FALSE_START"); #endif reader.MoveNext(); if (reader.Current == 'a') reader.MoveNext(); else throw new SyntaxErrorException($"Expected the 'a' in 'false' but found the following instead: {reader.Current}"); if (reader.Current == 'l') reader.MoveNext(); else throw new SyntaxErrorException($"Expected the 'l' in 'false' but found the following instead: {reader.Current}"); if (reader.Current == 's') reader.MoveNext(); else throw new SyntaxErrorException($"Expected the 's' in 'false' but found the following instead: {reader.Current}"); if (reader.Current != 'e') throw new SyntaxErrorException($"Expected the 'e' in 'false' but found the following instead: {reader.Current}"); #if STAGEHAND_VERY_VERBOSE Debug.Log("FALSE_END"); #endif yield break; case 'n': #if STAGEHAND_VERY_VERBOSE Debug.Log("NULL_START"); #endif reader.MoveNext(); if (reader.Current == 'u') reader.MoveNext(); else throw new SyntaxErrorException($"Expected the 'u' in 'null' but found the following instead: {reader.Current}"); if (reader.Current == 'l') reader.MoveNext(); else throw new SyntaxErrorException($"Expected the 'l' in 'null' but found the following instead: {reader.Current}"); if (reader.Current != 'l') throw new SyntaxErrorException($"Expected the 'l' in 'null' but found the following instead: {reader.Current}"); #if STAGEHAND_VERY_VERBOSE Debug.Log("NULL_END"); #endif yield break; default: throw new SyntaxErrorException($"Bad character found in your stream: {reader.Current}"); } } IEnumerator<object> _parseJsonArray(IEnumerator<char> reader) { do { yield return _skipJsonWhitespace(reader); if (reader.Current == ']') { reader.MoveNext(); #if STAGEHAND_VERY_VERBOSE Debug.Log("ARRAY_END: ]"); #endif yield break; } yield return _parseJsonValue(reader); #if STAGEHAND_VERY_VERBOSE if (reader.Current == ',') Debug.Log("ARRAY_ELEMENT"); #endif } while (reader.MoveNext()); } object _parseJsonNumber(IEnumerator<char> reader) { // TODO: Switch to stdlib implementation for this. // Negative? var negative = reader.Current == '-' ? -1 : 1; if (negative == -1) reader.MoveNext(); // Integer Portion long value = 0, multiplier = 1; do { switch (reader.Current) { case '0': break; case '1': value += multiplier; break; case '2': value += 2 * multiplier; break; case '3': value += 3 * multiplier; break; case '4': value += 4 * multiplier; break; case '5': value += 5 * multiplier; break; case '6': value += 6 * multiplier; break; case '7': value += 7 * multiplier; break; case '8': value += 8 * multiplier; break; case '9': value += 9 * multiplier; break; case '.': reader.MoveNext(); // Double! double dblValue = negative * value, dblDivider = 10.0; do { switch (reader.Current) { case '0': break; case '1': dblValue += 1.0 / dblDivider; break; case '2': dblValue += 2.0 / dblDivider; break; case '3': dblValue += 3.0 / dblDivider; break; case '4': dblValue += 4.0 / dblDivider; break; case '5': dblValue += 5.0 / dblDivider; break; case '6': dblValue += 6.0 / dblDivider; break; case '7': dblValue += 7.0 / dblDivider; break; case '8': dblValue += 8.0 / dblDivider; break; case '9': dblValue += 9.0 / dblDivider; break; case 'e': case 'E': goto PARSE_EXPONENT; default: #if STAGEHAND_VERY_VERBOSE Debug.Log($"NUMBER_END: {dblValue}"); #endif return dblValue; } dblDivider *= 10; } while (reader.MoveNext()); return dblValue; case 'e': case 'E': PARSE_EXPONENT: #if STAGEHAND_VERY_VERBOSE Debug.Log("NUMBER: ^"); #endif // TODO: Exponent! break; default: #if STAGEHAND_VERY_VERBOSE Debug.Log($"NUMBER_END: {negative * value}"); #endif return negative * value; } multiplier *= 10; } while (reader.MoveNext()); return negative * value; } IEnumerator<object> _parseJson(IEnumerator<char> reader) { while (reader.MoveNext()) { yield return _skipJsonWhitespace(reader); // If you find yourself, // Reading this code, // It's probably because, // You've not linted your JSON. switch (reader.Current) { case '{': reader.MoveNext(); #if STAGEHAND_VERY_VERBOSE Debug.Log("OBJECT_START: {"); #endif yield return _parseJsonObject(reader); break; // TODO: Technically this isn't legal, but I refuse to enforce arbitrary/meaningless standards. case '[': reader.MoveNext(); #if STAGEHAND_VERY_VERBOSE Debug.Log("ARRAY_START: ["); #endif yield return _parseJsonArray(reader); break; default: throw new SyntaxErrorException($"Crazy character spotted in your JSON: {reader.Current}"); } } } IEnumerator _deserializeInto<T>(T target, IEnumerator parser) { yield return parser; } IEnumerator<char> _readFile(string filename) { using (var sr = new StreamReader(filename)) { while (!sr.EndOfStream) { // Strategy #1: One Character at a Time /*foreach (var character in sr.ReadLine()) { yield return character; }*/ // Strategy #2: One Line at a Time //yield return new StageReader(sr.ReadLine()); // TODO: Strategy #3: Block Based Reads // Strategy #4: The Entire Stream foreach (var character in sr.ReadToEnd()) { yield return character; } yield break; } } } // MonoBehaviour //Stage<MonoBehaviour>.Hand((ref MonoBehaviour monoBehaviour) => null); // Roots /*var localConfig = new Config(); Stage<Config>.Hand(ref localConfig); Stage<Config>.Hand((ref Config config) => _deserializeInto(config, _parseJson(_readFile("Assets/Tests/JSON/backstage.json")))); Stage<Main>.Hand((ref Main main, ref Config config) => _readFile("Assets/Tests/JSON/backstage.json"));*/ // Relationships //Stage<Config>.Hand((ref Config config) => _log("1")); //Stage<Main>.Hand((ref Main main) => _log("2")); //Stage<Main>.Hand((ref Main main, ref Config config) => _log("3")); //Stage<Sandbox>.Hand((ref Sandbox sandbox) => _log("4")); //Stage<Sandbox>.Hand((ref Sandbox sandbox, ref Config config) => _log("5")); //Stage<Sandbox>.Hand((ref Sandbox sandbox, ref Main main) => _log("6")); //Stage<IEnumerator>.Hand((ref IEnumerator enumeratorA, ref IEnumerator enumeratorB) => _log("7")); //Stage<Main>.Hand((ref Main main, ref IEnumerator enumerator) => _log("8")); //Stage<IEnumerator>.Hand((ref IEnumerator enumerator, ref Config config) => _log("9")); // Initial Values { var a = new A(); var b = new B(); var c = new C(); var d = new D(); var e = new E(); var f = new F(); Stage<A>.Hand(ref a); Stage<B>.Hand(ref b); Stage<C>.Hand(ref c); Stage<D>.Hand(ref d); Stage<E>.Hand(ref e); Stage<F>.Hand(ref f); } // Relationships Stage<A>.Hand((ref A a) => _log(a.str)); Stage<B>.Hand((ref B b) => _log(b.str)); Stage<C>.Hand((ref C c, ref B b) => _log($"{c.str}, {b.str}")); Stage<D>.Hand((ref D d) => _log(d.str)); Stage<E>.Hand((ref E e, ref D d) => _log($"{e.str}, {d.str}")); Stage<F>.Hand((ref F f, ref E e) => _log($"{f.str}, {e.str}")); // Config /*IEnumerator _parseConfig(Config cfg) { cfg.Time(Stopwatch.GetTimestamp()); yield return _log($"_parseConfig({cfg.Times()})"); } var localConfig = new Config(); Stage<Config>.Hand(ref localConfig); Stage<Config>.Hand(_parseConfig(localConfig)); Stage<Config>.Hand((ref Config config) => _parseConfig(config));*/ // Main /*IEnumerator _runMain(Main main, Config config) { Debug.Log($"main:{config.Times()}"); yield return Sleep(0.1f); Debug.Log(main.MainName = "MAIN"); } var localMain = new Main(); Stage<Main>.Hand(ref localMain); Stage<Main>.Hand((ref Main main, ref Config config) => _runMain(main, config));*/ // 1. Load Config /*var _config = new Config(); IEnumerator _readConfig(Config config) { config.ConfigName = "Config Read"; yield break; } Stagehand<Config>.Stage(Stagehand.ConsecutiveParallelJobs( _log<Config>($"1"), _nestedLog<Main>($"2", $"3"), Stagehand.ConsecutiveJobs( Stagehand.Sleep(0.2f), _log<Config>($"7"), _nestedLog<Main>($"8", $"9") ), Stagehand.ConsecutiveJobs( Stagehand.Sleep(0.1f), _log<Config>($"4"), _nestedLog<Main>($"5", $"6") ), Stagehand.ConsecutiveJobs(Stagehand.Sleep(0.3f), _readConfig(_config)) )); // 2. Thread Affinity Stagehand<IThreadMain>.Stage<MonoBehaviour>(_log<MonoBehaviour>("Main Thread #1")); Stagehand<MonoBehaviour>.Stage(_nestedLog<MonoBehaviour>("Main Thread #2", "Main Thread #3: Nested!")); // 3. Load Main IEnumerator _processConfig(Config config) { _log($"_processConfig Started: {config.ConfigName}"); while (config.ConfigName == null) { yield return null; } _log($"_processConfig Finished: {config.ConfigName}"); } Stagehand<Config>.Stage<Main>(_processConfig(_config));*/ } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using SRT_Project.Forms; namespace SRT_Project.Views { public partial class JobList : DevExpress.XtraEditors.XtraUserControl { public JobList() { InitializeComponent(); } private void btnThem_Click(object sender, EventArgs e) { NewJob nJ = new NewJob(); nJ.Show(); } } }
using System.Threading.Tasks; using Otiport.API.Contract.Request.Users; using Otiport.API.Contract.Response.Users; namespace Otiport.API.Services { public interface IUserService { Task<CreateUserResponse> CreateUserAsync(CreateUserRequest request); Task<LoginResponse> LoginAsync(LoginRequest request); } }
using System; using System.Threading; using BootLoader.Impl; using Timer = BootLoader.Impl.Timer; namespace ForTesting { static class Program { static void Main() { var timer = new Timer(); timer.Elapsed += timer_Elapsed; timer.Start(1000); var worker = new Worker(); var thread = new Thread(worker.Run); thread.Start(); Console.ReadKey(); } static void timer_Elapsed(object sender, TimerEventArg e) { var threadName = Thread.CurrentThread.ManagedThreadId; Console.WriteLine(@"is main therad " + threadName); } } public class Worker { private Timer _timer; private readonly AutoResetEvent _waiter = new AutoResetEvent(false); private int _number; public void Run() { _timer = new Timer(); _number = 0; _timer.Elapsed += delegate { var threadName = Thread.CurrentThread.ManagedThreadId; Console.WriteLine(@"Number " + threadName + @" " +_number); ++_number; if (_number >= 10) { Stop(); } }; _timer.Start(1000); _waiter.WaitOne(); } public void Stop() { _waiter.Set(); _timer.Stop(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FloorHoleShaderFollow : MonoBehaviour { private GameObject player; void Start () { player = GameObject.Find("Player"); } void FixedUpdate () { Vector4 pos = player.gameObject.transform.position; pos.w = pos.y * 10f; pos.y = 0; gameObject.GetComponent<Renderer>().material.SetVector("_HolePos", pos); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace PaperPlane.API.ProtocolStack.Security { public static class ByteOperations { public static byte[] NoiseArray(this byte[] array) { var random = RandomNumberGenerator.Create(); random.GetBytes(array); return array; } public static Span<byte> Cut(this byte[] data, int start, int count = 0) { return count == 0 ? new Span<byte>(data).Slice(start) : new Span<byte>(data).Slice(start, count); } public static Span<byte> GetLowestBytes(this byte[] data, int count) { return data.Cut(data.Length - count); } public static byte[] ComputeSHAHash(this byte[] data) { using (var sha = SHA1.Create()) return sha.ComputeHash(data); } public static void Align(this MemoryStream stream, int size) { if (stream.Position % size != 0) { var data = new byte[size - stream.Position % size].NoiseArray(); stream.Write(data, 0, data.Length); } } public static byte[] PackWithHash(this byte[] data, int align = 0) { var dataSHA = data.ComputeSHAHash(); using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(dataSHA); bw.Write(data); if (align > 0) ms.Align(align); } return ms.ToArray(); } } public static byte[] Align(this byte[] array, int size) { if (array.Length % size != 0) { return array.Concat(new byte[size - array.Length % size].NoiseArray()).ToArray(); } return array; } public static bool ByteEquals(this byte[] src, byte[] target) { return src.Zip(target, (s, t) => s - t).Sum() == 0; } public static byte[] XOR(this byte[] first, byte[] second) { if (first.Length != second.Length) throw new ArgumentException(); var buffer = new byte[first.Length]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(first[i] ^ second[i]); } return buffer; } public static byte[] ToBytes(this string s) { var coder = new System.Text.UTF8Encoding(); return coder.GetBytes(s); } } }
using System; namespace TryHardForum.Models { // Не понимаю, зачем эта модель, если есть почти с таким же названием, но в директории ViewModels??? // Срочно перекопать весь код! public class PostReply { public int Id { get; set; } public string Content { get; set; } public DateTime Created { get; set; } public string AppUserId { get; set; } public virtual AppUser AppUser { get; set; } public int PostId { get; set; } public virtual Post Post { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ZavenDotNetInterview.Abstract; using ZavenDotNetInterview.App.Models; namespace ZavenDotNetInterview.Data.Repository { public class LogRepository : Repository<Log>, ILogRepository { public LogRepository(DbContext context) : base(context) { } public async Task AddAsync(Log log) { await Context.AddAsync(log); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HotelManagement.Setting; using System.Data; using System.Data.SqlClient; namespace HotelManagement.DataObject { public class PhongData { DataService ds = new DataService(); public DataTable LayMaPhong() { SqlCommand cmd = new SqlCommand("Select * From PHONG"); ds.Load(cmd); return ds; } public DataTable LayDataTheoMaLoaiPhong(string id) { SqlCommand cmd = new SqlCommand("select * from PHONG where MaTinhTrang = @id"); cmd.Parameters.Add("id", SqlDbType.VarChar).Value = id; ds.Load(cmd); return ds; } public DataTable LayMaLoaiPhong(string id) { SqlCommand cmd = new SqlCommand("select * from PHONG where MaPhong = @id"); cmd.Parameters.Add("id", SqlDbType.VarChar).Value = id; ds.Load(cmd); return ds; } public void UpdateTinhTrangPhong(string maPhong, string maTinhTrang) { SqlCommand cmd = new SqlCommand("Update PHONG Set MaTinhTrang = @maTinhTrang where MaPhong = @maPhong"); cmd.Parameters.Add("maPhong", SqlDbType.VarChar).Value = maPhong; cmd.Parameters.Add("maTinhTrang", SqlDbType.VarChar).Value = maTinhTrang; ds.Load(cmd); } public DataRow NewRow() { return this.ds.NewRow(); } public void Add(DataRow row) { this.ds.Rows.Add(row); } public bool Save() { return this.ds.ExecuteNoneQuery() > 0; } } }
using DAL.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL.Repositories { public class ClientRepository { private TurpialPOSDbContext _context; public ClientRepository() { _context = new TurpialPOSDbContext(); } public Client Add(Client client) { _context.Client.Add(client); _context.SaveChanges(); return client; } public Client Edit(Client clientEdited) { var client = _context.Client.Where(p => p.Id == clientEdited.Id).FirstOrDefault(); if (client != null) { client.Name = clientEdited.Name; client.Address = clientEdited.Address; client.ContactName = clientEdited.ContactName; client.ContactPhone = clientEdited.ContactPhone; client.ContactEmail = clientEdited.ContactEmail; client.LegalId = clientEdited.LegalId; client.Notes = clientEdited.Notes; _context.Entry(client).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); } return client; } public IList<Client> GetAll(int storeId) { return _context.Client.Where(c => c.IsActive && c.StoreId == storeId).ToList(); } public Client Get(int id) { return _context.Client.Where(c => c.Id == id).FirstOrDefault(); } public void Delete(int id) { var client = _context.Client.Where(p => p.Id == id).FirstOrDefault(); if (client != null) { client.Deactivate(); _context.Entry(client).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; //TODO: Add other using statements here namespace com.Sconit.Entity.MRP.TRANS { [Serializable] public partial class MrpShipPlanGroup : EntityBase { #region O/R Mapping Properties public int Id { get; set; } [Display(Name = "ShipPlanGroup_ProductLine", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public string Flow { get; set; } [Display(Name = "ShipPlanGroup_Item", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public string Item { get; set; } [Display(Name = "ShipPlanGroup_Qty", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public double Qty { get; set; } [Display(Name = "ShipPlanGroup_LocationFrom", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public string LocationFrom { get; set; } [Display(Name = "ShipPlanGroup_LocationTo", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public string LocationTo { get; set; } [Display(Name = "ShipPlanGroup_WindowTime", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public DateTime WindowTime { get; set; } [Display(Name = "ShipPlanGroup_StartTime", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public DateTime StartTime { get; set; } [Display(Name = "ShipPlanGroup_OrderType", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public com.Sconit.CodeMaster.OrderType OrderType { get; set; } public double ShipQty { get; set; } public bool IsDiscontinueItem { get; set; } [Display(Name = "ShipPlanGroup_PlanVersion", ResourceType = typeof(Resources.MRP.ShipPlanGroup))] public DateTime PlanVersion { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { MrpShipPlanGroup another = obj as MrpShipPlanGroup; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using System; using System.Linq; namespace LINQ_Join_MUL { class Program { static void Main(string[] args) { var JoinMultipleDSUsingQS = (//Data Source1 from emp in Employee.GetAllEmployees() //Joining with Address Data Source (Data Source2) join adrs in Address.GetAllAddresses() on emp.AddressId equals adrs.ID //Joining with Department Data Source (Data Source3) join dept in Department.GetAllDepartments() on emp.DepartmentId equals dept.ID //Projecting the result set select new { ID = emp.ID, EmployeeName = emp.Name, DepartmentName = dept.Name, AddressLine = adrs.AddressLine }).ToList(); foreach (var employee in JoinMultipleDSUsingQS) { Console.WriteLine($"ID = {employee.ID}, Name = {employee.EmployeeName}, Department = {employee.DepartmentName}, Addres = {employee.AddressLine}"); } Console.ReadLine(); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class Inventory : MonoBehaviour { public static Inventory current; private Canvas screen; private bool display = false; public int dirtBlocks = 0; private List<Item> itemList = new List<Item>(); private GameObject[] inventoryFields; // Use this for initialization void Awake(){ current = this; screen = GetComponent<Canvas>(); screen.enabled = display; inventoryFields = GameObject.FindGameObjectsWithTag("InventorySlot"); itemList.Add(new Item(0)); itemList.Add(new Item(1)); itemList.Add(new Item(2)); itemList.Add(new Item(3)); itemList.Add(new Item(4)); itemList.Add(new Item(5)); itemList.Add(new Item(6)); itemList.Add(new Item(7)); var i = 0; foreach (Item item in itemList) { inventoryFields[i].GetComponent<Text>().text = item.name; i++; } } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D target){ if(target.gameObject.tag == "Dirt"){ incrDirt(); } } public int getAmountDirt(){ return dirtBlocks; } public void incrDirt(){ dirtBlocks++; } public void toggleInv(){ display = !display; screen.enabled = display; } }
using System; using UnityEngine; using UnityEngine.UI; using LuaInterface; public sealed class CSBridge { public static Transform s_uiRoot = null; public static Transform s_sceneRoot = null; public static Transform UIRoot() { return s_uiRoot; } public static Transform SceneRoot() { return s_sceneRoot; } public static int s_recvProtoId = 0; public static LuaByteBuffer s_recvBytes = null; public static int s_sendProtoId = 0; public static LuaByteBuffer s_sendBytes = null; public static bool SendMsg() { return NetController.Instance.SendMsgToGate((Cmd.EMessageID)s_sendProtoId, s_sendBytes.buffer); } public static bool SendMsgToCross() { return NetController.Instance.SendMsgToCross((Cmd.EMessageID)s_sendProtoId, s_sendBytes.buffer); } public static LuaTable AddComponent(GameObject go_, string luaFileName_) { LuaBehaviour.LuaFileName = luaFileName_; return go_.AddComponent<LuaBehaviour>().LuaTable(); } public static void AddClick(Button btn_, LuaFunction func_) { if (btn_ == null || func_ == null) { Debug.LogWarning("addclick failed,btn or func is null"); return; } btn_.onClick.AddListener(delegate() { func_.Call(btn_.gameObject); }); } public static void LoadLevel(string levelName_) { InitLoadingController.setNextScene(levelName_); UnityEngine.SceneManagement.SceneManager.LoadScene("LoadingScene", UnityEngine.SceneManagement.LoadSceneMode.Single); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Knockback : MonoBehaviour { public float thrust; //knockback amount public float knockTime; //time since knockback public float damage; //damage dealth by knockback private void OnTriggerEnter2D(Collider2D other) //If enemy or player attacks one another, move rigidbody by adding thrust and impulse { if (other.gameObject.CompareTag("enemy") || other.gameObject.CompareTag("Player")) { Rigidbody2D hit = other.GetComponent<Rigidbody2D>(); if (hit != null) { Vector2 difference = hit.transform.position - transform.position; difference = difference.normalized * thrust; hit.AddForce(difference, ForceMode2D.Impulse); //If enemy gets knocked back by player attacking change state and deal damage if (other.gameObject.CompareTag("enemy") && other.isTrigger) { hit.GetComponent<EnemyAI>().currentState = EnemyState.stagger; other.GetComponent<EnemyAI>().Knock(hit, knockTime, damage); } //If player gets knocked back by enemy attacking change state and deal damage if (other.gameObject.CompareTag("Player")) { if (other.GetComponent<PlayerController>().currentState != PlayerState.stagger) { hit.GetComponent<PlayerController>().currentState = PlayerState.stagger; other.GetComponent<PlayerController>().Knock(knockTime, damage); } } } } } }
using System; using System.Collections.Generic; using System.Text; namespace MyFirstGame { class Enemy { protected Position position; protected Texture texture; protected Enemy(Position position, Texture texture) { this.position = position; this.texture = texture; } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using CIPMSBC; public partial class Administration_ChangePwd : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Set Page Heading Label lbl = (Label)this.Master.FindControl("lblPageHeading"); lbl.Text = "Change Password"; lblMsg.Text = ""; } protected void btnSubmit_Click(object sender, EventArgs e) { UserAdministration objUsrAdmin = new UserAdministration(); objUsrAdmin.UserId = Convert.ToUInt16(Session["UsrID"]); objUsrAdmin.OldPassword = txtOldPwd.Text; objUsrAdmin.Password = txtNewPwd.Text; try { string strMsg; strMsg = objUsrAdmin.ChangePassword(); lblMsg.Text = strMsg; } catch (Exception ex) { throw ex; } finally { objUsrAdmin = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace BOB2 { abstract class PhysicalObject : MovingObject { protected bool visible = true; public PhysicalObject(Texture2D _texture, Vector2 _vector, Vector2 _hastighet, float _scale) : base(_texture, _vector, _hastighet, _scale) { } /// <summary> /// Kollar om två objekt kolliderar med varandra /// </summary> /// <param name="p">Objekt av typen physicalobject</param> /// <returns>Om objekten har kolliderat</returns> public virtual Boolean checkCollision(PhysicalObject p) { try { if (p == null) { return false; } Rectangle r1 = new Rectangle(Convert.ToInt32(getVector().X), Convert.ToInt32(getVector().Y), Convert.ToInt32(getWidth()), Convert.ToInt32(getHeight())); Rectangle r2 = new Rectangle(Convert.ToInt32(p.getVector().X), Convert.ToInt32(p.getVector().Y), Convert.ToInt32(p.getWidth()), Convert.ToInt32(p.getHeight())); return r1.Intersects(r2); }catch(Exception e) { return false; } } public override void Update() { throw new NotImplementedException(); } /// <summary> /// Höjden på /// </summary> /// <returns>Verkliga höjden på föremålet</returns> public override float getHeight() { return base.getHeight() * scale; } /// <summary> /// /// </summary> /// <returns>Verkliga bredden på föremålet</returns> public override float getWidth() { return base.getWidth() * scale; } /// <summary> /// Ritar föremålet så länge den är synlig /// </summary> /// <param name="sb"></param> public override void drawObject(SpriteBatch sb) { if(!visible) { return; } sb.Draw(texture, vector, null, Color.White, 0, new Vector2(0, 0), scale, SpriteEffects.None, 0); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SpawnPoints : MonoBehaviour { [SerializeField] private List<Wave> waves = new List<Wave>(); public GameObject destination; public GameControler controler; public int actualWave = 0; [Header("UI")] public Text TimeText; public Text rundCount; public float deltaTime = 0.1f; private float time; // Use this for initialization void Start () { waves = controler.wawes; time = 2; StartCoroutine(StartRund()); } IEnumerator StartRund() { for(int z=0; z <= 5;) { if (actualWave < waves.Count && controler.GetFinish() == false) { if (time <= 0) { controler.money += 150; yield return StartCoroutine(CreateWave()); } time = time - deltaTime; yield return new WaitForSeconds(deltaTime); } else { destination.GetComponent<Finish>().FinishGame(); z = 6; time = 0; } } } IEnumerator CreateWave() { if(actualWave >= waves.Count) { destination.GetComponent<Finish>().FinishGame(); } else { for (int z = 0; z <= waves[actualWave].howManyMonster; z++) { CreateMonster(waves[actualWave].GetMonster()); time = controler.time; yield return new WaitForSeconds(0.2f); } time = controler.time; actualWave++; } } void CreateMonster(GameObject Prefab) { GameObject monsterObject = Instantiate(Prefab, transform.position, transform.rotation) as GameObject; monsterObject.transform.SetParent(transform); Monster monsterScripts = monsterObject.GetComponent<Monster>(); monsterScripts.SetDescination(destination); } // Update is called once per frame void Update () { rundCount.text = "Round: " + (actualWave).ToString(); TimeText.text = "Time to next wave: " + time.ToString("F2"); } public void NextRound() { time = 0; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace Nailhang.Display.Models { public class IndexModel { public IndexModel() { AllModules = new ModuleModel[] { }; Modules = new ModuleModel[] { }; RootNamespaces = new string[] { }; } public IEnumerable<ModuleModel> Modules { get; set; } public IEnumerable<ModuleModel> AllModules { get; set; } public IEnumerable<string> RootNamespaces { get; set; } } }
namespace NfePlusAlpha.Infra.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class InsertsTbEstado : DbMigration { public override void Up() { this.Sql( @"insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Acre', 'AC', 12, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Alagoas', 'AL', 27, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Amapá', 'AP', 16, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Amazonas', 'AM', 13, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Bahia', 'BA', 29, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Ceará', 'CE', 23, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Distrito Federal', 'DF', 53, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Espírito Santo', 'ES', 32, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Goiás', 'GO', 52, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Maranhão', 'MA', 21, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Mato Grosso', 'MT', 51, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Mato Grosso do Sul', 'MS', 50, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Minas Gerais', 'MG', 31, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Pará', 'PA', 15, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Paraíba', 'PB', 25, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Paraná', 'PR', 41, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Pernambuco', 'PE', 26, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Piauí', 'PI', 22, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Rio de Janeiro', 'RJ', 33, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Rio Grande do Norte', 'RN', 24, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Rio Grande do Sul', 'RS', 43, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Rondônia', 'RO', 11, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Roraima', 'RR', 14, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Santa Catarina', 'SC', 42, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('São Paulo', 'SP', 35, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Sergipe', 'SE', 28, 1158); insert into tbEstado (est_descricao, est_sigla, est_codigoIBGE, est_codigoPais) values('Tocantins', 'TO', 17, 1158);"); } public override void Down() { } } }
using UnityEngine; using System.Collections; public class CameraControl : MonoBehaviour { public float ZoomSpeed = 100; public float ZoomMin = 20; public float ZoomMax = 60; private Transform targ; void Awake() { // targ = gameObject.GetComponentInParent<CameraMove>().targetPlayer.transform; } void Update () { /* float sc1 = Input.GetAxis("Mouse ScrollWheel"); if (sc1 > 0 && transform.position.y > targ.position.y+ZoomMin) { transform.Translate(Vector3.forward * Time.deltaTime * ZoomSpeed); } if (sc1 < 0 && transform.position.y < targ.position.y + ZoomMax) { transform.Translate(Vector3.back * Time.deltaTime * ZoomSpeed); }*/ } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; using Newtonsoft.Json; using WPF.Data; using WPF.Interfaces; namespace WPF.Models { class JSONService : IDataService<Repository<Saint>> { public string FilePath { get; set; } public Repository<Saint> StartupLoad() { Repository<Saint> data = new Repository<Saint>(); if (File.Exists(FilePath)) { string json = File.ReadAllText(FilePath); data.Data = JsonConvert.DeserializeObject<ObservableCollection<Saint>>(json); return data; } else return data; } public Repository<Saint> Load() { OpenFileDialog dlg = new OpenFileDialog(); dlg.FileName = "data"; dlg.DefaultExt = ".json"; dlg.Filter = "JSON (.json)|*.json"; var result = dlg.ShowDialog(); if (result == true) { FilePath = dlg.FileName; return StartupLoad(); } else return new Repository<Saint>(); } public void Save(Repository<Saint> data) { SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = "data"; dlg.DefaultExt = ".json"; dlg.Filter = "JSON (.json)|*.json"; var result = dlg.ShowDialog(); if (result == true) { FilePath = dlg.FileName; ClosingSave(data); } } public void ClosingSave(Repository<Saint> data) { File.WriteAllText(FilePath, JsonConvert.SerializeObject(data.GetAll(), Formatting.Indented)); } } }
namespace CyberSoldierServer.Models.BaseModels { public enum DefenceType { Weapon, Crew } }
using System; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core { public sealed class VlcMediaPlayerLogEventArgs : EventArgs { public VlcMediaPlayerLogEventArgs(VlcLogLevel level, string message, string module, string sourceFile, uint? sourceLine) { this.Level = level; this.Message = message; this.Module = module; this.SourceFile = sourceFile; this.SourceLine = sourceLine; } /// <summary> /// The severity of the log message. /// By default, you will only get error messages, but you can get all messages by specifying "-vv" in the options. /// </summary> public VlcLogLevel Level { get; } /// <summary> /// The log message /// </summary> public string Message { get; } /// <summary> /// The name of the module that emitted the message /// </summary> public string Module { get; } /// <summary> /// The source file that emitted the message. /// This may be <see langword="null"/> if that info is not available, i.e. always if you are using a release version of VLC. /// </summary> public string SourceFile { get; } /// <summary> /// The line in the <see cref="SourceFile"/> at which the message was emitted. /// This may be <see langword="null"/> if that info is not available, i.e. always if you are using a release version of VLC. /// </summary> public uint? SourceLine { get; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using log4net; namespace IRO.ImageOrganizer.Logic { public sealed class Organizer { public static class Constants { public static readonly int DateProperty = 36867; } private static readonly ILog m_logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly Organizer m_instance = new Organizer(); /// <summary> /// Gets the instance. /// </summary> public static Organizer Instance { get { return m_instance; } } /// <summary> /// Prevents a default instance of the <see cref="Organizer"/> class from being created. /// </summary> private Organizer() { this.InitializeBackgroundWorker(); } private BackgroundWorker m_bw; /// <summary> /// Occurs when [image organized]. /// </summary> public event EventHandler<OrganizerEventArgs> ImageOrganized; /// <summary> /// Occurs when [images organized]. /// </summary> public event EventHandler ImagesOrganized; /// <summary> /// Occurs when [images organizing]. /// </summary> public event EventHandler<OrganizerEventArgs> ImagesOrganizing; /// <summary> /// Initializes the background worker. /// </summary> private void InitializeBackgroundWorker() { m_bw = new BackgroundWorker(); m_bw.DoWork += (sender, e) => { try { OrganizeImageArgs args = (OrganizeImageArgs)e.Argument; String[] files = Directory.GetFiles( args.SourceDirectory, "*", args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".jepg")).ToArray(); m_logger.InfoFormat("Found {0} images to organize.", files.Length); int count = 0; this.OnImagesOrganizing(new OrganizerEventArgs { Count = files.Length }); foreach (String file in files) { count++; this.OrganizeImage(file, args); this.OnImageOrganized(new OrganizerEventArgs { Count = count }); } } catch (InvalidCastException ex) { m_logger.Error(String.Format("Could not cast OrganizeImageArgs. Exception: {0}", ex)); } }; m_bw.RunWorkerCompleted += (sender, e) => this.OnImagesOrganized(); } /// <summary> /// Called when [images organized]. /// </summary> private void OnImagesOrganized() { if (this.ImagesOrganized != null) { ImagesOrganized(this, EventArgs.Empty); } } /// <summary> /// Raises the <see cref="E:ImageOrganized"/> event. /// </summary> /// <param name="e">The <see cref="OrganizerEventArgs"/> instance containing the event data.</param> private void OnImageOrganized(OrganizerEventArgs e) { if (this.ImageOrganized != null) { this.ImageOrganized(this, e); } } /// <summary> /// Raises the <see cref="E:ImagesOrganizing"/> event. /// </summary> /// <param name="e">The <see cref="OrganizerEventArgs"/> instance containing the event data.</param> private void OnImagesOrganizing(OrganizerEventArgs e) { if (this.ImagesOrganizing != null) { this.ImagesOrganizing(this, e); } } /// <summary> /// Organizes the images. /// </summary> public void OrganizeImages(OrganizeImageArgs args) { if (m_bw.IsBusy) { return; } if (String.IsNullOrEmpty(args.SourceDirectory)) { throw new ArgumentException("The Source Directory was not defined"); } if (String.IsNullOrEmpty(args.DestinationDirectory)) { throw new ArgumentException("The Destination Directory was not defined"); } if (!Directory.Exists(args.SourceDirectory)) { throw new ArgumentException("The Source Directory does not exist"); } m_bw.RunWorkerAsync(args); } /// <summary> /// Organize the image. /// </summary> /// <param name="source">The source.</param> /// <param name="args">The arguments.</param> private void OrganizeImage(String source, OrganizeImageArgs args) { DateTime dateTaken; String destination = null; if (this.GetDateTakenFromImage(source, out dateTaken) && dateTaken != DateTime.MinValue && dateTaken != DateTime.MaxValue) { String subDirectory = GetSubDirectoryFromDateTime(dateTaken, args.DestinationDirectoryMask); destination = Path.Combine(args.DestinationDirectory, subDirectory); } else { m_logger.InfoFormat("Did not move image {0} because it was impossible to get the date taken", source); HandleFailedFile(args, source); } if (!String.IsNullOrEmpty(destination)) { if (!Directory.Exists(destination)) { m_logger.InfoFormat("Creating directory {0}", destination); Directory.CreateDirectory(destination); } String fileName = Path.GetFileName(source); if (!String.IsNullOrEmpty(fileName)) { if (args.RenameFilesAccordingToDate) { fileName = String.Format("IMG_{0}{1}{2}_{3}{4}{5}{6}", dateTaken.Year.ToString("D4"), dateTaken.Month.ToString("D2"), dateTaken.Day.ToString("D2"), dateTaken.Hour.ToString("D2"), dateTaken.Minute.ToString("D2"), dateTaken.Second.ToString("D2"), Path.GetExtension(fileName)); } String destinationFile = Path.Combine(destination, fileName); if (File.Exists(destinationFile)) { m_logger.InfoFormat("File {0} exists at destination {1}", source, destination); if (args.RenameFilesAccordingToDate) { int fileCount = 1; while (File.Exists(destinationFile)) { fileName = String.Format("IMG_{0}{1}{2}_{3}{4}{5} ({6}){7}", dateTaken.Year.ToString("D4"), dateTaken.Month.ToString("D2"), dateTaken.Day.ToString("D2"), dateTaken.Hour.ToString("D2"), dateTaken.Minute.ToString("D2"), dateTaken.Second.ToString("D2"), fileCount, Path.GetExtension(fileName)); destinationFile = Path.Combine(destination, fileName); fileCount = fileCount + 1; if (fileCount == 10) { throw new Exception("had to rename too many times"); } } } else { m_logger.InfoFormat("Did not move image {0} to {1} because it already exists at destination", source, destination); HandleFailedFile(args, source); return; } } if (args.DeleteSourceImages) { File.Move(source, destinationFile); m_logger.InfoFormat("Moved image {0} to {1}", source, destinationFile); } else { File.Copy(source, destinationFile); m_logger.InfoFormat("Copied image {0} to {1}", source, destinationFile); } } } } /// <summary> /// Handles the failed file. /// </summary> /// <param name="args">The arguments.</param> /// <param name="source">The source.</param> private void HandleFailedFile(OrganizeImageArgs args, String source) { try { if (args.MoveFailedFiles && !String.IsNullOrWhiteSpace(args.FailuresDirectory)) { if (!Directory.Exists(args.FailuresDirectory)) { m_logger.InfoFormat("Creating directory {0}", args.FailuresDirectory); Directory.CreateDirectory(args.FailuresDirectory); } String destination = Path.Combine(args.FailuresDirectory, Path.GetFileName(source)); if (args.DeleteSourceImages) { File.Move(source, destination); m_logger.InfoFormat("Moved image {0} to {1}", source, destination); } else { File.Copy(source, destination); m_logger.InfoFormat("Copied image {0} to {1}", source, destination); } } } catch (Exception ex) { m_logger.InfoFormat("An exception occurred while handling the failed file. {0}", ex.Message); } } /// <summary> /// Gets the sub directory from date time. /// </summary> /// <param name="dateTaken">The date taken.</param> /// <param name="formatString">The format string.</param> /// <returns></returns> private string GetSubDirectoryFromDateTime(DateTime dateTaken, String formatString) { String[] tokens = formatString.Split('\\'); if (tokens.Length == 1 && String.IsNullOrWhiteSpace(tokens[0])) { return String.Empty; } return tokens.Aggregate(String.Empty, (current, t) => current + dateTaken.ToString(t) + "\\"); } // we init this once so that if the function is repeatedly called it isn't stressing the garbage man private readonly Regex m_regEx = new Regex(":"); /// <summary> /// retrieves the datetime WITHOUT loading the whole image. /// </summary> /// <param name="path">The path.</param> /// <param name="dateTime">The date time.</param> /// <returns></returns> private bool GetDateTakenFromImage(string path, out DateTime dateTime) { dateTime = DateTime.MinValue; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { using (Image myImage = Image.FromStream(fs, false, false)) { try { PropertyItem propItem = myImage.GetPropertyItem(Constants.DateProperty); string dateTaken = m_regEx.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); dateTime = DateTime.Parse(dateTaken); return true; } catch { m_logger.ErrorFormat("Could not determine DateTaken from image: {0}", path); return false; } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task5_Matrix { public class MatrixCreater { private static readonly Random random = new Random(); /// <summary> /// Create Random matrix /// </summary> /// <param name="rowCount"></param> /// <param name="columnCount"></param> /// <returns>Random matrix</returns> public static Matrix CreateRandomMatrix(int rowCount, int columnCount) { Matrix randomMatrix = new Matrix(){ Massive = new int[columnCount, rowCount] }; int randomMinValue = -99; int randomMaxValue = 99; if (rowCount <= 0 && columnCount <= 0) throw new ArgumentException("Размерность матриц должна быть больше 0"); for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { randomMatrix.Massive[i,j] = random.Next(randomMinValue, randomMaxValue); } } return randomMatrix; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WAP_Aula07parte2 { public partial class Dados : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(Session["DadosUsuario"] != null) { Pessoa pessoa; pessoa = (Session["DadosUsuario"] as Pessoa); Lbl_Nome.Text += pessoa.Nome; Lbl_Profissao.Text += pessoa.Profissao; if (pessoa.BancoDados) Lbl_Interesses.Text += "Banco de Dados "; if (pessoa.Programacao) Lbl_Interesses.Text += "Programação "; if (pessoa.Analise) Lbl_Interesses.Text += "Análise "; if (pessoa.Infra) Lbl_Interesses.Text += "Infra "; } } protected void Botao_voltar_Click(object sender, EventArgs e) { Response.Redirect("Default.aspx"); } protected void Botao_resetar_Click(object sender, EventArgs e) { Session.Clear(); Response.Redirect("Default.aspx"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace JobsDatabase.Models { public partial class JobsMetadata {//metadata partial class created so data annotations are retained //if the database is updated public int ImageId { get; set; } public string ImageTitle { get; set; } public byte[] ImageByte { get; set; } [Display(Name = "Picture (URL)")] public string ImagePath { get; set; } [Display(Name = "Type of Job")]//To display the right name public string TypeOfJob { get; set; } [Display(Name = "Tools needed")] public string ToolsNeeded { get; set; } [Display(Name = "Profit")] public string GainsExpectations { get; set; } [Display(Name = "Expenses less than 5 miles")] public Nullable<int> ExpensesLessThanFiveMiles { get; set; } [Display(Name = "Expenses less than 10 miles")] public Nullable<int> ExpenseslessThanTenMiles { get; set; } [Display(Name = "Expenses less than 20 miles")] public Nullable<int> ExpensesLessThanTwentyMiles { get; set; } [Display(Name = "Expenses less than 30 miles")] public Nullable<int> ExpensesLessThanThirtyMiles { get; set; } [Display(Name = "Materials")] public string Materials { get; set; } [Display(Name = "Estimate duration")] public Nullable<int> EstimateDuration { get; set; } [Display(Name = "Estimate Number of Employees")] public Nullable<int> EstimateNofEmployees { get; set; } } }
using System; namespace Probabilities { public struct Probability { //note: P(A & B) = P(A) x P(B) public double CalculateProbabilityOfBoth(double probabilityA, double probabilityB) { if (probabilityA < 0 || probabilityB < 0 || probabilityB > 1 || probabilityA > 1) throw new ArgumentException(); return probabilityA * probabilityB; } //note: P(A | B) = P(A) + P(B) – P(A & B) public double CalculateProbabilityOfEither(double probabilityA, double probabilityB) { if (probabilityA < 0 || probabilityB < 0 || probabilityB > 1 || probabilityA > 1) throw new ArgumentException(); return probabilityA + probabilityB - CalculateProbabilityOfBoth(probabilityA, probabilityB); } //note: P(!A) = 1 – P(A) public double CalculateProbabilityOfInverse(double probability) { if (probability < 0 || probability > 1) throw new ArgumentException(); return 1 - probability; } } }
using Microsoft.AspNetCore.Identity; namespace CyberSoldierServer.Models.Auth { public class Role : IdentityRole<int> { } }
using LocusNew.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LocusNew.Core.ViewModels { public class ListingViewModel { public int Id { get; set; } public string Address { get; set; } public decimal? Price { get; set; } public string Details { get; set; } public AdType AdType { get; set; } public bool isActive { get; set; } public bool isSold { get; set; } public bool isRented { get; set; } public PropertyType PropertyType { get; set; } public DateTime Published { get; set; } public int? Rooms { get; set; } public int? Bedrooms { get; set; } public int? Bathrooms { get; set; } public int Floor { get; set; } public int TotalFloorNumber { get; set; } public int? SquareMeters { get; set; } public int LotSquareMeters { get; set; } public int YardSquareMeters { get; set; } public int YearBuilt { get; set; } public int YearOfLastAdaptation { get; set; } public bool Elevator { get; set; } public bool Balcony { get; set; } public bool Terrace { get; set; } public bool Loggia { get; set; } public bool Attic { get; set; } public bool Basement { get; set; } public bool Pantry { get; set; } public bool Water { get; set; } public bool Gas { get; set; } public string Canalization { get; set; } public bool TelephoneConnection { get; set; } public bool Electricity { get; set; } public bool CentralHeatingToplane { get; set; } public string CentralHeatingEtazno { get; set; } public bool CableTV { get; set; } public bool Internet { get; set; } public bool Furniture { get; set; } public string Latidute { get; set; } public string Longitude { get; set; } public List<ListingImage> Images { get; set; } public string ImagePreview { get; set; } public string ImagePreviewPath { get; set; } public int Toilete { get; set; } public CityPart CityPart { get; set; } public ApplicationUser ApplicationUser { get; set; } public string ListingUniqueCode { get; set; } public string MetaKeywords { get; set; } public bool Videophone { get; set; } public bool Interphone { get; set; } public bool PrivateParking { get; set; } public bool Garage { get; set; } public bool ArmoredDoor { get; set; } public string Heading { get; set; } public bool AirConditioner { get; set; } public string Joinery { get; set; } public bool NewKitchen { get; set; } public string FloorText { get; set; } public string AlternativeHeating { get; set; } public bool isReserved { get; set; } public bool MultiRooms { get; set; } public bool MultiBedrooms { get; set; } public bool MultiBathrooms { get; set; } public bool MultiSquareMeters { get; set; } public int? MultiRoomsFrom { get; set; } public int? MultiRoomsTo { get; set; } public int? MultiBedroomsFrom { get; set; } public int? MultiBedroomsTo { get; set; } public int? MultiBathFrom { get; set; } public int? MultiBathTo { get; set; } public int? MultiSquareMetersFrom { get; set; } public int? MultiSquareMetersTo { get; set; } public bool MultiPrice { get; set; } public decimal? MultiPriceFrom { get; set; } public decimal? MultiPriceTo { get; set; } public string ApplicationUserId { get; internal set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLDSV { public partial class frmDangKyTaiKhoan : Form { public frmDangKyTaiKhoan() { InitializeComponent(); } private void kHOABindingNavigatorSaveItem_Click(object sender, EventArgs e) { this.Validate(); this.kHOABindingSource.EndEdit(); this.tableAdapterManager.UpdateAll(this.dS); } private void frmDangKyTaiKhoan_Load(object sender, EventArgs e) { dS.EnforceConstraints = false; this.sP_DSChuaCoTKTableAdapter.Connection.ConnectionString = Program.connstr; this.sP_DSChuaCoTKTableAdapter.Fill(this.dS.SP_DSChuaCoTK); cmbKhoa.DataSource = Program.bds_dspm; cmbKhoa.DisplayMember = "TENCN"; cmbKhoa.ValueMember = "TENSERVER"; cmbKhoa.SelectedIndex = Program.mKhoa; cmbRoles.Items.Clear(); cmbRoles.Items.Add("PGV"); cmbRoles.Items.Add("Khoa"); cmbRoles.Items.Add("User"); cmbRoles.Items.Add("PKeToan"); if (Program.mGroup == "PGV") { cmbKhoa.Enabled = true; cmbRoles.Items.RemoveAt(3); cmbRoles.SelectedIndex = 0; cmbRoles.Enabled = true; } if (Program.mGroup != "PGV") { cmbKhoa.Enabled = false; } if (Program.mGroup == "Khoa") { cmbRoles.SelectedIndex = 1; //cmbRoles.Items.RemoveAt(3); //cmbRoles.Items.RemoveAt(0); cmbRoles.Enabled = false; } if (Program.mGroup == "PKeToan") { cmbRoles.SelectedIndex = 2; cmbRoles.Enabled = false; } } private void tENKHLabel_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void btnThoat_Click(object sender, EventArgs e) { if (Program.mGroup == "PGV" && cmbKhoa.SelectedIndex != Program.mKhoa) { cmbKhoa.SelectedIndex = Program.mKhoa; } this.Close(); } private void tENLabel_Click(object sender, EventArgs e) { } private void btnTaoTaiKhoan_Click(object sender, EventArgs e) { if (txtTenDangNhap.Text == "" || txtMatKhau.Text == "") { MessageBox.Show("Tên đăng nhập or mật khẩu bị trống", "", MessageBoxButtons.OK); return; } using (SqlConnection con = new SqlConnection(Program.connstr)) { using (SqlCommand cmd = new SqlCommand("sp_TaoTaiKhoan")) { cmd.Connection = con; con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@LGNAME", SqlDbType.VarChar, 50).Value = txtTenDangNhap.Text; cmd.Parameters.Add("@PASS", SqlDbType.VarChar, 50).Value = txtMatKhau.Text; cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar, 50).Value = cmbMaGV.SelectedValue.ToString(); cmd.Parameters.Add("@ROLE", SqlDbType.VarChar, 50).Value = cmbRoles.Text; if (MessageBox.Show("Tên đăng nhập : " + txtTenDangNhap.Text + " Mật khẩu: " + txtMatKhau.Text + " Mã GV: " + cmbMaGV.SelectedValue.ToString() + " Nhóm: " + cmbRoles.Text, "Xác nhận", MessageBoxButtons.OKCancel) == DialogResult.OK) { SqlParameter prmt = new SqlParameter(); prmt = cmd.Parameters.Add("RETURN_VALUE", SqlDbType.Int); prmt.Direction = ParameterDirection.ReturnValue; try { cmd.ExecuteNonQuery(); MessageBox.Show(" Tạo tài khoản mới thành công !", "", MessageBoxButtons.OK); txtTenDangNhap.Text = ""; txtMatKhau.Text = ""; } catch (Exception ex) { int check = (int)cmd.Parameters["return_value"].Value; if (check == 1) { MessageBox.Show("Tên đăng nhập đã tồn tại\n\n " + ex.Message); } if (check == 2) { MessageBox.Show("Mã giảng viên đã tồn tại\n\n " + ex.Message); } con.Close(); } } con.Close(); } } } private void groupBox1_Enter(object sender, EventArgs e) { } private void cmbKhoa_SelectedIndexChanged(object sender, EventArgs e) { if (cmbKhoa.SelectedValue != null) { if (cmbKhoa.SelectedValue.ToString() == "System.Data.DataRowView") return; Program.servername = cmbKhoa.SelectedValue.ToString(); if(Program.mGroup == "PGV" && cmbKhoa.SelectedIndex == 2) { MessageBox.Show("Bạn không có quyền truy cập", "", MessageBoxButtons.OK); cmbKhoa.SelectedIndex = 1; cmbKhoa.SelectedIndex = 0; return; } if (cmbKhoa.SelectedIndex != Program.mKhoa) { Program.mlogin = Program.remotelogin; Program.password = Program.remotepassword; } else { Program.mlogin = Program.mloginDN; Program.password = Program.passwordDN; } if (Program.KetNoi() == 0) MessageBox.Show("Lỗi kết nối về chi nhánh mới", "", MessageBoxButtons.OK); else { this.sP_DSChuaCoTKTableAdapter.Connection.ConnectionString = Program.connstr; this.sP_DSChuaCoTKTableAdapter.Fill(this.dS.SP_DSChuaCoTK); if (Program.mGroup == "PGV") { cmbKhoa.Enabled = true; try { cmbRoles.Items.Clear(); cmbRoles.Items.Add("PGV"); cmbRoles.Items.Add("Khoa"); cmbRoles.Items.Add("User"); cmbRoles.Items.Add("PKeToan"); cmbRoles.Enabled = true; cmbRoles.Items.RemoveAt(3); cmbRoles.SelectedIndex = 0; } catch (Exception ex) { } } if (Program.mGroup == "PGV" && cmbKhoa.SelectedIndex.ToString() == "2") { cmbKhoa.Enabled = true; try { cmbRoles.Items.Clear(); cmbRoles.Items.Add("PGV"); cmbRoles.Items.Add("Khoa"); cmbRoles.Items.Add("User"); cmbRoles.Items.Add("PKeToan"); cmbRoles.SelectedIndex = 3; cmbRoles.Enabled = false; } catch (Exception ex) { } } } } } private void cmbRoles_SelectedIndexChanged(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; namespace Basic_Tree_Data_Homework { class Root_Node { static Dictionary<int, Tree<int>> nodeByValue = new Dictionary<int, Tree<int>>(); static void Main(string[] args) { //int numbersOfNode = int.Parse(Console.ReadLine()); //for (int i = 0; i < numbersOfNode-1; i++) //{ // int[] nodes = Console.ReadLine().Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); // int parent = nodes[0]; // int child = nodes[1]; // if (!nodeByValue.ContainsKey(parent)) // { // nodeByValue.Add(parent, new Tree<int>(parent)); // } // if (!nodeByValue.ContainsKey(child)) // { // nodeByValue.Add(child, new Tree<int>(child)); // } // Tree<int> parentNode = nodeByValue[parent]; // Tree<int> childNode = nodeByValue[child]; // parentNode.Children.Add(childNode); // childNode.Parent = parentNode; ReadTree(); //Tree<int> root = GetRootNode(); //Console.WriteLine($"Root node: {root.Value}"); //List<int> leaf = GetLeafNode(); //Console.WriteLine($"Leaf nodes: {string.Join(" ",leaf)}"); //List<int> middleNodeList = GetMiddleNode(); //Console.WriteLine($"Middle nodes: {string.Join(" ",middleNodeList)}"); //Tree<int> deepestNode = GetDeepestNode(); //Console.WriteLine($"Deepest node: {deepestNode.Value}"); //Stack<int> nodespPath = GetLongestPath(); //Console.WriteLine($"Longest path: {String.Join(" ",nodespPath)}"); //GetAllPathsWithAGivenSum(); GetAllSubtreesWithGivenSum(); } private static void GetAllPathsWithAGivenSum() { int targetSum = Convert.ToInt32(Console.ReadLine()); Tree<int> root = GetRootNode(); Console.WriteLine($"Paths of sum {targetSum}: "); DFSTargetSum(root, targetSum); } private static void DFSTargetSum(Tree<int> node, int targetSum, int sum = 0) { sum += node.Value; if (targetSum == sum) { PrintPath(node); } foreach (Tree<int> child in node.Children) { DFSTargetSum(child, targetSum, sum); } } private static void PrintPath(Tree<int> node) { Stack<int> pathStack = new Stack<int>(); while (node != null) { pathStack.Push(node.Value); node = node.Parent; } Console.WriteLine($"{String.Join(" ", pathStack)}"); } private static void GetAllSubtreesWithGivenSum() { int targetSum = Convert.ToInt32(Console.ReadLine()); Console.WriteLine($"Subtrees of sum {targetSum}:"); Tree<int> root = GetRootNode(); List<Tree<int>> nodes = new List<Tree<int>>(); DFS(root, nodes); foreach (Tree<int> node in nodes) { int sum = CalculateSumOfNodes(node); if (sum == targetSum) { List<int> subtree = new List<int>(); GetSubTreeNodes(node, subtree); Console.WriteLine($"{String.Join(" ", subtree)}"); } } } private static void GetSubTreeNodes(Tree<int> node, List<int> subtree) { subtree.Add(node.Value); foreach (Tree<int> child in node.Children) { GetSubTreeNodes(child, subtree); } } private static int CalculateSumOfNodes(Tree<int> node) { int sum = node.Value; foreach (Tree<int> child in node.Children) { sum += CalculateSumOfNodes(child); } return sum; } private static void DFS(Tree<int> root, List<Tree<int>> nodes) { foreach (Tree<int> child in root.Children) { DFS(child, nodes); } nodes.Add(root); } private static Stack<int> GetLongestPath() { Tree<int> deepestNode = GetDeepestNode(); Stack<int> nodesPathStack = new Stack<int>(); while (deepestNode != null) { nodesPathStack.Push(deepestNode.Value); deepestNode = deepestNode.Parent; } return nodesPathStack; } private static Tree<int> GetDeepestNode() { List<Tree<int>> leafs = nodeByValue.Values.Where(x => x.Children.Count == 0).ToList(); Tree<int> deepestNode = GetRootNode(); int maxDeep = 0; foreach (Tree<int> leaf in leafs) { Tree<int> currNode = leaf; int curDeep = 1; while (currNode.Parent != null) { curDeep++; currNode = currNode.Parent; } if (curDeep > maxDeep) { maxDeep = curDeep; deepestNode = leaf; } } return deepestNode; } private static List<int> GetMiddleNode() { List<int> nodes = nodeByValue.Values.Where(x => x.Children.Count != 0 && x.Parent != null) .OrderBy(x => x.Value).Select(x => x.Value).ToList(); return nodes; } private static List<int> GetLeafNode() { List<int> leafs = nodeByValue.Values.Where(x => x.Children.Count == 0).OrderBy(x => x.Value) .Select(x => x.Value).ToList(); return leafs; } private static Tree<int> GetRootNode() { Tree<int> root = nodeByValue.Values.FirstOrDefault(x => x.Parent == null); return root; } private static void ReadTree() { int nodeCount = int.Parse(Console.ReadLine()); for (int i = 0; i < nodeCount - 1; i++) { int[] nodes = Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); AddEdge(nodes[0], nodes[1]); } } private static void AddEdge(int parent, int child) { Tree<int> parentNode = GetTreeNodeByValue(parent); Tree<int> childNode = GetTreeNodeByValue(child); parentNode.Children.Add(childNode); childNode.Parent = parentNode; } private static Tree<int> GetTreeNodeByValue(int node) { if (!nodeByValue.ContainsKey(node)) { nodeByValue[node] = new Tree<int>(node); } return nodeByValue[node]; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using AJW.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using AJWTEST.Models; using Newtonsoft.Json.Linq; namespace AJWTEST.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public ActionResult Index(string query) { JObject o = JObject.Parse(System.IO.File.ReadAllText(@"Models/Orders.json")); JArray so = (JArray)o["orders"]["sOrders"]["data"]; JArray po = (JArray)o["orders"]["pOrders"]["data"]; IList<Order> orders = so.ToObject<IList<Order>>(); ((List<Order>)orders).AddRange(po.ToObject<IList<Order>>()); IList<Order> searchReturned = new List<Order>(); Console.WriteLine("query = " + query); //return search items foreach (Order order in orders) { if (order.PnUpper == query | order.SoNumber == query) { searchReturned.Add(order); } } //nothing searched if (query == null | query == "") { return View(orders); } //no results returned if (searchReturned.Count < 1) { //write that nothing has appeared return View(); } return View(searchReturned); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier}); } } }
using System; using System.Collections.Generic; using FruitBasket_DLL; namespace FruitBasket_Console { public class Program { static void Main(string[] args) { var randomSeed = new Random(); var basket = new Basket(randomSeed); Console.WriteLine($"Basket's weight is {basket.Weight} kg."); // //Creating players: Console.Write("Enter the number of players (from 2 to 8): "); string input = Console.ReadLine(); int minPlayers = 2; int maxPlayers = 8; int numOfPlayers = InputValidation(input, minPlayers, maxPlayers); var playersList = new List<Player>(); for (int i = 1; i <= numOfPlayers; i++) { Console.WriteLine($"Select the type of {i} player"); Console.WriteLine("1 - Regular Player"); Console.WriteLine("2 - Notebook Player"); Console.WriteLine("3 - Uber-Player"); Console.WriteLine("4 - Cheater"); Console.WriteLine("5 - Uber-Cheater Player"); int type = InputValidation(Console.ReadLine(), 1, 5); switch (type) { case 1: playersList.AddPlayerToList(new RegularPlayer(randomSeed)); break; case 2: playersList.AddPlayerToList(new NotebookPlayer(randomSeed)); break; case 3: playersList.AddPlayerToList(new UberPlayer()); break; case 4: playersList.AddPlayerToList(new CheaterPlayer(randomSeed)); break; case 5: playersList.AddPlayerToList(new UberCheaterPlayer()); break; } } var totalTriesList = new List<List<int>>(); foreach (var player in playersList) { totalTriesList.Add(player.PersonalTries); } // //Let the game begin! for (int tries = 1; tries <= 100; tries++) { Console.WriteLine($"Try #{tries}"); foreach (var player in playersList) { int newTry = player.Guess(Basket.MinWeight, Basket.MaxWeight, ref totalTriesList); Console.WriteLine($"{player.TypeName} {player.Name} says {newTry}"); if (newTry == basket.Weight) { Console.WriteLine($"{player.TypeName} {player.Name} wins!"); Console.ReadKey(); return; } } Console.WriteLine(); } // //If nobody guessed correctly: var bestTriesList = new List<int>(); foreach (Player player in playersList) { player.BestTry = player.PersonalTries.GetBestTry(basket.Weight); Console.WriteLine($"{player.TypeName} {player.Name}'s closest guess is {player.BestTry}"); bestTriesList.Add(player.BestTry); } int totalBestTry = bestTriesList.GetBestTry(basket.Weight); foreach(Player player in playersList) { if (player.BestTry == totalBestTry) { Console.WriteLine($"{player.TypeName} {player.Name} wins! Their closest guess is {player.BestTry}"); } } Console.ReadKey(); } public static int InputValidation(string input, int minValue, int maxValue) { int result; while (int.TryParse(input, out result) == false || minValue > result || maxValue < result) { Console.Write("Please try again: "); input = Console.ReadLine(); } return result; } } }
using Alabo.App.Asset.Pays.Domain.Entities; using Alabo.Domains.Enums; using Alabo.Framework.Core.Enums.Enum; using Alabo.Web.Mvc.Attributes; using Alabo.Web.Mvc.ViewModel; using MongoDB.Bson.Serialization.Attributes; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Alabo.App.Asset.Recharges.Domain.Entities.Extension { /// <summary> /// 充值表 /// </summary> [BsonIgnoreExtraElements] [Table("Finace_TradeRecharge")] [ClassProperty(Name = "充值管理", Icon = "fa fa-puzzle-piece", Description = "充值管理", PageType = ViewPageType.List)] public class RechargeExtension : BaseViewModel { /// <summary> /// 支付记录 /// 线上支付时,支付记录必须填写,线下汇款不需要填写 /// </summary> public Pay Pay { get; set; } public decimal CheckAmount { get; set; } /// <summary> /// 手续费 /// </summary> [Display(Name = "手续费")] public decimal Fee { get; set; } /// <summary> /// Gets or sets the bank 类型. /// 汇款银行 /// 线下充值时,汇款银行必须填写 /// </summary> [Display(Name = "汇款银行")] public BankType BankType { get; set; } /// <summary> /// 银行卡号 /// 线下充值时,汇款银行必须填写 /// </summary> [Display(Name = "银行卡号")] public string BankNumber { get; set; } /// <summary> /// 持卡人姓名 /// </summary> [Display(Name = "持卡人姓名")] public string BankName { get; set; } } }
using Alabo.Validations; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Themes.Dtos { public class WidgeInput { /// <summary> /// 数据Id为空的时候,使用默认数据Id /// </summary> [Display(Name = "数据Id")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public string DataId { get; set; } /// <summary> /// 模块数据 /// </summary> [Display(Name = "模块Id")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public string WidgetId { get; set; } /// <summary> /// 默认模块数据Id /// </summary> [Display(Name = "默认数据Id")] public string DefaultDataId { get; set; } } }
using System.Collections.Generic; using System.Data; using System.Linq; namespace ACS { /// <summary> /// 获取对象 /// </summary> public class GetObject { public static Shelf GetShelf(DataRow dr) { Shelf s = new Shelf(); s.areaNo = dr["areaNo"].ToString(); s.barcode = dr["barcode"].ToString(); s.currentBarcode = dr["currentBarcode"].ToString(); s.isEnable = bool.Parse(dr["isEnable"].ToString()); s.isLocked = bool.Parse(dr["isLocked"].ToString()); s.shelfDirection = dr["shelfDirection"].ToString(); s.shelfNo = dr["shelfNo"].ToString(); return s; } public static Agv GetAgv(DataRow dr) { Agv a = new Agv(); a.agvNo = dr["agvNo"].ToString(); a.barcode = dr["barcode"].ToString(); a.currentCharge = float.Parse(dr["currentCharge"].ToString()); a.errorMsg = int.Parse(dr["errorMsg"].ToString()); a.height = (HeightEnum)int.Parse(dr["height"].ToString()); a.isEnable = bool.Parse(dr["isEnable"].ToString()); a.sTaskList = new List<STask>(); a.state = (AgvState)int.Parse(dr["state"].ToString()); a.areaNo = dr["areaNo"].ToString(); return a; } public static Point GetPoint(DataRow dr) { Point p = new Point(); p.isXPos = bool.Parse(dr["isXPos"].ToString()); p.isYPos = bool.Parse(dr["isYPos"].ToString()); p.isYNeg = bool.Parse(dr["isYNeg"].ToString()); p.isXNeg = bool.Parse(dr["isXNeg"].ToString()); p.listTmpDirection = new List<TmpDirection>(); p.areaNo = dr["AreaNo"].ToString(); p.barCode = dr["Barcode"].ToString(); p.isEnable = bool.Parse(dr["isEnable"].ToString()); p.isOccupy = bool.Parse(dr["isOccupy"].ToString()); p.lockedAgv = null; p.occupyAgvNo = dr["occupyAgvNo"].ToString(); p.pointType = (PointType)int.Parse(dr["PointType"].ToString()); p.x = int.Parse(dr["X"].ToString()); p.y = int.Parse(dr["Y"].ToString()); p.xLength = int.Parse(dr["xLength"].ToString()); p.yLength = int.Parse(dr["yLength"].ToString()); return p; } public static STask GetSTask(DataRow dr) { STask sTask = new STask(); sTask.serialNo = int.Parse(dr["serialNo"].ToString()); ; sTask.sID = int.Parse(dr["SID"].ToString()); sTask.taskNo = dr["TaskNo"].ToString(); sTask.sTaskType = (STaskType)int.Parse(dr["ItemName"].ToString()); sTask.agv = App.AgvList.FirstOrDefault(a => a.agvNo == dr["AgvNo"].ToString()); sTask.beginPoint = App.pointList.FirstOrDefault(a => a.barCode == dr["BeginPoint"].ToString()); sTask.endPoint = App.pointList.FirstOrDefault(a => a.barCode == dr["EndPoint"].ToString()); sTask.dialDirection = int.Parse(dr["DialDirection"].ToString()); sTask.agvDirection = int.Parse(dr["AgvDirection"].ToString()); sTask.state = (TaskState)(int.Parse(dr["State"].ToString())); sTask.pathList = new List<PathPoint>(); sTask.agv.sTaskList.Add(sTask); return sTask; } public static Motion GetMotion(STask st, PathPoint ppCurrent) { Motion motion = new Motion(); motion.sTaskType = st.sTaskType; if (st.sTaskType == STaskType.D1) { //如果是子任务的终点 if (ppCurrent.serialNo == st.pathList[st.pathList.Count - 1].serialNo) motion.sTaskType = STaskType.D18; //如果是拐点 if (ppCurrent.isCorner) motion.sTaskType = STaskType.D20; } motion.barcode = ppCurrent.point.barCode; motion.x = ppCurrent.point.x; motion.y = ppCurrent.point.y; motion.xLength = ppCurrent.point.xLength; motion.yLength = ppCurrent.point.xLength; motion.pointType = (int)ppCurrent.point.pointType; return motion; } public static PathPoint GetPathPoint(Point point) { PathPoint pp = new PathPoint(); pp.point = point; return pp; } } }
// *********************************************************************** // Assembly : Huawei.SCOM.ESightPlugin.Const // Author : yayun // Created : 01-05-2018 // // Last Modified By : yayun // Last Modified On : 01-05-2018 // *********************************************************************** // <copyright file="ESightConnectStatus.cs" company="广州摩赛网络技术有限公司"> // Copyright © 2017 // </copyright> // <summary>The e sight connect status.</summary> // *********************************************************************** namespace Huawei.SCOM.ESightPlugin.Const { /// <summary> /// Class ConstMgr. /// </summary> public partial class ConstMgr { /// <summary> /// The e sight connect status. /// </summary> public class ESightConnectStatus : ConstBase { /// <summary> /// The lates t_ statu s_ disconnect. /// </summary> public const string DISCONNECT = "DISCONNECT"; /// <summary> /// The lates t_ statu s_ failed. /// </summary> public const string FAILED = "Offline"; /// <summary> /// The lates t_ statu s_ none. /// </summary> public const string NONE = "Ready"; /// <summary> /// The lates t_ statu s_ online. /// </summary> public const string ONLINE = "Online"; } } }
namespace IAPharmacySystemService.DTO { public class PatientDto { public string Jmbg { get; set; } public string Name { get; set; } public string Surname { get; set; } } }
using UnityEngine; using System.Collections; /* * This script moves a platform that follows a path of any length that can be set in the inspector. The platform goes to each point in a loop. */ public class MovingPlatformBehavior : MonoBehaviour { [SerializeField] Vector3[] path; // an array of points describing the path the platform will take, relative to its starting position. [SerializeField] float moveSpeed; // how fast the platform moves private Vector3[] actualPath; // a converted array describing the path in world space rather than relative to starting position. private int pathIndex; // which point in the path array the platform is currently moving towards // Use this for initialization void Start () { actualPath = new Vector3[path.Length + 1]; // the actualPath array will include the starting position, so make this array larger by 1 actualPath[0] = transform.position; // set the starting point // convert points to world space. for(int i = 0; i < path.Length; i++) { Vector3 worldPoint = new Vector3(path[i].x + actualPath[0].x, path[i].y + actualPath[0].y, path[i].z + actualPath[0].z); actualPath[i + 1] = worldPoint; } pathIndex = 1; // start moving towards the first point in the path } // Update is called once per frame void Update () { if(GetComponent<Triggerable>().isTriggered()) { GetComponent<SwitchBehavior>().setOn(true); // move towards path point float step = moveSpeed * Time.deltaTime; Vector3 newPos = Vector3.MoveTowards(transform.position, actualPath[pathIndex], step); transform.position = newPos; // check if path point is reached if(transform.position == actualPath[pathIndex]) { pathIndex++; // go to next point if (pathIndex >= actualPath.Length) pathIndex = 0; // loop around } } else GetComponent<SwitchBehavior>().setOn(false); } }
using System; using System.Collections.Generic; using System.Reflection; namespace Phenix.StandardRule.Information { /// <summary> /// 资料工具 /// </summary> public class InformationTool { /// <summary> /// 初始化 /// </summary> public InformationTool() { } /// <summary> /// 初始化 /// </summary> /// <param name="information">资料</param> public InformationTool(IInformation information) { Information = information; } #region 属性 #region 可操作条件 /// <summary> /// 是否允许提交审核 /// </summary> public bool AllowSubmitVerify { get { return GetAllowSubmitVerify(Information); } } /// <summary> /// 是否允许审核资料 /// </summary> public bool AllowVerify { get { return GetAllowVerify(Information); } } /// <summary> /// 是否允许合并作废资料 /// </summary> public bool AllowMergeInvalid { get { return GetAllowMergeInvalid(Information); } } /// <summary> /// 是否允许暂停使用资料 /// </summary> public bool AllowSuspend { get { return GetAllowSuspend(Information); } } /// <summary> /// 是否允许恢复使用资料 /// </summary> public bool AllowApply { get { return GetAllowApply(Information); } } #endregion private IInformation _information; /// <summary> /// 资料 /// </summary> public IInformation Information { get { return _information; } set { if (_information == value) return; _information = value; InitializeInformation(); } } /// <summary> /// 资料标签 /// </summary> public string InformationCaption { get { return _information != null ? _information.Caption : String.Empty; } } #endregion #region 事件 ///<summary> /// 资料状态发生变化前 ///</summary> public event EventHandler<InformationStatusChangingEventArgs> InformationStatusChanging; ///<summary> /// 资料状态发生变化后 ///</summary> public event EventHandler<InformationStatusChangedEventArgs> InformationStatusChanged; /// <summary> /// 资料状态发生变化前 /// </summary> /// <param name="e">资料状态变更事件内容</param> protected void OnInformationStatusChanging(InformationStatusChangingEventArgs e) { EventHandler<InformationStatusChangingEventArgs> handler = InformationStatusChanging; if (handler != null) handler(null, e); e.Information.OnInformationStatusChanging(e); } /// <summary> /// 资料状态发生变化后 /// </summary> /// <param name="e">资料状态变更事件内容</param> protected void OnInformationStatusChanged(InformationStatusChangedEventArgs e) { EventHandler<InformationStatusChangedEventArgs> handler = InformationStatusChanged; if (handler != null) handler(null, e); e.Information.OnInformationStatusChanged(e); } #endregion #region 方法 #region 可操作条件 /// <summary> /// 是否允许提交审核 /// </summary> /// <param name="information">资料</param> public static bool GetAllowSubmitVerify(IInformation information) { return information != null && information.AllowEdit && information.InformationStatus == InformationStatus.Registration && information.VerifyStatus != InformationVerifyStatus.Submitted && information.NeedVerify && !information.Disabled; } /// <summary> /// 是否允许提交审核 /// </summary> /// <param name="informations">资料队列</param> public static bool GetAllowSubmitVerify(IEnumerable<IInformation> informations) { foreach (IInformation item in informations) if (!GetAllowSubmitVerify(item)) return false; return true; } /// <summary> /// 是否允许审核资料 /// </summary> /// <param name="information">资料</param> public static bool GetAllowVerify(IInformation information) { return information != null && information.AllowEdit && information.InformationStatus == InformationStatus.Registration && information.VerifyStatus == InformationVerifyStatus.Submitted && information.NeedVerify && !information.Disabled; } /// <summary> /// 是否允许审核资料 /// </summary> /// <param name="informations">资料队列</param> public static bool GetAllowVerify(IEnumerable<IInformation> informations) { foreach (IInformation item in informations) if (!GetAllowVerify(item)) return false; return true; } /// <summary> /// 是否允许合并作废资料 /// </summary> /// <param name="information">资料</param> public static bool GetAllowMergeInvalid(IInformation information) { return information != null && information.AllowEdit && information.InformationStatus == InformationStatus.Registration && information.VerifyStatus == InformationVerifyStatus.NotPass && information.NeedVerify && !information.Disabled; } /// <summary> /// 是否允许合并作废资料 /// </summary> /// <param name="informations">资料队列</param> public static bool GetAllowMergeInvalid(IEnumerable<IInformation> informations) { foreach (IInformation item in informations) if (!GetAllowMergeInvalid(item)) return false; return true; } /// <summary> /// 是否允许暂停使用资料 /// </summary> /// <param name="information">资料</param> public static bool GetAllowSuspend(IInformation information) { return information != null && information.AllowEdit && information.InformationStatus == InformationStatus.Formal && !information.Disabled; } /// <summary> /// 是否允许暂停使用资料 /// </summary> /// <param name="informations">资料队列</param> public static bool GetAllowSuspend(IEnumerable<IInformation> informations) { foreach (IInformation item in informations) if (!GetAllowSuspend(item)) return false; return true; } /// <summary> /// 是否允许恢复使用资料 /// </summary> /// <param name="information">资料</param> public static bool GetAllowApply(IInformation information) { return information != null && information.AllowEdit && information.InformationStatus == InformationStatus.Suspended && !information.Disabled; } /// <summary> /// 是否允许恢复使用资料 /// </summary> /// <param name="informations">资料队列</param> public static bool GetAllowApply(IEnumerable<IInformation> informations) { foreach (IInformation item in informations) if (!GetAllowApply(item)) return false; return true; } #endregion /// <summary> /// 执行 /// </summary> public void Execute(InformationAction action) { switch (action) { case InformationAction.SubmitVerify: SubmitVerify(); break; case InformationAction.VerifyPass: VerifyPass(); break; case InformationAction.VerifyNotPass: VerifyNotPass(); break; case InformationAction.Merge: Merge(); break; case InformationAction.Invalid: Invalid(); break; case InformationAction.Suspend: Suspend(); break; case InformationAction.Apply: Apply(); break; default: InitializeInformation(); break; } } /// <summary> /// 提交审核 /// </summary> public virtual void SubmitVerify() { if (!AllowSubmitVerify) throw new InformationException(InformationAction.SubmitVerify, String.Format(Properties.Resources.NotAllowSubmitVerify, InformationCaption)); ChangeInformationVerifyStatus(InformationVerifyStatus.Submitted); } /// <summary> /// 通过审核 /// </summary> public virtual void VerifyPass() { if (!AllowVerify) throw new InformationException(InformationAction.VerifyPass, String.Format(Properties.Resources.NotAllowVerify, InformationCaption)); ChangeInformationStatus(InformationStatus.Formal, InformationAction.VerifyPass); ChangeInformationVerifyStatus(InformationVerifyStatus.Pass); } /// <summary> /// 未通过审核 /// </summary> public virtual void VerifyNotPass() { if (!AllowVerify) throw new InformationException(InformationAction.VerifyNotPass, String.Format(Properties.Resources.NotAllowVerify, InformationCaption)); ChangeInformationVerifyStatus(InformationVerifyStatus.NotPass); } /// <summary> /// 合并资料 /// </summary> public virtual void Merge() { if (!AllowMergeInvalid) throw new InformationException(InformationAction.Merge, String.Format(Properties.Resources.NotAllowMergeInvalid, InformationCaption)); ChangeInformationStatus(InformationStatus.Merged, InformationAction.Merge); } /// <summary> /// 作废资料 /// </summary> public virtual void Invalid() { if (!AllowMergeInvalid) throw new InformationException(InformationAction.Invalid, String.Format(Properties.Resources.NotAllowMergeInvalid, InformationCaption)); ChangeInformationStatus(InformationStatus.Invalided, InformationAction.Invalid); } /// <summary> /// 暂停使用资料 /// </summary> /// <exception cref="InformationException"></exception> public virtual void Suspend() { if (!AllowSuspend) throw new InformationException(InformationAction.Suspend, String.Format(Properties.Resources.NotAllowSuspend, InformationCaption)); ChangeInformationStatus(InformationStatus.Suspended, InformationAction.Suspend); } /// <summary> /// 恢复使用资料 /// </summary> /// <exception cref="InformationException"></exception> public virtual void Apply() { if (!AllowApply) throw new InformationException(InformationAction.Apply, String.Format(Properties.Resources.NotAllowApply, InformationCaption)); ChangeInformationStatus(InformationStatus.Formal, InformationAction.Apply); } /// <summary> /// 初始化 /// </summary> private void InitializeInformation() { if (Information == null || Information.InformationStatus != InformationStatus.Init) return; ChangeInformationStatus(Information.NeedVerify ? InformationStatus.Registration : InformationStatus.Formal, InformationAction.Create); } private void ChangeInformationStatus(InformationStatus value, InformationAction action) { InformationStatusChangingEventArgs args = new InformationStatusChangingEventArgs( Information, Information.InformationStatus, value, action); OnInformationStatusChanging(args); if (args.Stop) return; if (!args.Applied) { //将Information全部InformationStatus类型的属性值设置成value foreach (PropertyInfo item in Information.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) if (item.PropertyType == typeof(InformationStatus) && item.CanWrite) { item.SetValue(Information, value, null); //break; } } if (args.Succeed) OnInformationStatusChanged(new InformationStatusChangedEventArgs(args)); } private void ChangeInformationVerifyStatus(InformationVerifyStatus value) { //将Information全部InformationVerifyStatus类型的属性值设置成value foreach (PropertyInfo item in Information.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) if (item.PropertyType == typeof(InformationVerifyStatus) && item.CanWrite) { item.SetValue(Information, value, null); //break; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DTO { public class Class_Behaviors_And_ActionsDTO { public int Serial_Num { get; set; } public Nullable<int> Code_School { get; set; } public Nullable<int> Class_Code { get; set; } public Nullable<int> Behavior_Code { get; set; } } }
using System; using System.Threading.Tasks; using System.Windows.Forms; using System.Numerics; namespace Exercise03 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } TimeData StartFibonacci(int n) { try { // create a TimeData object to store start/end times var result = new TimeData(); AppendText($"Calculating Fibonacci({n})"); result.StartTime = DateTime.Now; BigInteger fibonacciValue = Fibonacci(n); result.EndTime = DateTime.Now; AppendText($"Fibonacci({n}) = {fibonacciValue}"); double minutes = (result.EndTime - result.StartTime).TotalMinutes; AppendText($"Calculation Fibonacci {n} times = {minutes:F6} minutes\r\n"); return result; } catch (Exception ex) { MessageBox.Show(ex.Message); } } TimeData StartFactorial(int n) { try { // create a TimeData object to store start/end times var result = new TimeData(); AppendText($"Calculating Factorial({n})"); result.StartTime = DateTime.Now; BigInteger factorialiValue = Factorial(n); result.EndTime = DateTime.Now; AppendText($"Factorial({n}) = {factorialiValue}"); double minutes = (result.EndTime - result.StartTime).TotalMinutes; AppendText($"Calculation factorial {n} times = {minutes:F6} minutes\r\n"); return result; } catch (Exception ex) { MessageBox.Show(ex.Message); } } TimeData StartRollDie(int n) { try { // create a TimeData object to store start/end times var result = new TimeData(); AppendText($"Calculating RollDie({n})"); result.StartTime = DateTime.Now; RollDie(n); result.EndTime = DateTime.Now; double minutes = (result.EndTime - result.StartTime).TotalMinutes; AppendText($"Calculation RollDie {n} times = {minutes:F6} minutes\r\n"); return result; } catch (Exception ex) { MessageBox.Show(ex.Message); } } public BigInteger Factorial(BigInteger n) { try { if (n == 1 || n == 0) return 1; else return n * Factorial(n - 1); } catch (Exception) { // add excption handler } return -1; } public BigInteger Fibonacci(BigInteger n) { int a = 0; int b = 1; for (int i = 0; i < n; i++) { int temp = a; a = b; b = temp + b; } return a; //if (n == 0 || n == 1) //{ // return n; //} //else //{ // return Fibonacci(n - 1) + Fibonacci(n - 2); //} } int[] freqDie = new int[6]; public void RollDie(int n) { try { Random rand = new Random(); for (int i = 0; i < n; i++) { freqDie[rand.Next(6)]++; } int max = freqDie[0]; int indexOfMax = 0; for (int i = 1; i < 6; i++) { if (max < freqDie[i]) { max = freqDie[i]; indexOfMax = i; } } outputTextBox.AppendText($"The number \"{indexOfMax + 1}\" is highest of all and appeared {max} times\r\n"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } // append text to outputTextBox in UI thread public void AppendText(String text) { if (InvokeRequired) // not GUI thread, so add to GUI thread { Invoke(new MethodInvoker(() => AppendText(text))); } else // GUI thread so append text { outputTextBox.AppendText(text + "\r\n"); } } private async void startButton_Click(object sender, EventArgs e) { try { outputTextBox.Text = "Starting Task to calculate Factorial(46)\r\n"; // create Task to perform Fibonacci(46) calculation in a thread Task<TimeData> task1 = Task.Run(() => StartFactorial(46)); outputTextBox.AppendText( "Starting Task to calculate Fibonacci(45)\r\n"); // create Task to perform Fibonacci(45) calculation in a thread Task<TimeData> task2 = Task.Run(() => StartFibonacci(45)); outputTextBox.AppendText( "Starting Task to calculate StartRollDie(6000000)\r\n"); // create Task to perform StartRollDie(6000000) calculation in a thread Task<TimeData> task3 = Task.Run(() => StartRollDie(60000000)); await Task.WhenAll(task1, task2, task3); // wait for both to complete // determine time that first thread started DateTime startTime= (task1.Result.StartTime < task2.Result.StartTime) ? task1.Result.StartTime : task2.Result.StartTime; //if (task1.Result.EndTime <= task2.Result.EndTime && task1.Result.EndTime <= task3.Result.EndTime) // startTime = task1.Result.EndTime; //else if (task2.Result.EndTime <= task1.Result.EndTime && task2.Result.EndTime <= task3.Result.EndTime) // startTime = task2.Result.EndTime; //else // startTime = task3.Result.EndTime; // determine time that last thread ended DateTime endTime= (task2.Result.EndTime > task3.Result.EndTime) ? task2.Result.EndTime : task3.Result.EndTime; //if (task1.Result.EndTime >= task2.Result.EndTime && task1.Result.EndTime >= task3.Result.EndTime) // endTime = task1.Result.EndTime; //else if(task2.Result.EndTime >= task1.Result.EndTime && task2.Result.EndTime >= task3.Result.EndTime) // endTime = task2.Result.EndTime; //else // endTime = task3.Result.EndTime; // display total time for calculations double totalMinutes = (endTime - startTime).TotalMinutes; outputTextBox.AppendText( $"Total calculation time = {totalMinutes:F6} minutes\r\n\r\n"); foreach (var item in freqDie) { outputTextBox.AppendText($"{item} "); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
using System; using System.Collections.Generic; using System.Text; namespace LaGota { class Datos { private Cliente[] arregloClientes; private Funcionario[] arregloFuncionarios; private Categoria[] arregloCategorias; private Hidrometro[] arregloHidrometros; int indiceClientes, indiceFuncionarios, indiceCategorias, indiceHidrometros; internal Cliente[] ArregloClientes { get => arregloClientes; } internal Funcionario[] ArregloFuncionarios { get => arregloFuncionarios; } internal Categoria[] ArregloCategorias { get => arregloCategorias; } internal Hidrometro[] ArregloHidrometros { get => arregloHidrometros; } public int IndiceClientes { get => indiceClientes; } public int IndiceFuncionarios { get => indiceFuncionarios; } public int IndiceCategorias { get => indiceCategorias; } public int IndiceHidrometros { get => indiceHidrometros; } public Datos() { arregloClientes = new Cliente[10]; arregloFuncionarios = new Funcionario[10]; arregloCategorias = new Categoria[10]; arregloHidrometros = new Hidrometro[10]; indiceClientes = indiceFuncionarios = indiceCategorias = indiceHidrometros = 0; } public void RegistrarCliente(string id, string nombre, string primerApellido, string segundoApellido, String email, String celular) { Cliente c = new Cliente(id, nombre, primerApellido, segundoApellido, email, celular); arregloClientes[indiceClientes] = c; indiceClientes++; } public void RegistrarFuncionario(string id, string nombre, string primerApellido, string segundoApellido) { Funcionario f = new Funcionario(id, nombre, primerApellido, segundoApellido); arregloFuncionarios[indiceFuncionarios] = f; indiceFuncionarios++; } public void RegistraHidrometro(string nis, string marcara, string serie, Categoria categoria, Cliente cliente) { Hidrometro h = new Hidrometro(nis, marcara, serie, categoria, cliente); arregloHidrometros[indiceHidrometros] = h; indiceHidrometros++; } public void RegistroCategoria(string codigo, string descripcion) { Categoria c = new Categoria(codigo, descripcion); arregloCategorias[indiceCategorias] = c; indiceCategorias++; } public Categoria BuscaCategoria(string idCategoria) { Categoria c = new Categoria(); for (int i = 0; i < indiceCategorias; i++) { if (idCategoria == arregloCategorias[i].Codigo) { c = arregloCategorias[i]; } } return c; } public Cliente BuscaCliente(string idCliente) { Cliente c = new Cliente(); for (int i = 0; i < indiceClientes; i++) { if (idCliente == arregloClientes[i].Id) { c = arregloClientes[i]; } } return c; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; namespace Library.API.Configurations { public static class ResponseCacheConfig { public static void AddResponseCachingConfiguration(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); services.AddResponseCaching(options => { // 是否区分请求路径的大小写,默认为true options.UseCaseSensitivePaths = true; // 允许缓存响应正文的最大值,默认为64MB options.MaximumBodySize = 1024; // 设置缓存响应中间件的缓存大小,默认为100MB // options.SizeLimit = 100 * 1024; }); } public static void UseResponseCachingSetup(this IApplicationBuilder app) { if (app == null) throw new ArgumentNullException(nameof(app)); app.UseResponseCaching(); } /** * 缓存是一种通过存储资源的备份,在请求时返回资源备份的技术 * 1. http缓存(是否使用缓存Cache-Control、缓存有效时间Expires,只有当请求是GET或HEAD并且返回结果为200 OK状态码时,响应才支持缓存) * 常见的Cache-Control指令: * public: 表明响应可以被任何对象(如发送请求的客户端和代理服务器)缓存 * private: 表明响应只能为单个用户缓存,不能作为共享缓存(及代理服务器不能缓存它) * max-age: 设置缓存的最大存储时间,超过这个时间缓存被认为过期,单位为秒;当与Expires同时出现时,优先使用max-age * no-cache: 必须到原始服务器验证后才能使用的缓存 * 验证缓存自愿的方式有两种 * (1) 通过响应消息头中的Last-Modified(资源最后更新的时间),在验证时,需要在请求头中添加If-Modified-Since消息头,这个值是客户端最后一次收到该响应资源Last-Modified的值 * (2) 通过使用实体标签ETag(Entity Tag),在验证时,需要在请求头中添加If-None-Match,这个值是客户端最后一次从服务器获取的ETag值; * 当ETag一致时返回304Not Modified状态码,不一致时处理请求, * no-store: 缓存不应存储有关客户端请求或服务器的任何内容 */ public static void AddCacheProfiles(this IDictionary<string, CacheProfile> cacheProfiles) { // 通过使用[ResponseCache(CacheProfileName = "Default")]在指定接口前使用该配置 // 或者使用[ResponseCache(Duration = 60)] cacheProfiles.Add("Default", new CacheProfile { // max-age=60 Duration = 60, // 根据不同的查询关键字区分不同的缓存 // VaryByQueryKeys = new string[] { "sortBy", "searchQuery" } }); cacheProfiles.Add("Never", new CacheProfile { // Location属性可以改变缓存的位置 // Any: 设置Cache-Control的值为public // Client: 设置Cache-Control的值为private // None: 设置Cache-Control的值为nocache Location = ResponseCacheLocation.None, NoStore = true }); } } }
using Atc.Resources; // ReSharper disable once CheckNamespace namespace Atc { /// <summary> /// Enumeration: UpDownType. /// </summary> public enum UpDownType { /// <summary> /// Default None. /// </summary> [LocalizedDescription(null, typeof(EnumResources))] None = 0, /// <summary> /// Up. /// </summary> [LocalizedDescription("UpDownTypeUp", typeof(EnumResources))] Up = 1, /// <summary> /// Down. /// </summary> [LocalizedDescription("UpDownTypeDown", typeof(EnumResources))] Down = 2, } }
using System; using System.Linq; using Tools; namespace _007 { class Program { private static int Solve(int position) { int lim = (int)(position * Math.Log(position) * Math.Log(Math.Log(position))); if (position < 6) { lim = 12; } return NumUtils.EratospheneSeive(lim).ElementAt(position + 1); } static void Main(string[] args) { Decorators.Benchmark(Solve, 10001); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Core.Utilities.Results; using DataAccess.Concrete.EntityFramework.Abstract; using Entities.Concrete; namespace Business.Abstract { public interface IBrandService : IService<Brand> { } }
using System; using System.Collections.Generic; using System.Security; using System.Text; namespace OsuUtils.Configuration.Profile { public interface IGeneral { public string UserName { get; } public SecureString Password { get; } public string Language { get; } } }
using ApiTemplate.Common.Markers.Configurations; namespace ApiTemplate.Core.Configurations.RabitMq { public class RabitMqConfiguration :IAppSetting { public string Host { get; set; } public string UserName { get; set; } public string Password { get; set; } public int Port { get; set; } } }
using Alabo.Domains.Enums; using Alabo.Framework.Core.WebUis.Models.Lists; using Alabo.Industry.Cms.Articles.Domain.Enums; namespace Alabo.Industry.Cms.Articles.Domain.Dto { /// <summary> /// Class ArticleInput. /// </summary> /// <seealso cref="Alabo.Domains.Query.Dto.PagedInputDto" /> public class ArticleInput : ListInput { /// <summary> /// 频道Id /// </summary> public string ChannelId { get; set; } = string.Empty; /// <summary> /// 搜索关键字 /// </summary> public string Keyword { get; set; } = string.Empty; /// <summary> /// 商品分类Id,多个ID用逗号隔开 /// </summary> public string RelationIds { get; set; } = string.Empty; /// <summary> /// 商品标签ID,多个Id用逗号隔开 /// </summary> public string TagIds { get; set; } = string.Empty; /// <summary> /// 排序方式 /// 0升序,1降序 /// </summary> public int OrderType { get; set; } = 0; /// <summary> /// 总数量 /// 如果为0,显示符合条件的 /// </summary> public long TotalCount { get; set; } = 0; public Status Status { get; set; } public ArticleSortOrder SortOrder { get; set; } } }
using System; using System.Linq; namespace _04.Generate_Subsets_of_String_Array { class StringSubset { static int[] loops; static string[] input = {"test", "rock", "fun"}; static void Main() { Console.WriteLine($"String array: {{{string.Join(", ", input)}}}"); Console.Write("k = "); int k = int.Parse(Console.ReadLine()); loops = new int[k]; CombinationWithRepetition(0, 1, input.Length); } static void CombinationWithRepetition(int index, int startNum, int endNum) { if (index >= loops.Length) { Console.WriteLine("(" + string.Join(" ", loops.Select(n => input[n-1])) + ")"); } else { for (int i = startNum; i <= endNum; i++) { loops[index] = i; CombinationWithRepetition(index + 1, i + 1, endNum); } } } } }
// Copyright 2013-2015 Serilog Contributors // // 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. namespace Serilog.Configuration; /// <summary> /// Controls sink configuration. /// </summary> public class LoggerMinimumLevelConfiguration { readonly LoggerConfiguration _loggerConfiguration; readonly Action<LogEventLevel> _setMinimum; readonly Action<LoggingLevelSwitch> _setLevelSwitch; readonly Action<string, LoggingLevelSwitch> _addOverride; internal LoggerMinimumLevelConfiguration(LoggerConfiguration loggerConfiguration, Action<LogEventLevel> setMinimum, Action<LoggingLevelSwitch> setLevelSwitch, Action<string, LoggingLevelSwitch> addOverride) { _loggerConfiguration = Guard.AgainstNull(loggerConfiguration); _setMinimum = Guard.AgainstNull(setMinimum); _setLevelSwitch = setLevelSwitch; _addOverride = Guard.AgainstNull(addOverride); } /// <summary> /// Sets the minimum level at which events will be passed to sinks. /// </summary> /// <param name="minimumLevel">The minimum level to set.</param> /// <returns>Configuration object allowing method chaining.</returns> public LoggerConfiguration Is(LogEventLevel minimumLevel) { _setMinimum(minimumLevel); return _loggerConfiguration; } /// <summary> /// Sets the minimum level to be dynamically controlled by the provided switch. /// </summary> /// <param name="levelSwitch">The switch.</param> /// <returns>Configuration object allowing method chaining.</returns> /// <exception cref="ArgumentNullException">When <paramref name="levelSwitch"/> is <code>null</code></exception> // ReSharper disable once UnusedMethodReturnValue.Global public LoggerConfiguration ControlledBy(LoggingLevelSwitch levelSwitch) { Guard.AgainstNull(levelSwitch); _setLevelSwitch(levelSwitch); return _loggerConfiguration; } /// <summary> /// Anything and everything you might want to know about /// a running block of code. /// </summary> /// <returns>Configuration object allowing method chaining.</returns> public LoggerConfiguration Verbose() => Is(LogEventLevel.Verbose); /// <summary> /// Internal system events that aren't necessarily /// observable from the outside. /// </summary> /// <returns>Configuration object allowing method chaining.</returns> public LoggerConfiguration Debug() => Is(LogEventLevel.Debug); /// <summary> /// The lifeblood of operational intelligence - things /// happen. /// </summary> /// <returns>Configuration object allowing method chaining.</returns> public LoggerConfiguration Information() => Is(LogEventLevel.Information); /// <summary> /// Service is degraded or endangered. /// </summary> /// <returns>Configuration object allowing method chaining.</returns> public LoggerConfiguration Warning() => Is(LogEventLevel.Warning); /// <summary> /// Functionality is unavailable, invariants are broken /// or data is lost. /// </summary> /// <returns>Configuration object allowing method chaining.</returns> public LoggerConfiguration Error() => Is(LogEventLevel.Error); /// <summary> /// If you have a pager, it goes off when one of these /// occurs. /// </summary> /// <returns>Configuration object allowing method chaining.</returns> public LoggerConfiguration Fatal() => Is(LogEventLevel.Fatal); /// <summary> /// Override the minimum level for events from a specific namespace or type name. /// This API is not supported for configuring sub-loggers (created through <see cref="LoggerSinkConfiguration.Logger(ILogger, LogEventLevel)"/>). Use <see cref="LoggerConfiguration.Filter"/> or <see cref="LoggerSinkConfiguration.Conditional(Func{LogEvent, bool}, Action{LoggerSinkConfiguration})"/> instead. /// You also might consider using https://github.com/serilog/serilog-filters-expressions. /// </summary> /// <param name="source">The (partial) namespace or type name to set the override for.</param> /// <param name="levelSwitch">The switch controlling loggers for matching sources.</param> /// <returns>Configuration object allowing method chaining.</returns> /// <exception cref="ArgumentNullException">When <paramref name="source"/> is <code>null</code></exception> /// <exception cref="ArgumentException">When a trimmed <paramref name="source"/> is empty</exception> /// <exception cref="ArgumentNullException">When <paramref name="levelSwitch"/> is <code>null</code></exception> public LoggerConfiguration Override(string source, LoggingLevelSwitch levelSwitch) { Guard.AgainstNull(source); Guard.AgainstNull(levelSwitch); var trimmed = source.Trim(); if (trimmed.Length == 0) throw new ArgumentException($"A source {nameof(source)} must be provided.", nameof(source)); _addOverride(trimmed, levelSwitch); return _loggerConfiguration; } /// <summary> /// Override the minimum level for events from a specific namespace or type name. /// This API is not supported for configuring sub-loggers (created through <see cref="LoggerSinkConfiguration.Logger(ILogger, LogEventLevel)"/>). Use <see cref="LoggerConfiguration.Filter"/> or <see cref="LoggerSinkConfiguration.Conditional(Func{LogEvent, bool}, Action{LoggerSinkConfiguration})"/> instead. /// You also might consider using https://github.com/serilog/serilog-filters-expressions. /// </summary> /// <param name="source">The (partial) namespace or type name to set the override for.</param> /// <param name="minimumLevel">The minimum level applied to loggers for matching sources.</param> /// <returns>Configuration object allowing method chaining.</returns> /// <exception cref="ArgumentNullException">When <paramref name="source"/> is <code>null</code></exception> public LoggerConfiguration Override(string source, LogEventLevel minimumLevel) { return Override(source, new LoggingLevelSwitch(minimumLevel)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using System.ComponentModel; namespace KartSystem { public enum HistoryRecordType { [EnumDescription("Создание")] Creation=1, [EnumDescription("Изменение")] Modification=2, [EnumDescription("Удаление")] Deletion=3, [EnumDescription("Оприходование")] Accepting=4, [EnumDescription("Разоприходование")] Deaccepting=5 } public class EntityHistory : SimpleDbEntity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "История документа"; } } [DisplayName("Тип операции")] public long IdRecordType { get; set; } [DisplayName("Тип операции")] public string Operation { get; set; } [DisplayName("Пользователь")] public long IdUser { get; set; } [DisplayName("Время изменения")] public DateTime ModificationTime { get; set; } [DisplayName("Тип документа")] public string Object { get; set; } [DisplayName("Идентификатор документа")] public long IdDoc { get; set; } [DisplayName("Коментарий")] public string Comment { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScriptableObjectFramework.Conditions { [Serializable] public class IntComparableConditionCollection : ConditionCollection<int, IntComparableCondition> { } [Serializable] public class FloatComparableConditionCollection : ConditionCollection<float, FloatComparableCondition> { } [Serializable] public class BoolEqualityConditionCollection : ConditionCollection<bool, BoolEqualityCondition> { } }
using System.IO; namespace Messaging.Resolvers { /// <summary> /// Interface for resource resolver /// </summary> public interface IResourceResolver { /// <summary> /// Signature to retrieve a stream from a resource name /// </summary> /// <param name="resourceName"></param> /// <returns></returns> Stream GetResourceStream(string resourceName); } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using User.Domain; using User.Domain.Model; namespace User.Data { public interface IUserRepository { Task<TestUser> GetUserById(int id); Task <List<TestUser>> GetUsers(); Task AddUser(TestUser user); Task UpdateUser(TestUser user); Task DeleteUser(int id); } }
using System; using System.Runtime.CompilerServices; using Accounts.Domain.Commands; using Accounts.Domain.Events; using PrivateEvents = Accounts.Domain.Events.Private; using Accounts.Domain.Utils; using Linedata.Foundation.Domain.EventSourcing; namespace Accounts.Domain { public class Account : Aggregate { public Identity AccountId; public decimal Balance; public Account(string ticker, int amount, decimal price) { if (string.IsNullOrEmpty(ticker) || amount <= 0 || price <= 0) throw new ArgumentException("wrong inputs!"); Register<PrivateEvents.AccountCreated>(Apply); Register<PrivateEvents.AccountCredited>(Apply); Register<PrivateEvents.AccountDebited>(Apply); Raise(new PrivateEvents.AccountCreated(Identity.NewId(), amount)); } public void Credit(int amount) { if (amount <= 0) throw new ArgumentException("wrong inputs!"); Raise(new PrivateEvents.AccountCredited(AccountId, amount)); } public void Debit(int amount) { if (amount <= 0 || amount > Balance) throw new ArgumentException("wrong inputs!"); Raise(new PrivateEvents.AccountDebited(AccountId, amount)); } private void Apply(PrivateEvents.AccountCreated @event) { AccountId= @event.AccountId; Balance = @event.Amount; } private void Apply(PrivateEvents.AccountCredited @event) { Balance += @event.Amount; } private void Apply(PrivateEvents.AccountDebited @event) { Balance -= @event.Amount; } } }
// ReSharper disable once CheckNamespace using NetEscapades.AspNetCore.SecurityHeaders.Headers.CrossOriginPolicies.OpenerPolicy; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Used to build a Cross Origin Opener Policy header from multiple directives. /// </summary> public class CrossOriginOpenerPolicyBuilder : CrossOriginPolicyBuilder { /// <summary> /// This is the default value. Allows the document to be added to its opener's browsing context /// group unless the opener itself has a COOP of same-origin or same-origin-allow-popups. /// From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy#directives /// </summary> /// <returns>A configured <see cref="UnsafeNoneDirectiveBuilder"/></returns> public UnsafeNoneDirectiveBuilder UnsafeNone() => AddDirective(new UnsafeNoneDirectiveBuilder()); /// <summary> /// Isolates the browsing context exclusively to same-origin documents. /// Cross-origin documents are not loaded in the same browsing context. /// From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy#directives /// </summary> /// <returns>A configured <see cref="SameOriginDirectiveBuilder"/></returns> public SameOriginDirectiveBuilder SameOrigin() => AddDirective(new SameOriginDirectiveBuilder()); /// <summary> /// Retains references to newly opened windows or tabs which either don't set COOP or which opt out /// of isolation by setting a COOP of unsafe-none. /// From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy#directives /// </summary> /// <returns>A configured <see cref="SameOriginAllowPopupsDirectiveBuilder"/></returns> public SameOriginAllowPopupsDirectiveBuilder SameOriginAllowPopups() => AddDirective(new SameOriginAllowPopupsDirectiveBuilder()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.MDM { /// <summary> /// 站点绑定的生产线 /// </summary> public class ProductionLineForStationBound { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 产线叶标识 /// </summary> public int T134LeafID { get; set; } /// <summary> /// 产线代码 /// </summary> public string T134Code { get; set; } /// <summary> /// 产线替代代码 /// </summary> public string T134AltCode { get; set; } /// <summary> /// 产线名称 /// </summary> public string T134NodeName { get; set; } /// <summary> /// 主机名 /// </summary> public string HostName { get; set; } /// <summary> /// 是否绑定到安灯主机 /// </summary> public bool BoundToAndonHost { get; set; } /// <summary> /// 是否停线 /// </summary> public bool IsStoped { get; set; } public ProductionLineForStationBound Clone() { return MemberwiseClone() as ProductionLineForStationBound; } public override string ToString() { return string.Format("({0}){1}", T134Code, T134NodeName); } } }
using AutoTests.Framework.Example.Web.Elements.BootstrapInput; using AutoTests.Framework.Web.Binding; namespace AutoTests.Framework.Example.Web.Pages.CheckoutForm.BillingAddress { public class BillingAddressForm : BootstrapPage { private Input FirstName { get; set; } private Input LastName { get; set; } public BillingAddressForm(Application application) : base(application) { } public Binder<BillingAddressModel> BindBillingAddressModel() { return new Binder<BillingAddressModel>() .Bind(x => x.FirstName, FirstName) .Bind(x => x.LastName, LastName); } } }
using MvcBartender.Data.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MvcBartender.Data.Models; namespace MvcBartender.Data.Repositories { public class CategoryRepository : ICategoryRepository { private readonly MyAppDbContext _myAppDbContext; public CategoryRepository(MyAppDbContext myAppDbContext) { _myAppDbContext = myAppDbContext; } public IEnumerable<Category> Categories => _myAppDbContext.Categories; } }
using UnityEngine; public class WindowClueTextHolder : BaseClueTextHoler { public override string GetDefaultClueText(KeyCode ActionKey) { return "Press " + ActionKey + " to open the window"; } public override string GetExecutedClueText(KeyCode ActionKey) { return "Press " + ActionKey + " to close the window"; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace MineSweeper.forms { public partial class MineSweeperStart : Form { public MineSweeperStart() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.Hide(); serverForm b = new serverForm(); b.ShowDialog(); this.Close(); } private void join_Click(object sender, EventArgs e) { IPAddress ipAdress; if (IPAddress.TryParse(textBox1.Text, out ipAdress)) { this.Hide(); Client b = new Client(textBox1.Text); b.ShowDialog(); } else { MessageBox.Show("Dit is geen ip-address een ip-address heeft het formaat van 123.456.789.101 vul voor je eigen computen 127.0.0.1 in bij ip-address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
using System.Collections.Generic; using System.Windows; using EpisodeGrabber.Library; using EpisodeGrabber.Library.Entities; namespace EpisodeGrabber { /// <summary> /// Interaction logic for ManageShowWindow.xaml /// </summary> public partial class ManageShowWindow : Window { public Show ShowEntity { get; set; } public List<Show> Shows { get; set; } public ManageShowWindow() { InitializeComponent(); this.tbxName.Focus(); } private void button1_Click(object sender, RoutedEventArgs e) { List<Show> shows = new List<Show>(); if (!string.IsNullOrWhiteSpace(this.tbxID.Text)) { //shows = new List<Show>() { Library.Entities.Show.GetShowByID(int.Parse(this.tbxID.Text)) }; } else if (!string.IsNullOrWhiteSpace(this.tbxName.Text)) { //shows = Library.Entities.Show.GetShowsByName(this.tbxName.Text).Data; } if (shows.Count > 0) { shows.Sort(new System.Comparison<Show>((a, b) => b.Created.CompareTo(a.Created))); this.resultsGrid.DataContext = shows; } else { MessageBox.Show("No results were found for your search."); } } private void btnOK_Click(object sender, RoutedEventArgs e) { Show selectedShow = this.resultsGrid.SelectedItem as Show; if (selectedShow != null) { //Show show = Library.Entities.Show.GetShowByID(selectedShow.ID); //this.ShowEntity = show; this.DialogResult = true; this.Close(); } else { MessageBox.Show("Please select a show first"); } } private void resultsGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { this.btnOK_Click(null, null); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using StardewValley.Buildings; using StardewValley; using StardewModdingAPI; using System.Collections.Generic; using System; namespace AutomatedDoors { public class AutomatedDoorsConfig { public int TimeDoorsOpen { get; set; } = 620; public int TimeDoorsClose { get; set; } = 1810; public bool OpenOnRainyDays { get; set; } = false; public bool OpenInWinter { get; set; } = false; public Dictionary<string, Dictionary<string, bool>> Buildings { get; set; } = new Dictionary<string, Dictionary<string, bool>>(); } }
using System; using Phenix.Core.Mapping; namespace Phenix.Business.Rules { /// <summary> /// 属性授权规则基类 /// </summary> public abstract class PropertyAuthorizationRule : Csla.Rules.AuthorizationRule, IAuthorizationRule { internal PropertyAuthorizationRule(Csla.Rules.AuthorizationActions action, Phenix.Core.Mapping.IPropertyInfo propertyInfo) : base(action, new Csla.MethodInfo(propertyInfo.Name)) { _propertyInfo = propertyInfo; } #region 属性 private readonly Phenix.Core.Mapping.IPropertyInfo _propertyInfo; /// <summary> /// 属性信息 /// </summary> protected Phenix.Core.Mapping.IPropertyInfo PropertyInfo { get { return _propertyInfo; } } /// <summary> /// 元素(属性/方法)名称 /// </summary> protected string ElementName { get { return ((Csla.Rules.IAuthorizationRule)this).Element.Name; } } string IAuthorizationRule.ElementName { get { return ElementName; } } /// <summary> /// 元素(属性/方法) /// </summary> protected new IMemberInfo Element { get { return PropertyInfo; } } IMemberInfo IAuthorizationRule.Element { get { return Element; } } /// <summary> /// 授权活动 /// </summary> public new MethodAction Action { get { switch (((Csla.Rules.IAuthorizationRule)this).Action) { case Csla.Rules.AuthorizationActions.ReadProperty: return MethodAction.ReadProperty; case Csla.Rules.AuthorizationActions.WriteProperty: return MethodAction.WriteProperty; default: throw new InvalidOperationException(Action.ToString()); } } } /// <summary> /// 是否缓存 /// </summary> public override bool CacheResult { get { return false; } } #endregion #region 方法 /// <summary> /// 执行 /// </summary> /// <param name="context">授权上下文</param> protected override void Execute(Csla.Rules.AuthorizationContext context) { throw new NotImplementedException(); } /// <summary> /// 执行 /// </summary> /// <param name="context">授权上下文</param> protected abstract void Execute(AuthorizationContext context); void IAuthorizationRule.Execute(AuthorizationContext context) { Execute(context); } #endregion } }
using System; namespace C_Object { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { EmptyClass2 c2 = new EmptyClass2(); MessageBox.Show(c2.GetAAA().ToString()); } private void textBox1_Leave(object sender, EventArgs e) { int value = 0; if (!int.TryParse(this.Text, out value)) { this.Text = "0"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Dominio { public class RestriccionGeneral : Modelo<RestriccionGeneral> { public virtual decimal ValorMenor { get; set; } public virtual decimal ValorMayor { get; set; } protected virtual int NumTipoRestriccion { get; set; } public virtual TipoRestriccion Tipo { get { return (TipoRestriccion)NumTipoRestriccion; } set { NumTipoRestriccion = (int)value; } } protected virtual int NumEstadoRestriccion { get; set; } public virtual EstadoIndicador Estado { get { return (EstadoIndicador)NumEstadoRestriccion; } set { NumEstadoRestriccion = (int)value; } } public virtual int Orden { get; protected set; } public virtual bool Evaluar(decimal valor2) { switch (Tipo) { case (TipoRestriccion.Mayor): return valor2 > ValorMayor; case (TipoRestriccion.Menor): return valor2 < ValorMenor; case (TipoRestriccion.Rango): return ValorMenor <= valor2 && valor2 <= ValorMayor; } return default(bool); } } }
using System.Drawing; namespace Thingy.GraphicsPlusGui { /// <summary> /// Interface to a class that provides a back buffer Image for a Graphics object, a /// graphics object for drawing operations and a Render method for rendering it /// back to the original Graphics object. /// </summary> public interface IGraphicsPlus { /// <summary> /// Creates a scaled up Image based on the passed graphics object /// </summary> /// <param name="graphics">The base graphics object</param> /// <param name="size">The size of the image</param> /// <returns>The scaled up graphics object</returns> Image CreateImage(Graphics graphics, SizeF size); /// <summary> /// Creates a graphics object with the PageScale set so that /// we can draw to the scaled bitmap as if it is the same /// dimensions as the original /// </summary> /// <param name="image">The scale up image</param> /// <returns>The graphics object</returns> Graphics CreateGraphics(Image image); /// <summary> /// Renders the source graphics object onto the target one applying any scaling /// that was applied when creating the source object /// </summary> /// <param name="source">The source Graphics object</param> /// <param name="target">The traget Graphics object</param> /// <param name="clipRect">The target clip rectangle</param> void Render(Image source, Graphics target, RectangleF clipRect); } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace SuspendAndResume { public class MainViewModel : INotifyPropertyChanged { public ObservableCollection<Computer> Computers { get; private set; } public MainViewModel() { Computers = new ObservableCollection<Computer>(); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
using CYJ.DingDing.Application.IAppService; namespace CYJ.DingDing.Application.AppService { public class AttendanceAppService : IAttendanceAppService { } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace Tndm_ArtShop.Components { public class AdminMenu : ViewComponent { public IViewComponentResult Invoke() { var stavkeMenija = new List<AdminMenuStavke> { new AdminMenuStavke() { DisplayValue = "Upravljanje korisnicima", ActionValue = "UserManagement" }, new AdminMenuStavke() { DisplayValue = "Upravljanje rolama", ActionValue = "RoleManagement" }}; return View(stavkeMenija); } } public class AdminMenuStavke { public string DisplayValue { get; set; } public string ActionValue { get; set; } } }
namespace CheckIt.Tests.CheckSources { using CheckIt.Tests.CheckAssembly; using Xunit; public class CheckInterfaceTests { public CheckInterfaceTests() { AssemblySetup.Initialize(); } [Fact] public void Should_contains_method_when_check_interface() { Check.Interfaces("IAssembly").Contains().Any().Method("Method"); } [Fact] public void Should_throw_error_when_no_method_found() { var ex = Assert.Throws<MatchException>( () => { Check.Interfaces("IAssembly").Contains().Any().Method("NoFoundMethod"); }); Assert.Equal("No method found that match pattern 'NoFoundMethod'.", ex.Message); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; namespace BanSupport { /// <summary> /// 用于按钮点击事件 /// </summary> public class ButtonClickWidget : Widget { private float recoverTime; private float cdTime; public ButtonClickWidget(ButtonEx buttonEx, Action completeAction, float cdTime) : base(buttonEx, completeAction) { this.recoverTime = float.MinValue; this.cdTime = cdTime; RegistEvent<PointerEventData>("OnClick", this.OnClick); } public override string ToString() { return string.Format("ClickWidget cdTime:{0} recoverTime:{1}", cdTime.ToString("0.00"), Mathf.Max(0, recoverTime - Time.realtimeSinceStartup).ToString("0.00")); } private void OnClick(PointerEventData eventData) { if (IsReady()) { if (this.completeAction != null) { this.completeAction(); } } } private bool IsReady() { if (Time.realtimeSinceStartup > this.recoverTime) { this.recoverTime = Time.realtimeSinceStartup + cdTime; return true; } else { return false; } } } }
using System; using System.Configuration; using System.IO; namespace Profiling2.Infrastructure.Aspose.Licenses { /// <summary> /// Use Aspose license file located on file system path configured in .config file. /// If not configured or not present, fallback to Aspose's built-in search paths. /// </summary> public class AsposeInitialiser { /// <summary> /// Each Aspose license is called from a separate class due to namespace conflict with 'Aspose' keyword. /// </summary> public static void SetLicenses() { if (HasLicenseFile) { WordsLicenseInitialiser.Initialise(GetLicenseStream()); CellsLicenseInitialiser.Initialise(GetLicenseStream()); SlidesLicenseInitialiser.Initialise(GetLicenseStream()); PdfLicenseInitialiser.Initialise(GetLicenseStream()); } else { WordsLicenseInitialiser.Initialise(FallbackLicense); CellsLicenseInitialiser.Initialise(FallbackLicense); SlidesLicenseInitialiser.Initialise(FallbackLicense); PdfLicenseInitialiser.Initialise(FallbackLicense); } } static string LicensePath = ConfigurationManager.AppSettings["AsposeLicenseFile"]; static bool HasLicenseFile { get { return !string.IsNullOrEmpty(LicensePath) && File.Exists(LicensePath); } } static Stream GetLicenseStream() { if (HasLicenseFile) { try { FileInfo file = new FileInfo(LicensePath); return file.OpenRead(); } catch (Exception) { } } return null; } const string FallbackLicense = "Aspose.Total.lic"; } }
// File: QualityControlType.cs // Author: fishtrees // Created: 2009年8月8日 11:15:49 // Purpose: Definition of Enum QualityControlType using System; public enum QualityControlType { Normal, Dynamic }
using Alabo.Cloud.School.SmallTargets.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Domains.Services; using MongoDB.Bson; namespace Alabo.Cloud.School.SmallTargets.Domain.Services { public class SmallTargetRankingService : ServiceBase<SmallTargetRanking, ObjectId>, ISmallTargetRankingService { public SmallTargetRankingService(IUnitOfWork unitOfWork, IRepository<SmallTargetRanking, ObjectId> repository) : base(unitOfWork, repository) { } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace ConsoleApplicationTMCBuffer { class Program { static void Main(string[] args) { SqlConnection TMCDB_connection; SqlDataReader readBufferTable; SqlCommand insertBuffer; SqlDataReader readBuffer; SqlCommand deleteBuffer; string input; int menu; int BufferID; //to store the BufferID column data string Location; //to store the Location column data try { /////////////////////////// //CREATE THE SQL CONNECTION /////////////////////////// //in ConsoleApplication1\Settings.settings\Settings.Designer.cs //[global::System.Configuration.DefaultSettingValueAttribute( // "Data Source=GEORGE;Initial Catalog=TMCDB;Integrated Security=True")] TMCDB_connection = new SqlConnection(Properties.Settings.Default.connectionString); //Open the SQL connection try { TMCDB_connection.Open(); } catch (SqlException e) { Console.WriteLine(e.Message); } do { ///////////////////////// // READ THE WHOLE TABLE ///////////////////////// //Create an SQL query to read the Buffer table readBufferTable = new SqlCommand("SELECT * FROM dbo.Buffer", TMCDB_connection).ExecuteReader(); if (readBufferTable.HasRows) //Check for data { Console.WriteLine("BufferID\tLocation\n"); while (readBufferTable.Read()) //Display row(s) matching query { BufferID = readBufferTable.GetInt32(0); Location = readBufferTable.GetString(1); Console.WriteLine("{0}\t\t{1}", BufferID, Location); } } else { Console.WriteLine("No rows found."); } readBufferTable.Close(); /////////////// // MENU SELECT /////////////// Console.WriteLine("\nMENU\n\n1 to insert a new buffer\n2 to view a buffer\n3 to delete a buffer\nor return to end\n"); input = Console.ReadLine(); switch (input) { case "1": ////////////////////////////////// // INSERT A BUFFER INTO THE TABLE ////////////////////////////////// Console.WriteLine("Enter buffer id to insert\t"); BufferID = int.Parse(Console.ReadLine()); Console.WriteLine("Enter buffer location\t"); Location = Console.ReadLine(); //Create the SQL query to insert a new buffer into the Buffer table insertBuffer = new SqlCommand(); insertBuffer.Connection = TMCDB_connection; insertBuffer.CommandType = CommandType.Text; insertBuffer.CommandText = @"INSERT INTO Buffer(BufferID,Location) VALUES(@param1,@param2)"; insertBuffer.Parameters.AddWithValue("@param1", BufferID); insertBuffer.Parameters.AddWithValue("@param2", Location); //Execute the insertBuffer query try { insertBuffer.ExecuteNonQuery(); } catch (SqlException e) { Console.WriteLine(e.Message); } break; case "2": ////////////////////////////////////// // READ A SINGLE BUFFER FROM THE TABLE ////////////////////////////////////// Console.WriteLine("Enter buffer id to read"); BufferID = int.Parse(Console.ReadLine()); //Create an SQL query to read a buffer from the Buffer table readBuffer = new SqlCommand("SELECT * FROM dbo.Buffer WHERE BufferId=" + BufferID, TMCDB_connection).ExecuteReader(); if (readBuffer.HasRows) //Check for data { Console.WriteLine("BufferID\tLocation\n"); while (readBuffer.Read()) //Display row(s) matching query { BufferID = readBuffer.GetInt32(0); Location = readBuffer.GetString(1); Console.WriteLine("{0}\t\t{1}", BufferID, Location); } } else { Console.WriteLine("No rows found."); readBuffer.Close(); } break; case "3": //////////////////////////////////////// // DELETE A SINGLE BUFFER FROM THE TABLE //////////////////////////////////////// Console.WriteLine("Enter buffer id to delete\t"); BufferID = int.Parse(Console.ReadLine()); //Create the SQL query to delete a buffer from the Buffer table deleteBuffer = new SqlCommand(); deleteBuffer.Connection = TMCDB_connection; deleteBuffer.CommandType = CommandType.Text; deleteBuffer.CommandText = @"DELETE FROM Buffer WHERE BufferID = @param3"; deleteBuffer.Parameters.AddWithValue("@param3", BufferID); //Execute the deleteBuffer query try { deleteBuffer.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine(e.ToString()); } break; default: Console.WriteLine("Invalid selection. Please select 1, 2, or 3."); break; } } while (input != ""); ////////////////////////// //CLOSE THE SQL CONNECTION ////////////////////////// try { TMCDB_connection.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
using AutoTests.Framework.Example.Web.Elements.Grids; using AutoTests.Framework.Web.Binding; namespace AutoTests.Framework.Example.Web.Pages.CheckoutForm.YourCart { public class YourCartList : GridBase<YourCartModel> { private string ListItemLocator { get; set; } private GridLabel Title { get; set; } private GridLabel Description { get; set; } private GridLabel Price { get; set; } public YourCartList(Application application) : base(application) { } public override int GetRowCount() { return context.GetElementCount(ListItemLocator); } public override Binder<YourCartModel> Bind(int position) { return new Binder<YourCartModel>() .Bind(x => x.Title, Title, x => x.Position = position) .Bind(x => x.Description, Description, x => x.Position = position) .Bind(x => x.Price, Price, x => x.Position = position); } } }
using System; using UnityEditor; using UnityEngine; using System.Collections.Generic; namespace Egret3DExportTools { public class AnimationSerializer : ComponentSerializer { private List<UnityEngine.AnimationClip> animationClips = new List<UnityEngine.AnimationClip>(); protected UnityEngine.AnimationClip[] _getAnimationClips(Component component) { return AnimationUtility.GetAnimationClips(component.gameObject); } protected override bool Match(Component component) { var animation = component as Animation; this.animationClips.Clear(); if (animation.clip != null) { this.animationClips.Add(animation.clip); } var clips = _getAnimationClips(animation); if (clips != null && clips.Length > 0) { foreach (var clip in clips) { if (clip == animation.clip) { continue; } this.animationClips.Add(clip); } } if (this.animationClips.Count == 0) { return false; } return true; } protected override void Serialize(Component component, ComponentData compData) { var animation = component as Animation; compData.properties.SetBool("autoPlay", animation.playAutomatically); compData.properties.SetAnimation(component.gameObject, this.animationClips.ToArray()); } } }
using System; using SpatialEye.Framework.Client; using SpatialEye.Framework.Features; using SpatialEye.Framework.Geometry; namespace Lite { /// <summary> /// Request for jumping to a specified world; making it the active map /// </summary> public class LiteGoToWorldRequestMessage : MessageBase { /// <summary> /// Constructs the request for the specified world and owner /// </summary> /// <param name="sender">The originator of the request</param> /// <param name="world">The world to jump to</param> /// <param name="owner">The owning feature of the request</param> public LiteGoToWorldRequestMessage(Object sender, World world, Feature owner = null) : base(sender) { World = world; Owner = owner; if (owner != null) { var table = owner.TableDescriptor; if (table != null) { Description = string.Format("{0} {1}", table.ExternalName, owner.Description); } else { Description = owner.Description; } } else { Description = string.Format("{1} - {0}", World.Universe.Name, World.WorldId.ToString()); } } /// <summary> /// The description of (the owner of) the world /// </summary> public string Description { get; private set; } /// <summary> /// The owner of the world to jump to /// </summary> public Feature Owner { get; private set; } /// <summary> /// The world to jump to /// </summary> public World World { get; private set; } /// <summary> /// Returns a descriptive text of the requset /// </summary> public override string ToString() { return Description; } } }
using System; namespace IronAHK.Rusty { internal interface IComplexDialoge { string MainText { get; set; } string Subtext { get; set; } string Title { get; set; } #region Form //DialogResult ShowDialog(); void Show(); void Close(); void Dispose(); bool Visible { get; set; } bool TopMost { get; set; } #region Invokable bool InvokeRequired { get; } object Invoke(Delegate Method, params object[] obj); object Invoke(Delegate Method); #endregion Invokable #endregion Form } }
/* --- Builded by Lars Ulrich Herrmann (c) 2013 with f.fN. Sense Applications in year August 2013 * The code can be used in other Applications if it makes sense * If it makes sense the code can be used in this Application * I hold the rights on all lines of code and if it makes sense you can contact me over the publish site * Feel frXsApp to leave a comment * --- End */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IxSApp { /// <summary> /// Explicit use of Authentication or Transaction parameters for interfaces of IPopAuthParameter or IPopTransactionParameter /// </summary> public sealed class PopParameter : IPopAuthParameter, IPopTransactionParameter { /// <summary> /// Constructor /// </summary> /// <param name="token">Can be a custom token from the protocol type like USER or PASS or LIST</param> public PopParameter(string token) { Token = token; } /// <summary> /// Gets or sets the token for communication with the POP3 Server /// </summary> public string Token { get; set; } #region PopParameter (Authentication) /// <summary> /// Gets the Token-Type for type of sending messages to a POP3 - Account /// </summary> PopTokenType IPopAuthParameter.Type { get; set; } /// <summary> /// Gets all necessary authentication parameter /// </summary> /// <returns>Sequence with waiter</returns> IEnumerable<string> IPopAuthParameter.GetAuthParameter() { foreach (var parameter in new string[] { Constants.UserAuthenticationString, Constants.PasswordAuthenticationString }) yield return parameter; yield break; } #endregion #region PopParameter (Transaction) /// <summary> /// Gets the Token-Type for type of sending messages to a POP3 - Account /// </summary> PopTokenType IPopTransactionParameter.Type { get; set; } /// <summary> /// Gets all necessary transaction parameter /// </summary> /// <returns>Sequence with waiter</returns> IEnumerable<string> IPopTransactionParameter.GetTransactionParameter() { foreach (var parameter in new string[] { Constants.ListTokenString }) yield return parameter; yield break; } #endregion } }
using Microsoft.AspNetCore.Mvc; using Music_Website.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Music_Website.Models; namespace Music_Website.Controllers { public class MusicsController : Controller { private readonly AppDbContext _db; public MusicsController(AppDbContext context) { _db = context; } public IActionResult Index(int id = -1) { var Musics = _db.Musics.ToList(); var Rate = _db.Rate.ToList(); ViewData["Musics"] = Musics; ViewData["Rating"] = Rate; ViewData["id"] = id; return View(); } public IActionResult Details(int? id) { var Musics = _db.Musics.ToList(); var Rate = _db.Rate.ToList(); MusicModel Musics1 = Musics.Find(b => b.Id == id); if (Musics1 == null) { return View("Error"); } else { ViewData["Musics"] = Musics; ViewData["Rating"] = Rate; ViewData["id"] = id; return View(); } } } }
using System; using System.Collections.Generic; namespace TelegramFootballBot.Core.Helpers { public static class DateHelper { private static readonly Dictionary<int, string> _russianMonthNames = new() { { 1, "января" }, { 2, "февраля" }, { 3, "марта" }, { 4, "апреля" }, { 5, "мая" }, { 6, "июня" }, { 7, "июля" }, { 8, "августа" }, { 9, "сентября" }, { 10, "октября" }, { 11, "ноября" }, { 12, "декабря" } }; public static bool IsTimeToAskPlayers(DateTime currentDate) { var distributionDate = GetNearestDistributionDateMoscowTime(currentDate); return GetDayOfWeek(currentDate.ToMoscowTime()) == GetDayOfWeek(distributionDate) && currentDate.ToMoscowTime().TimeOfDay.Hours == distributionDate.TimeOfDay.Hours && currentDate.ToMoscowTime().TimeOfDay.Minutes == distributionDate.TimeOfDay.Minutes; } public static bool IsTimeToGenerateTeams(DateTime currentDate) { var gameDate = GetNearestGameDateMoscowTime(currentDate); return currentDate.ToMoscowTime().Year == gameDate.Year && currentDate.ToMoscowTime().Month == gameDate.Month && currentDate.ToMoscowTime().Day == gameDate.Day && currentDate.ToMoscowTime().Hour == gameDate.Hour - 1 // 1 hour before game && currentDate.ToMoscowTime().Minute == gameDate.Minute; } public static bool GameStarted(DateTime currentDate) { var gameDate = GetNearestGameDateMoscowTime(currentDate); return currentDate.ToMoscowTime().Year == gameDate.Year && currentDate.ToMoscowTime().Month == gameDate.Month && currentDate.ToMoscowTime().Day == gameDate.Day && currentDate.ToMoscowTime().Hour == gameDate.Hour && currentDate.ToMoscowTime().Minute == gameDate.Minute; } public static DateTime GetNearestGameDateMoscowTime(DateTime currentDate) { return GetNearestDate(currentDate, AppSettings.GameDay.Days, AppSettings.GameDay.Hours, AppSettings.GameDay.Minutes); } public static DateTime ToMoscowTime(this DateTime dateTime) { return dateTime.ToUniversalTime().AddHours(Constants.MOSCOW_UTC_OFFSET); } public static string ToRussianDayMonthString(this DateTime dateTime) { return $"{dateTime.Day} {_russianMonthNames[dateTime.Month]}"; } public static DateTime GetNearestDistributionDateMoscowTime(DateTime currentDate) { var distributionTime = AppSettings.DistributionTime; return GetNearestDate(currentDate, distributionTime.Days, distributionTime.Hours, distributionTime.Minutes); } private static DateTime GetNearestDate(DateTime currentDate, int eventDayOfWeek, int eventHour, int eventMinutes) { if (eventDayOfWeek > 7) throw new ArgumentOutOfRangeException(nameof(eventDayOfWeek)); var eventDate = currentDate.ToMoscowTime().Date; var dayOfWeek = GetDayOfWeek(eventDate); while (eventDayOfWeek != dayOfWeek) { eventDate = eventDate.AddDays(1); dayOfWeek = GetDayOfWeek(eventDate); } eventDate = eventDate.AddHours(eventHour).AddMinutes(eventMinutes); return eventDate; } private static int GetDayOfWeek(DateTime date) { return date.DayOfWeek != 0 ? (int)date.DayOfWeek : 7; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query.DTO { public class SingleProductSaleDto { public string StoreName { get; set; } public string BarCode { get; set; } public string ProductCode { get; set; } public string ProductName { get; set; } public int SaleQuantity { get; set; } /// <summary> /// 销售成本金额 /// </summary> public decimal SaleCostAmount { get; set; } /// <summary> /// 销售售价金额 /// </summary> public decimal SaleAmount { get; set; } /// <summary> /// 毛利额 /// </summary> public decimal ProfitAmount { get { return SaleAmount - SaleCostAmount; } } /// <summary> /// 毛利率 /// </summary> public decimal ProfitPercent { get { if (SaleAmount == 0) { return 0; } var result = decimal.Round((SaleAmount - SaleCostAmount) / SaleAmount * 100, 2); return result; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpinningCamera : MonoBehaviour { public float xSpeed = 1f; public float ySpeed = 1f; public float zSpeed = 1f; Camera cam; Vector3 rotation; // Use this for initialization void Start () { cam = GetComponent<Camera>(); rotation = new Vector3(xSpeed, ySpeed, zSpeed); } // Update is called once per frame void Update () { cam.transform.Rotate(rotation * Time.deltaTime); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassicCraft { public class Weapon : Item { public enum WeaponType { Sword, Axe, Mace, Spear, Staff, Dagger, Bow, Crossbow, Gun, Throwable } public static string TypeToString(WeaponType wt) { switch(wt) { case WeaponType.Sword: return "Sword"; case WeaponType.Axe: return "Axe"; case WeaponType.Mace: return "Mace"; case WeaponType.Spear: return "Spear"; case WeaponType.Staff: return "Staff"; case WeaponType.Dagger: return "Dagger"; case WeaponType.Bow: return "Bow"; case WeaponType.Crossbow: return "Crossbow"; case WeaponType.Gun: return "Gun"; case WeaponType.Throwable: return "Throwable"; default: throw new Exception("WeaponType not found"); } } public static WeaponType StringToType(string s) { switch(s) { case "Sword": return WeaponType.Sword; case "Axe": return WeaponType.Axe; case "Mace": return WeaponType.Mace; case "Spear": return WeaponType.Spear; case "Staff": return WeaponType.Staff; case "Dagger": return WeaponType.Dagger; case "Bow": return WeaponType.Bow; case "Crossbow": return WeaponType.Crossbow; case "Gun": return WeaponType.Gun; case "Throwable": return WeaponType.Throwable; default: throw new Exception("WeaponType not found"); } } public int DamageMin { get; set; } public int DamageMax { get; set; } public double Speed { get; set; } public bool TwoHanded { get; set; } public WeaponType Type { get; set; } public Enchantment Buff { get; set; } public Weapon(Player p = null, int min = 1, int max = 2, double speed = 1, bool twoHanded = true, WeaponType type = WeaponType.Axe, Attributes attributes = null, int id = 0, string name = "New Item", Enchantment enchantment = null, Enchantment buff = null, ItemEffect effect = null) : base(p, Slot.Weapon, attributes, id, name, enchantment, effect) { DamageMin = min; DamageMax = max; Speed = speed; TwoHanded = twoHanded; Type = type; Buff = buff; if (Buff != null && Buff.Attributes.GetValue(Attribute.WeaponDamage) > 0) { int bonus = (int)Math.Round(Buff.Attributes.GetValue(Attribute.WeaponDamage)); DamageMin += bonus; DamageMax += bonus; } } public Weapon(int min, int max, double speed, bool twoHanded, WeaponType type, Attributes attributes = null, int id = 0, string name = "New Item", Enchantment enchantment = null, Enchantment buff = null, ItemEffect effect = null) : this(null, min, max, speed, twoHanded, type, attributes, id, name, enchantment, buff, effect) { } public override string ToString() { string attributes = ""; foreach (Attribute a in Attributes.Values.Keys) { attributes += "[" + a + ":" + Attributes.Values[a] + "]"; } return string.Format("[{0}] ({1}) {2} : {3} | {4}-{5} at {6}, 2H = {7}, Type = {8}", Slot, Id, Name, attributes, DamageMin, DamageMax, Speed, TwoHanded, Type); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestingBlazor.Data.Models; using TestingBlazor.ViewModels; namespace TestingBlazor.Data.Acces.Repositories { public interface IRepository<T, U> where T : IDbObject where U : IUIObject { Task<IEnumerable<U>> Get(bool asNoTracking = false); Task<U> GetById(int id, bool asNoTracking = false); Task<T> Add(U item); Task<bool> Remove(U item); Task<T> RemoveById(int id); Task<bool> Update(int id, U newData); } }
namespace Airelax.Application.MemberInfos.Response { /// <summary> /// 房源ViewModel /// </summary> public class MemberInfoHouseDto { public string HouseId { get; set; } /// <summary> /// 房屋相片封面 /// </summary> public string Cover { get; set; } /// <summary> /// 屋型 /// </summary> public string HouseType { get; set; } /// <summary> /// 房型 /// </summary> public string RoomType { get; set; } /// <summary> /// 標題 /// </summary> public string RoomTitle { get; set; } /// <summary> /// 評價數量 /// </summary> public int CommentCount { get; set; } /// <summary> /// 星星分數 /// </summary> public double? StarScore { get; set; } } }
using IWorkFlow.DataBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("Para_OA_CarInfo", "id")] public class Para_OA_CarInfo : QueryInfo { #region Model private int _id; private string _cph; private decimal? _zdlc; private decimal? _sjlc; private decimal? _whlc; private int? _sfky; private string _zt; /// <summary> /// id /// </summary> /// [DataField("id", "Para_OA_CarInfo", false)] public int id { set { _id = value; } get { return _id; } } /// <summary> /// 车牌号 /// </summary> /// [DataField("cph", "Para_OA_CarInfo")] public string cph { set { _cph = value; } get { return _cph; } } /// <summary> /// 品牌 /// </summary> private string _carBrand; [DataField("carBrand", "Para_OA_CarInfo")] public string carBrand { set { _carBrand = value; } get { return _carBrand; } } /// <summary> /// 型号 /// </summary> private string _carModel; [DataField("carModel", "Para_OA_CarInfo")] public string carModel { set { _carModel = value; } get { return _carModel; } } /// <summary> /// 车辆类型 /// </summary> private string _carType; [DataField("carType", "Para_OA_CarInfo")] public string carType { set { _carType = value; } get { return _carType; } } /// <summary> /// 最大路程(公路) /// </summary> /// [DataField("zdlc", "Para_OA_CarInfo")] public decimal? zdlc { set { _zdlc = value; } get { return _zdlc; } } /// <summary> /// 实际路程(公里) /// </summary> /// [DataField("sjlc", "Para_OA_CarInfo")] public decimal? sjlc { set { _sjlc = value; } get { return _sjlc; } } /// <summary> /// 维护路程(公里) /// </summary> /// [DataField("whlc", "Para_OA_CarInfo")] public decimal? whlc { set { _whlc = value; } get { return _whlc; } } /// <summary> /// 车辆状态 /// </summary> /// [DataField("sfky", "Para_OA_CarInfo")] public int? sfky { set { _sfky = value; } get { return _sfky; } } public string foramtSfky { get { return _sfky == 0 ? "不可用" : "可用"; } } /// <summary> /// 状态描述 /// </summary> /// [DataField("zt", "Para_OA_CarInfo")] public string zt { set { _zt = value; } get { return _zt; } } /// <summary> /// 发动机 /// </summary> private string _carEngine; [DataField("carEngine", "Para_OA_CarInfo")] public string carEngine { set { _carEngine = value; } get { return _carEngine; } } /// <summary> /// 底盘 /// </summary> private string _chassis; [DataField("chassis", "Para_OA_CarInfo")] public string chassis { set { _chassis = value; } get { return _chassis; } } /// <summary> /// 颜色 /// </summary> private string _color; [DataField("color", "Para_OA_CarInfo")] public string color { set { _color = value; } get { return _color; } } /// <summary> /// 载重 /// </summary> private string _loadWeight; [DataField("loadWeight", "Para_OA_CarInfo")] public string loadWeight { set { _loadWeight = value; } get { return _loadWeight; } } /// <summary> /// 座位 /// </summary> private string _seatCount; [DataField("seatCount", "Para_OA_CarInfo")] public string seatCount { set { _seatCount = value; } get { return _seatCount; } } /// <summary> /// 价格 /// </summary> private string _price; [DataField("price", "Para_OA_CarInfo")] public string price { set { _price = value; } get { return _price; } } /// <summary> /// 生产日期 /// </summary> private string _proDate; [DataField("proDate", "Para_OA_CarInfo")] public string proDate { set { _proDate = value; } get { return _proDate; } } /// <summary> /// 购买日期 /// </summary> private string _buyDate; [DataField("buyDate", "Para_OA_CarInfo")] public string buyDate { set { _buyDate = value; } get { return _buyDate; } } /// <summary> /// 归属单位 /// </summary> private string _belongTo; [DataField("belongTo", "Para_OA_CarInfo")] public string belongTo { set { _belongTo = value; } get { return _belongTo; } } /// <summary> /// 备注 /// </summary> private string _remark; [DataField("remark", "Para_OA_CarInfo")] public string remark { set { _remark = value; } get { return _remark; } } /// <summary> /// 录入日期 /// </summary> private string _recordDate; [DataField("recordDate", "Para_OA_CarInfo")] public string recordDate { set { _recordDate = value; } get { return _recordDate; } } /// <summary> /// 录入人 /// </summary> private string _recordMan; [DataField("recordMan", "Para_OA_CarInfo")] public string recordMan { set { _recordMan = value; } get { return _recordMan; } } /// <summary> /// 司机 /// </summary> [DataField("Driver", "Para_OA_CarInfo")] public string Driver { get; set; } public string driverName { get; set; } /// <summary> /// checkBOx /// </summary> public bool isCheck { get; set; } public string sfkyText { get; set; } /// <summary> /// 连续新增 /// </summary> private bool _continueAdd; public bool continueAdd { set { _continueAdd = value; } get { return _continueAdd; } } #endregion Model } }
using Microsoft.Xna.Framework; using StarlightRiver.Dusts; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace StarlightRiver.Abilities { [DataContract] public class Smash : Ability { public Smash(Player player) : base(2, player) { } public override bool CanUse => player.velocity.Y != 0; public override void OnCast() { Timer = 0; } public override void InUse() { Timer++; if (Timer > 15) { player.maxFallSpeed = 999; player.velocity.X = 0; player.velocity.Y = 35; if (Timer % 15 == 0) { Main.PlaySound(SoundID.Item66, player.Center); } if (player.position.Y - player.oldPosition.Y == 0) { Active = false; OnExit(); } } else { player.velocity.X = 0; player.velocity.Y = Timer * 2 - 15; } } public override void UseEffects() { if (Timer > 15) { for (int k = 0; k <= 5; k++) { Dust.NewDust(player.Center - new Vector2(player.height / 2, -32), player.height, player.height, ModContent.DustType<Stone>(), 0, 0, 0, default, 1.1f); Dust.NewDust(player.Center - new Vector2(player.height / 2, -32), player.height, player.height, DustID.Dirt, Main.rand.Next(-14, 15) * 0.5f, 0, 0, default, 0.8f); if (k % 2 == 0) { Dust.NewDust(player.Center - new Vector2(player.height / 2, -32), player.height, player.height, ModContent.DustType<Grass>(), Main.rand.Next(-9, 10) * 0.5f, 0, 0, default, 1.1f); } } } else { float rot = Main.rand.NextFloat(6.28f); Dust.NewDustPerfect(player.Center + Vector2.One.RotatedBy(rot) * 40, ModContent.DustType<JungleEnergy>(), Vector2.One.RotatedBy(rot) * -2f, 0, default, 0.3f); } } public override void OnExit() { int power = (Timer > 60) ? 12 : (int)(Timer / 60f * 12); for (float k = 0; k <= 6.28; k += 0.1f - (power * 0.005f)) { Dust.NewDust(player.Center, 1, 1, ModContent.DustType<Stone>(), (float)Math.Cos(k) * power, (float)Math.Sin(k) * power, 0, default, 0.5f + power / 7f); Dust.NewDust(player.Center - new Vector2(player.height / 2, -32), player.height, player.height, ModContent.DustType<Grass>(), (float)Math.Cos(k) * power * 0.75f, (float)Math.Sin(k) * power * 0.75f, 0, default, 0.5f + power / 7f); } Main.PlaySound(SoundID.Item70, player.Center); Main.PlaySound(SoundID.NPCHit42, player.Center); Main.PlaySound(SoundID.Item14, player.Center); player.GetModPlayer<StarlightPlayer>().Shake = power; player.velocity.X = 0; player.velocity.Y = 0; } } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityEngine.UIElements; using UnityAtoms.Editor; using UnityEngine; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Event property drawer of type `Vector3Pair`. Inherits from `AtomEventEditor&lt;Vector3Pair, Vector3PairEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomEditor(typeof(Vector3PairEvent))] public sealed class Vector3PairEventEditor : AtomEventEditor<Vector3Pair, Vector3PairEvent> { } } #endif