Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
b591a3cebd9092122f833c9f2efaa7b955f2a0e5
C#
Adithyat/WebAgentPro
/WebAgentProTemplate/Api/CostCalculators/DriverReceipt.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAgentProTemplate.Api.Models; namespace WebAgentProTemplate.Api.CostCalculators { public class DriverReceipt { public decimal BaseCost; public decimal FinalCost; public Dictionary<String, decimal> driverAppliedDiscounts; public Driver driver; public decimal multiplier; public DriverReceipt(Driver driver) { this.driver = driver; driverAppliedDiscounts = new Dictionary<string, decimal>(); BaseCost = QuoteCostCalculator.DriverBaseCost; FinalCost = BaseCost; multiplier = 1.00m; } } }
ea5eb00bb1da2f8c46c93fd3f79f8a9916d65d65
C#
DomainGroupOSS/IdentityServer3
/source/Core/Services/ExternalClaimsFilter/MicrosoftClaimsFilter.cs
2.546875
3
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace IdentityServer3.Core.Services.Default { /// <summary> /// Claims filter for facebook. Converts the "urn:facebook:name" claim to the "name" claim. /// </summary> public class MicrosoftClaimsFilter : ClaimsFilterBase { /// <summary> /// Initializes a new instance of the <see cref="MicrosoftClaimsFilter"/> class. /// </summary> public MicrosoftClaimsFilter() : this("Microsoft") { } /// <summary> /// Initializes a new instance of the <see cref="MicrosoftClaimsFilter"/> class. /// </summary> /// <param name="provider">The provider this claims filter will operate against.</param> public MicrosoftClaimsFilter(string provider) : base(provider) { } /// <summary> /// Transforms the claims if this provider is used. /// </summary> /// <param name="claims">The claims.</param> /// <returns></returns> protected override IEnumerable<Claim> TransformClaims(IEnumerable<Claim> claims) { var nameClaim = claims.FirstOrDefault(x => x.Type == "urn:microsoftaccount:name"); var firstNameClaim = claims.FirstOrDefault(x => x.Type == "urn:microsoftaccount:first_name"); var lastNameClaim = claims.FirstOrDefault(x => x.Type == "urn:microsoftaccount:last_name"); var list = claims.ToList(); if (nameClaim != null) { list.Remove(nameClaim); list.RemoveAll(x => x.Type == Constants.ClaimTypes.Name); list.Add(new Claim(Constants.ClaimTypes.Name, nameClaim.Value)); } if (firstNameClaim != null) { list.Remove(firstNameClaim); list.RemoveAll(x => x.Type == Constants.ClaimTypes.GivenName); list.Add(new Claim(Constants.ClaimTypes.GivenName, firstNameClaim.Value)); } if (lastNameClaim != null) { list.Remove(lastNameClaim); list.RemoveAll(x => x.Type == Constants.ClaimTypes.FamilyName); list.Add(new Claim(Constants.ClaimTypes.FamilyName, lastNameClaim.Value)); } return list; } } }
5be0fabdfd7fc285b2584bdc48443a00a4e19f3e
C#
natalkata/C_Sharp
/4. Console_Input_and_Output/Problem7_SumOf5Numbers/Problem7_SumOf5Numbers/Problem7_SumOf5Numbers.cs
3.4375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; class Problem7_SumOf5Numbers { static void Main(string[] args) { string inputNums = Console.ReadLine(); inputNums = inputNums.Replace(',', '.'); decimal sum = 0.00m; string[] numbersAsStrings = inputNums.Split(' '); for (int i = 0; i < numbersAsStrings.Length; i++) { sum += decimal.Parse(numbersAsStrings[i]); } Console.WriteLine(sum); } }
ef161b18b3bc852273b520d9f5e4d7552b128039
C#
Azure/azure-sdk-for-net
/sdk/storage/Azure.Storage.Queues/src/Models/Internal/EncryptedMessageSerializer.cs
2.546875
3
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Text.Json; using Azure.Core; using Azure.Storage.Cryptography.Models; namespace Azure.Storage.Queues.Specialized.Models { internal static class EncryptedMessageSerializer { private const string EncryptedMessage_EncryptedMessageTextName = "EncryptedMessageContents"; #region Serialize public static BinaryData Serialize(EncryptedMessage data) { return BinaryData.FromBytes(SerializeEncryptedMessage(data)); } public static ReadOnlyMemory<byte> SerializeEncryptedMessage(EncryptedMessage message) { var writer = new Core.ArrayBufferWriter<byte>(); using var json = new Utf8JsonWriter(writer); json.WriteStartObject(); WriteEncryptedMessage(json, message); json.WriteEndObject(); json.Flush(); return writer.WrittenMemory; } public static void WriteEncryptedMessage(Utf8JsonWriter json, EncryptedMessage message) { json.WriteString(EncryptedMessage_EncryptedMessageTextName, message.EncryptedMessageText); json.WriteStartObject(nameof(message.EncryptionData)); EncryptionDataSerializer.WriteEncryptionData(json, message.EncryptionData); json.WriteEndObject(); } #endregion #region Deserialize public static bool TryDeserialize(BinaryData serializedData, out EncryptedMessage encryptedMessage) { try { encryptedMessage = Deserialize(serializedData); return true; } // JsonException does not actually cover everything. InvalidOperationException can be thrown // on some string inputs, as we can't assume input is even JSON. catch (Exception) { encryptedMessage = default; return false; } } public static EncryptedMessage Deserialize(BinaryData serializedData) { var reader = new Utf8JsonReader(serializedData.ToMemory().Span); return DeserializeEncryptedMessage(ref reader); } public static EncryptedMessage DeserializeEncryptedMessage(ref Utf8JsonReader reader) { using JsonDocument json = JsonDocument.ParseValue(ref reader); JsonElement root = json.RootElement; return ReadEncryptionData(root); } private static EncryptedMessage ReadEncryptionData(JsonElement root) { var data = new EncryptedMessage(); foreach (var property in root.EnumerateObject()) { ReadPropertyValue(data, property); } if (data.EncryptionData == default || data.EncryptedMessageText == default) { throw new FormatException($"Failed to find non-optional properties while deserializing `{typeof(EncryptedMessage).FullName}`."); } return data; } private static void ReadPropertyValue(EncryptedMessage data, JsonProperty property) { if (property.NameEquals(EncryptedMessage_EncryptedMessageTextName)) { data.EncryptedMessageText = property.Value.GetString(); } else if (property.NameEquals(nameof(data.EncryptionData))) { data.EncryptionData = EncryptionDataSerializer.ReadEncryptionData(property.Value); } else { throw new FormatException($"Failed to deserialize `{typeof(EncryptedMessage).FullName}`. Unrecognized property `{property.Name}`."); } } #endregion } }
45859fb2c0bacd5bde07bbcd38889aea08648f5f
C#
spencer-langley/alfariq
/alfariq/ViewModels/ParticipantWelcomeViewModel.cs
2.53125
3
using alfariq.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace alfariq.ViewModels { public class ParticipantWelcomeViewModel { public ParticipantWelcomeViewModel(Participant p) { OpenSessions = new Dictionary<string, int>(); this.Age = p.Age; this.Home = p.Home; this.Id = p.Id; this.ImagePath = p.ImagePath; this.Name = p.Name; this.Username = p.Username; foreach(var session in p.Sessions) { if (!session.Completed) { OpenSessions.Add(session.Name, session.Id); } } } public int Age { get; set; } public string Home { get; set; } public int Id { get; set; } public string ImagePath { get; set; } public string Name { get; set; } public Dictionary<string, int> OpenSessions { get; set; } public string Username { get; set; } } }
f52114b50dc61079f16fc1c30b8c336153210ed8
C#
nicolascof/Music-Manager
/Music-Manager/frm_About.cs
2.84375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Reflection; using System.Runtime.InteropServices; namespace Music_Manager { partial class frm_About : Form { const int MF_BYPOSITION = 0x400; [DllImport("User32")] private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags); [DllImport("User32")] private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("User32")] private static extern int GetMenuItemCount(IntPtr hWnd); public frm_About() { InitializeComponent(); IntPtr hMenu = GetSystemMenu(this.Handle, false); int menuItemCount = GetMenuItemCount(hMenu); RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION); // Inicializar AboutBox para mostrar la información del producto desde la información del ensamblado. // Cambiar la configuración de la información del ensamblado correspondiente a su aplicación desde: // - Proyecto->Propiedades->Aplicación->Información del ensamblado // - AssemblyInfo.cs this.Text = String.Format("Acerca de {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Versión {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; this.textBoxDescription.Text = AssemblyDescription; textBoxDescription.Multiline = true; } #region Descriptores de acceso de atributos de ensamblado public string AssemblyTitle { get { // Obtener todos los atributos Title en este ensamblado object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); // Si hay al menos un atributo Title if (attributes.Length > 0) { // Seleccione el primero AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; // Si no es una cadena vacía, devuélvalo if (titleAttribute.Title != "") return titleAttribute.Title; } // Si no había ningún atributo Title, o si el atributo Title era una cadena vacía, devuelva el nombre del archivo .exe return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { // Obtener todos los atributos de descripción de este ensamblado object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); // Si no hay ningún atributo de descripción, devuelva una cadena vacía if (attributes.Length == 0) return ""; // Si hay un atributo de descripción, devuelva su valor return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { // Obtenga todos los atributos del producto de este ensamblado object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); // Si no hay atributos del producto, devuelva una cadena vacía if (attributes.Length == 0) return ""; // Si hay un atributo de producto, devuelva su valor return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { // Obtenga todos los atributos de copyright de este ensamblado object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); // Si no hay atributos de copyright, devuelva una cadena vacía if (attributes.Length == 0) return ""; // Si hay un atributo de copyright, devuelva su valor return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { // Obtenga todos los atributos de compañía en este ensamblado object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); // Si no hay ningún atributo de compañía, devuelva una cadena vacía if (attributes.Length == 0) return ""; // Si hay un atributo de compañía, devuelva su valor return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion private void okButton_Click(object sender, EventArgs e) { this.Close(); } private void textBoxDescription_TextChanged(object sender, EventArgs e) { //textBoxDescription.Lines = textBoxDescription.Text = "Integrantes del grupo:" + Environment.NewLine + " • Back, Leonardo" + Environment.NewLine + " • Fassi, Claudio" + Environment.NewLine + " • Mastroviti, Nicolas"; } } }
d4ea5e18f4888b32ff37e7f08d4dd2d9bb35945f
C#
GHDevelop/FirstPersonGameThing
/First Person Game/Assets/Camera/Camera Controllers/BaseCameraMover.cs
2.75
3
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// The base camera mover that all camera movers derive from. This one simply rotates the camera with input given. /// </summary> public class BaseCameraMover : MonoBehaviour { [Header("Cameras and Transforms")] [Tooltip("The transform of the object this component is attached to, should typically be the character in question"), SerializeField, VisibleOnly] private Transform _cameraMoverTransform; /// <summary> /// The <see cref="Transform"/> of the object the <see cref="UnityEngine.Camera"/> is attached to (for example, the player character). /// </summary> protected Transform CameraMoverTransform { get { return _cameraMoverTransform; } private set { _cameraMoverTransform = value; } } [Tooltip("The camera that the character will look through. Will be set automatically if not pre-configured"), SerializeField] private Camera _camera; /// <summary> /// The camera itself. Generally only used to get the <see cref="CameraTransform"/> if not already set /// </summary> /// <seealso cref="CameraTransform"/> protected Camera Camera { get { return _camera; } private set { _camera = value; } } [Tooltip("The transform to move when altering the camera. Will typically just be the camera, but can be set manually if a more complicated configuration is desired."), SerializeField] private Transform _cameraTransform; /// <summary> /// The <see cref="Transform"/> used to move the camera. /// This is by default set to the transform of <see cref="Camera"/>, but can also be set manually to a pivot. /// </summary> /// <seealso cref="Camera"/> protected Transform CameraTransform { get { return _cameraTransform; } private set { _cameraTransform = value; } } [Header("Camera Mover Properties")] [Tooltip("The camera's vertical bounds"), SerializeField] private float _maxYRotation = 60; /// <summary> /// The maximum deviation the camera can achieve in rotation along the Y Axis. /// </summary> public float MaxYRotation { get { return _maxYRotation; } private set { _maxYRotation = value; } } [Tooltip("The speed the camera moves per second"), SerializeField] private float _cameraSpeed = 300; /// <summary> /// The speed multiplier used for the camera's rotation /// </summary> public float CameraSpeed { get { return _cameraSpeed; } private set { _cameraSpeed = value; } } [Tooltip("The camera's initial rotation"), SerializeField, VisibleOnly] private Vector3 _initialCameraRotation; /// <summary> /// The initial local rotation of the camera. Used in calculations with <see cref="MaxYRotation"/> to limit vertical look /// </summary> public Vector3 InitialCameraRotation { get { return _initialCameraRotation; } private set { _initialCameraRotation = value; } } [Tooltip("The current amount the camera is rotated"), SerializeField, VisibleOnly] private Vector3 _currentCameraRotation = Vector3.zero; /// <summary> /// The camera's current intended local rotation /// </summary> public Vector3 CurrentCameraRotation { get { return _currentCameraRotation; } private set { value.x = Mathf.Clamp(value.x, -MaxYRotation, MaxYRotation); _currentCameraRotation = value; } } private void Awake() { CameraMoverTransform = transform; if (Camera == null) { Camera = GetComponentInChildren(typeof(Camera)) as Camera; } if (CameraTransform == null) { CameraTransform = Camera.transform; } InitialCameraRotation = CameraTransform.localEulerAngles; CurrentCameraRotation = InitialCameraRotation; } /// <summary> /// Updates the current camera rotation speed, then applies the rotation /// </summary> /// <param name="rotationDirection"></param> public virtual void RotateCamera(Vector3 rotationDirection) { CurrentCameraRotation += rotationDirection * CameraSpeed * Time.fixedDeltaTime; ApplyRotation(); } /// <summary> /// Applies rotation to the camera /// </summary> protected virtual void ApplyRotation() { CameraTransform.localRotation = Quaternion.Euler(CurrentCameraRotation); } }
e86584f3ef7867550dacc7505efb07b4c8ba6c2a
C#
DAABMoney/RsND-Inventory-Management
/RsND Inventory Management/Repo/OrderRepo.cs
2.890625
3
using RsND_Inventory_Management.Contracts; using RsND_Inventory_Management.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RsND_Inventory_Management.Repo { public class OrderRepo : IOrderRepo { private readonly ApplicationDbContext _db; public OrderRepo(ApplicationDbContext db) { _db = db; } public bool Create(Order entity) { _db.Orders.Add(entity); return Save(); } public bool Delete(Order entity) { _db.Orders.Remove(entity); return Save(); } public ICollection<Order> FindAll() { var orders = _db.Orders.ToList(); return orders; } public Order FindById(int id) { var orders = _db.Orders.Find(id); return orders; } public bool isExists(int id) { var exists = _db.Orders.Any(l => l.Id == id); return exists; } public bool Save() { var changes = _db.SaveChanges(); return changes > 0; } public bool Update(Order entity) { _db.Orders.Update(entity); return Save(); } } }
0729da4ffa0141f49b91ececedcd19152acf1fb9
C#
bravesoftdz/stroke-recognition
/segmenter/Segmenter/Segment.cs
3
3
/** * Author: Levi Lindsey (llind001@cs.ucr.edu) */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Shapes; namespace StrokeCollector { public abstract class Segment : Drawable { protected int strokeStartPointIndex; protected int strokeEndPointIndex; protected double errorOfFit; /// <summary> /// Create this Segment's shape to draw on the canvas. /// </summary> protected abstract void CreateShape(); /// <summary> /// Return the Shape for drawing on the Canvas. /// </summary> public abstract Shape GetShape(); public abstract String GetDataFileEntry(SaveValue saveValue, SegmentationAlgorithm segmentationAlgorithm); public int StrokeStartPointIndex { get { return strokeStartPointIndex; } } public int StrokeEndPointIndex { get { return strokeEndPointIndex; } } public double ErrorOfFit { get { return errorOfFit; } } } }
92e5e54aa6964b747f76f52ea54662490897ff4f
C#
HIOTechnologies/dashboard_win
/dashboard/Backend/EncodingBase64.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HIO.Backend { public class EncodingForBase64 { public string Base64Encode(string plainText) { if (plainText == "" || plainText == null || plainText.Length == 0) return ""; var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); return System.Convert.ToBase64String(plainTextBytes); } public string Base64Decode(string base64EncodedData) { if (base64EncodedData == "" || base64EncodedData == null || base64EncodedData.Length == 0) return ""; var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); return System.Text.UnicodeEncoding.UTF8.GetString(base64EncodedBytes); } } }
f85804db5baaf524b3fa6011528a328d5cb33cd3
C#
lum1nary/MVVM.ViewModelFirst
/Src/Mvvm.ViewModelFirst/ViewResolver.cs
2.75
3
using System; using System.Collections.Generic; namespace MVVM.ViewModelFirst { public sealed class ViewResolver : IViewResolver { private readonly Dictionary<Type, ISingletonFactoryContainer> _singletonMethodContainer; private readonly Dictionary<Type, Type> _singletonAssociations = new Dictionary<Type, Type>(); private readonly Dictionary<Type, Type> _associations = new Dictionary<Type, Type>(); private readonly object _syncRoot = new object(); private readonly Type _managerProtorype; public ViewResolver(Type resolvePrototype) { if (!typeof(IViewManager).IsAssignableFrom(resolvePrototype)) throw new InvalidOperationException("resolvePrototype is notimplements IViewManager"); _managerProtorype = resolvePrototype; } public void Register<TViewModel, TView>() { lock (_syncRoot) { if (_associations.ContainsKey(typeof(TViewModel))) throw new InvalidOperationException("Already Registered"); _associations.Add(typeof(TViewModel), typeof(TView)); } } public IViewManager Resolve<TViewModel>(object dataContext) { lock (_syncRoot) { if (!_associations.ContainsKey(typeof(TViewModel))) throw new InvalidOperationException("Type is Not Registered"); var view = Activator.CreateInstance(_associations[typeof(TViewModel)]); var instance = Activator.CreateInstance(_managerProtorype, view, dataContext); return (IViewManager)instance; } } public void RegisterSingleton<TViewModel, TView>(ISingletonFactoryContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); if (_singletonAssociations.ContainsKey(typeof(TViewModel))) throw new InvalidOperationException(typeof(TViewModel).Name + "is already registered"); _singletonAssociations.Add(typeof(TViewModel), typeof(TView)); _singletonMethodContainer.Add(typeof(TViewModel), container); } public IViewManager ResolveSingleton<TViewModel>(object dataContext) { if (!_singletonAssociations.ContainsKey(typeof(TViewModel))) throw new InvalidOperationException("Type is Not Registered"); var view = Activator.CreateInstance(_singletonAssociations[typeof(TViewModel)]); var instance = Activator.CreateInstance(_managerProtorype, view, dataContext); return (IViewManager)instance; } public void Unregister<TViewModel>() { lock (_syncRoot) { _associations.Remove(typeof(TViewModel)); } } public void UnregisterSingleton<TViewModel>() { _singletonAssociations.Remove(typeof(TViewModel)); _singletonMethodContainer.Remove(typeof(TViewModel)); } public TViewModel GetSingletonViewModel<TViewModel>() { if (!_singletonMethodContainer.ContainsKey(typeof(TViewModel))) throw new InvalidOperationException("Requested singleton is not registered"); return (TViewModel)_singletonMethodContainer[typeof(TViewModel)].GetSingletonInstance(); } } }
82f81741d59d9253843644fda88484a9e272d03c
C#
UnicornOfDoom12/NEA
/Assets/Scripts/MapMarkerHandler.cs
2.671875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapMarkerHandler : MonoBehaviour { public void UpdatePosition(){ GameObject Tracker = GameObject.Find("Cordinate Tracker"); // Finds the gameobject resposible for tracking cordx and cordy CordinateHandler CordinateHandler = Tracker.GetComponent<CordinateHandler>(); // adds the script with the values of cordx inside int Cordx = CordinateHandler.Cordx; // assigns the values of cordx to a local variable int Cordy = CordinateHandler.Cordy; // assigns the values of cordx to a local variable float posx = -50 + -6.5f + (4 * Cordx); // adjust the position of the marker in the x direction float posy = 3.0f - (2 * Cordy); // adjust the position of the marker in the y direction Vector3 NewPosition = new Vector3(posx,posy,0); // Converts the position into a vector transform.position = NewPosition; // assigns the vector } }
20d4d267c8a09a7c731eb414b85bd9e4409f37f7
C#
juanquinones/SpaceMan
/Assets/Scripts/Collectable.cs
2.9375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum CollectableType //creamos un enumerado para configurar todos los colleccionables { healthPotion, manaPotion, money } public class Collectable : MonoBehaviour { public CollectableType type = CollectableType.money; //variable de collectable de tipo money para configurar la moneda private SpriteRenderer sprite; //accedemos a su sprite private CircleCollider2D itemCollider; //accedemos a su collider bool hasBeenCollected = false; //variable que nos indica si ya fue o no colleccionada public int value = 1; //valor del collecionable GameObject player; //variable que llama al objeto player private void Awake() { sprite = GetComponent<SpriteRenderer>(); //llamamos el componente sprite del objeto al igual que su collider itemCollider = GetComponent<CircleCollider2D>(); } private void Start() { player = GameObject.Find("Player"); //inicializamos el objeto player buscandolo por su tag name } void Show() //metodo para mostrar la moneda { sprite.enabled = true; itemCollider.enabled = true; hasBeenCollected = false; } void Hide() //metodo para esconder la moneda { sprite.enabled = false; itemCollider.enabled = false; } void Collect() //metodo para collecionar la moneda { Hide(); hasBeenCollected = true; switch (this.type) //utilizamos un switch para dependiendo del collecionable programar su acción { case CollectableType.money: GameManager.sharedInstance.CollectObject(this); //se llama al metodode CollectObject en el game manager para incrementar el contador en el valor de moneda GetComponent<AudioSource>().Play(); //activamos el sonido de recolectar moneda break; case CollectableType.healthPotion: player.GetComponent<PlayerController>().CollectHealth(this.value); //buscamos el componente PlayerController del objeto player y especificamente el metodo health break; case CollectableType.manaPotion: player.GetComponent<PlayerController>().CollectMana(this.value); break; } } private void OnTriggerEnter2D(Collider2D collision) { if(collision.tag == "Player") { Collect(); //si el jugador colisiona contra un colleccionable entonces se llama al metodo collect } } }
478ee52ed771fe582069330e7763529021ff47fb
C#
rafaelvasco/OMEGA
/OMEGA/Primitives/Point.cs
3.25
3
using System; using System.Runtime.InteropServices; namespace OMEGA { [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct Point : IEquatable<Point> { public static readonly Point Zero = new Point(0, 0); public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } public Point(int val) : this(val, val) { } public override bool Equals(object obj) { return obj is Point point2 && Equals(point2); } public bool Equals(Point other) { return X == other.X && Y == other.Y; } public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + X; hash = hash * 23 + Y; return hash; } } public override string ToString() { return $"{X},{Y}"; } public static int Cross(Point a, Point b) { return a.X * b.Y - a.Y * b.X; } public static implicit operator Vec2(Point p) { return new Vec2(p.X, p.Y); } public static explicit operator Point(Vec2 p) { return new Point((int) p.X, (int) p.Y); } public static bool operator ==(Point a, Point b) { return a.X == b.X && a.Y == b.Y; } public static bool operator !=(Point a, Point b) { return a.X != b.X || a.Y != b.Y; } public static Point operator +(Point a, Point b) { a.X += b.X; a.Y += b.Y; return a; } public static Point operator -(Point a, Point b) { a.X -= b.X; a.Y -= b.Y; return a; } public static Point operator *(Point a, Point b) { a.X *= b.X; a.Y *= b.Y; return a; } public static Point operator *(Point p, int n) { p.X *= n; p.Y *= n; return p; } public static Point operator *(int n, Point p) { p.X *= n; p.Y *= n; return p; } public static Point operator /(Point a, Point b) { a.X /= b.X; a.Y /= b.Y; return a; } public static Point operator /(Point p, int n) { p.X /= n; p.Y /= n; return p; } public static Point operator /(int n, Point p) { p.X /= n; p.Y /= n; return p; } } }
11d9ec200e1ab895801fa06bbf65e42e0e9ae7bb
C#
diego-escalante/LD46-FriendlyFire
/Assets/Scripts/Player/TopDownMovement.cs
2.765625
3
using UnityEngine; // For future reuse: // TopDownMovement shouldn't take input directly, there should be a input manager controlling everything. (Ok, inputs are a little better now but there's still room to improve.) // It would be nice for TopDownMovement to have acceleration, but its not necessary for this game. public class TopDownMovement : MonoBehaviour { public float moveSpeed = 5f; // public bool accelerationEnabled = true; // public float acceleration = 50f; private PlayerInputs playerInputs; private Vector2 velocity = Vector2.zero; private CollisionChecker collisionChecker; public void Start() { playerInputs = GetComponent<PlayerInputs>(); // Make sure this object has a collision checker. collisionChecker = GetComponent<CollisionChecker>(); if (collisionChecker == null) { Debug.LogError(string.Format("There is no CollisionChecker on game object {0} for TopDownMovement to work.", gameObject.name)); this.enabled = false; } } public void Update() { // Calculate the new velocity based on inputs. move(); // Update velocity based on collisions. Vector2 translationVector = velocity * Time.deltaTime; Vector2 checkedTranslationVector = collisionChecker.checkForCollisions(translationVector); // If the checked translation is different, we hit something, and velocity in that direction should stop. if (translationVector.y != checkedTranslationVector.y) { velocity.y = 0; } if (translationVector.x != checkedTranslationVector.x) { velocity.x = 0; } // Actually move the object. transform.Translate(checkedTranslationVector, Space.World); } public Vector2 getVelocity() { return velocity; } private void move() { Vector2 targetVelocity = new Vector2(playerInputs.horizontal, playerInputs.vertical).normalized * moveSpeed; velocity = targetVelocity; // There's really no need to spend time with acceleration here for this project. // if (!accelerationEnabled) { // velocity = targetVelocity; // } else { // if (targetVelocity == Vector2.zero) { // targetVelocity = -velocity; // } // velocity = Vector2.ClampMagnitude((targetVelocity * acceleration * Time.deltaTime) + velocity, moveSpeed); // } } }
b0f6824d7bc1abbb803bd64f96d0a031b8eb49ae
C#
boryanagm/Telerik-Projects
/04. WEB/04. Basic Authentication/InClassActivity/Beers.Services/BeerService.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using Beers.Data; using Beers.Data.Models; using Beers.Services.Contracts; using Beers.Services.Models; using Microsoft.EntityFrameworkCore; namespace Beers.Services { public class BeerService : IBeerService { private readonly BeerDbContext dbContext; public BeerService(BeerDbContext dbContext) { this.dbContext = dbContext; } public BeerDTO Get(int id) { // Data model Beer beer = this.dbContext .Beers .Include(b => b.Brewery) .Include(b => b.Ratings) .ThenInclude(r => r.User) .FirstOrDefault(b => b.BeerId == id); // Service model BeerDTO beerDTO = new BeerDTO(); beerDTO.Name = beer.Name; beerDTO.Brewery = beer.Brewery.Name; foreach (var rating in beer.Ratings) { var pair = new Tuple<string, double>(rating.User.Name, rating.Value); beerDTO.UserRatings.Add(pair); } return beerDTO; } public List<Beer> GetAll() { var beers = this.dbContext.Beers.Include(b => b.Brewery).ToList(); return beers; } public Beer Create(int id, Beer beer) { var user = this.dbContext.Users .FirstOrDefault(u => u.UserId == id) ?? throw new ArgumentNullException(); this.dbContext.Beers.Add(beer); beer.UserId = user.UserId; this.dbContext.SaveChanges(); return beer; } public Beer Update(int id, string name) { var beer = this.dbContext.Beers .FirstOrDefault(beer => beer.BeerId == id) ?? throw new ArgumentNullException(); beer.Name = name; this.dbContext.SaveChanges(); return beer; } public void Delete(int id) { var beer = this.dbContext.Beers .FirstOrDefault(beer => beer.BeerId == id) ?? throw new ArgumentNullException(); this.dbContext.Beers.Remove(beer); this.dbContext.SaveChanges(); } public Beer Rate(int beerId, int userId, int rate) { var beer = this.dbContext.Beers .FirstOrDefault(beer => beer.BeerId == beerId) ?? throw new ArgumentNullException(); var user = this.dbContext.Users .FirstOrDefault(u => u.UserId == userId) ?? throw new ArgumentNullException(); beer.Ratings.Add(new Rating { BeerId = beerId, UserId = userId, Value = rate }); this.dbContext.SaveChanges(); return beer; } } }
bf163a33ac7d23d945830fcb94e66675949c790a
C#
ligu/KafkaClient
/src/KafkaClient/Protocol/HeartbeatResponse.cs
2.625
3
using System; using System.Collections.Immutable; namespace KafkaClient.Protocol { /// <summary> /// HeartbeatResponse => ErrorCode /// ErrorCode => int16 /// /// see http://kafka.apache.org/protocol.html#protocol_messages /// </summary> public class HeartbeatResponse : IResponse, IEquatable<HeartbeatResponse> { public HeartbeatResponse(ErrorResponseCode errorCode) { ErrorCode = errorCode; Errors = ImmutableList<ErrorResponseCode>.Empty.Add(ErrorCode); } /// <inheritdoc /> public IImmutableList<ErrorResponseCode> Errors { get; } public ErrorResponseCode ErrorCode { get; } /// <inheritdoc /> public override bool Equals(object obj) { return Equals(obj as HeartbeatResponse); } /// <inheritdoc /> public bool Equals(HeartbeatResponse other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ErrorCode == other.ErrorCode; } /// <inheritdoc /> public override int GetHashCode() { return (int) ErrorCode; } /// <inheritdoc /> public static bool operator ==(HeartbeatResponse left, HeartbeatResponse right) { return Equals(left, right); } /// <inheritdoc /> public static bool operator !=(HeartbeatResponse left, HeartbeatResponse right) { return !Equals(left, right); } } }
7644f46bebfde8557639cefdd3d45804e2232997
C#
andyhodges10/RogueSharpExample
/RogueSharpExample/Actors/Monsters/Hard Monsters/Werewolf.cs
2.8125
3
using RogueSharp.DiceNotation; using RogueSharpExample.Core; namespace RogueSharpExample.Monsters { public class Werewolf : Monster { public static Werewolf Create(int level) { int health = Dice.Roll("4D4") + level / 2; return new Werewolf { AttackMessages = new string[] { "The Werewolf swings its paw at you", "The Wolf goes in for a bite" }, GreetMessages = new string[] { "The Werewolf goes into an alerted stance as it notices you" }, DeathMessages = new string[] { "The Werewolf yelps and crumbles to the ground" }, Attack = Dice.Roll("4D2") + level / 2, AttackChance = Dice.Roll("25D4"), Awareness = 14, Color = Colors.WolfColor, Defense = Dice.Roll("2D2") + level / 3, DefenseChance = Dice.Roll("17D2"), Gold = Dice.Roll("8D3") + level / 2, Health = health, MaxHealth = health, Name = "Werewolf", Speed = 8, Experience = Dice.Roll("3D3") + level / 2, Symbol = 'W' }; } } }
f1b448cdd42f0dd0be12bbec745a90e2fdae27bd
C#
albertodemarco/CupidoBot
/CupidoBotV1/CupidoBotV1/Services/CustomVisionService.cs
2.59375
3
using System; using System.Collections; using System.Linq; using System.Web; using System.Configuration; using System.Threading.Tasks; using CupidoBotV1.Data; using Microsoft.Cognitive.CustomVision; namespace CupidoBotV1.Services { public class CustomVisionService { public static async Task<ArrayList> customVisionPredictions(string imageUrl) { ArrayList lst = new ArrayList(); CupidoProfile cp = new CupidoProfile(); string retVal = String.Empty; string predictionKey = ConfigurationManager.AppSettings["CustomVisionKey"]; string iterationId = ConfigurationManager.AppSettings["CustomVisionIterationId"]; string projectId = ConfigurationManager.AppSettings["ProjectIdKey"]; string customVisionUrl = ConfigurationManager.AppSettings["CustomVisionUrl"]; Guid projeczIdGuid = new Guid(projectId); Guid iterationGuid = new Guid(iterationId); Microsoft.Cognitive.CustomVision.Models.ImageUrl url = new Microsoft.Cognitive.CustomVision.Models.ImageUrl(imageUrl); PredictionEndpointCredentials predictionEndpointCredentials = new PredictionEndpointCredentials(predictionKey); PredictionEndpoint endpoint = new PredictionEndpoint(predictionEndpointCredentials); endpoint.BaseUri = new Uri(customVisionUrl); Microsoft.Cognitive.CustomVision.Models.ImagePredictionResultModel result = await endpoint.PredictImageUrlAsync(projeczIdGuid, url, iterationGuid); int counter = 0; foreach (var c in result.Predictions) { retVal = retVal + $"{c.Tag}: {c.Probability:P1}"; if (c.Tag.Contains("Model1")) { cp.SuperModelPoints = System.Convert.ToInt32(Math.Round(c.Probability * 100, 0)); } else { cp.NormalPoints = System.Convert.ToInt32(Math.Round(c.Probability * 100, 0)); } counter++; } retVal = retVal.Replace("Model2", " Normal "); retVal = retVal.Replace("Model1", " Super Model "); lst.Add(retVal); lst.Add(cp); return lst; } } }
c7b076c2f4e9402f70e2a25bd6c5da507a22da42
C#
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc104/B/4784135.cs
3.578125
4
using System; namespace AtCoder { class Program { static void Main(string[] args) { MainStream(); } static void MainStream() { char[] s = Console.ReadLine().ToCharArray(); if(Judge(s)) { Console.WriteLine("AC"); } else { Console.WriteLine("WA"); } } static bool Judge(char[] s) { int C_count = 0; int C_index = 0; if (s[0] != 'A') { return false; } for (int i = 2; i < s.Length - 1; i++) { if (s[i] == 'C') { C_count += 1; C_index = i; if(C_count > 1)//C????? { return false; } } } if(C_count != 1) { return false; } for (int i = 1;i<s.Length;i++) { if (i != C_index) { if (Char.IsUpper(s[i])) { return false; } } } return true; } } }
76530579f6e65605b666b204da17015034ee9d1e
C#
ciscoalmighty/SafeAutoKata
/TripWork.cs
3.03125
3
using FileUpload.Models; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FileUpload { public class TripWork { public static List<string> Split(string lineToSplit) { //split a line using " " as a delimiter List<string> finishedLine = lineToSplit.Split(" ").ToList(); return finishedLine; } public static TimeSpan GetDuration(string splitLine) { //endtime - starttime = totaltime List<string> result = new List<string>(); result = Split(splitLine); DateTime startTime = Convert.ToDateTime(result[2]); DateTime endTime = Convert.ToDateTime(result[3]); TimeSpan totalTime = endTime - startTime; return totalTime; } public static double GetMiles(string splitLine) { List<string> result = new List<string>(); result = Split(splitLine); double miles = Convert.ToDouble(result[4]); return miles; } public static double GetMPH(string splitLine) { //distance/time= mph TimeSpan duration = GetDuration(splitLine); double miles = GetMiles(splitLine); double milesPerHour = miles / duration.TotalHours; return milesPerHour; } public static string GetName(string line) { return GetName(Split(line)); } public static string GetName(List<string> splitLine) { string name = splitLine[1]; return name; } public static string GetStartTime(string line) { return GetStartTime(Split(line)); } public static string GetStartTime(List<string> splitLine) { string startTime = splitLine[2]; return startTime; } public static string GetEndTime(string line) { return GetEndTime(Split(line)); } public static string GetEndTime(List<string> splitLine) { string endTime = splitLine[3]; return endTime; } public static double Time (TimeSpan time) { return time.TotalMinutes / 60; } public static Driver MakeDriver (string line) { Driver driver = new Driver(); driver.Name = GetName(line); driver.StartTime = "0:00"; driver.EndTime = "0:00"; driver.Mph = 0; driver.Miles = 0; return driver; } public static Driver UpdateDriver(Driver driver, string line) { int mphTest = Convert.ToInt32(GetMPH(line)); if (mphTest > 5 && mphTest < 100) { driver.trip++; driver.TotalTime = driver.TotalTime + GetDuration(line); driver.Miles = Math.Round(driver.Miles + GetMiles(line)); driver.Mph = Math.Round(driver.Miles / driver.TotalTime.TotalHours); return driver; } else return driver; } public static List <Driver> SortList (List<Driver> drivers) { List<Driver> sortedList = Program.DriverLog.OrderByDescending(o => o.Miles).ToList(); return sortedList; } } }
ec25f45aedc1acd57bee364a8b35ee35baac75e2
C#
quattro004/Recipieces
/RecipeUIClassLib/Extensions/StringExtensions.cs
3.78125
4
using System; using System.Collections.Generic; using System.Text; namespace RecipeUIClassLib.Extensions { public static class StringExtensions { /// <summary> /// Converts the <paramref name="input" /> string list into a string delimiting each entry using the /// <paramref name="delimiter" />. The default delimiter is \r\n /// </summary> /// <param name="input"></param> /// <param name="delimiter"></param> /// <returns></returns> public static string ToDelimited(this List<string> input, string delimiter = "\r\n") { if (null == input) { return string.Empty; } var stringBuilder = new StringBuilder(); foreach (var stringValue in input) { stringBuilder.AppendFormat("{0}{1}", stringValue, delimiter); } return stringBuilder.ToString(); } public static List<string> FromDelimited(this string input, string delimiter = "\r\n") { if (!string.IsNullOrWhiteSpace(input)) { return new List<string>(input.Split(new string[] {delimiter}, StringSplitOptions.RemoveEmptyEntries)); } return new List<string>(); } public static bool IsNullOrWhiteSpace(this string input) { return string.IsNullOrWhiteSpace(input); } } }
02300be8efb849f2e6fe2a61942c8cc5cf0801d1
C#
willardf/InfiniteCyborg
/InfiniteCyborg/Genetics/BitField.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InfCy.Genetics { public class BitField { private const int DataSize = sizeof(long) * 8; private long[] data; public BitField(int len) { Length = len; data = new long[len / sizeof(long) + 1]; } public BitField CopyBits(BitField src, int start, int len) { for (int i = start; i < len; ++i) this[i] = src[i]; return this; } public BitField Randomize(Func<bool> randy) { for (int i = 0; i < this.Length; ++i) { this[i] = randy(); } return this; } private long Get(int bit, int nBits = 1) { int idx = bit / DataSize; int end = (bit + nBits) / DataSize; int b = bit % DataSize; int select = Math.Min(DataSize - b, nBits); long mask = (1L << select) - 1L; long output = ((this.data[idx] >> b) & mask); if (idx != end) { mask = (1L << nBits - select) - 1L; output |= ((this.data[end]) & mask) << select; } return output; } private void Set(int bit, int nBits = 1, long value = 0) { int idx = bit / DataSize; int end = (bit + nBits) / DataSize; var b = bit % DataSize; int select = Math.Min(DataSize - b, nBits); long mask = (1L << select) - 1L; this.data[idx] &= ~(mask << b); this.data[idx] |= (value & mask) << b; if (idx != end) { this.Set(bit + select, nBits - select, value >> select); } } public long this[int bit, int len] { get { return Get(bit, len); } set { Set(bit, len, value); } } public bool this[int bit] { get { return Get(bit, 1) != 0; } set { Set(bit, 1, (value ? 1 : 0)); } } public bool this[Bit bit] { get { return this[bit.Start]; } set { this[bit.Start] = value; } } public long this[BitSet b] { get { return this[b.Start, b.Length] + b.MinValue; } set { this[b.Start, b.Length] = value - b.MinValue; } } public TribitState this[Tribit b] { get { return (TribitState)this[b.Start, b.Length]; } set { this[b.Start, b.Length] = (long)value; } } public static BitField operator &(BitField a, BitField b) { BitField output = new BitField(Math.Max(a.Length, b.Length)); for (int i = 0; i < b.data.Length && i < a.data.Length; ++i) { long input = long.MaxValue; input &= (i < a.data.Length) ? a.data[i] : 0; input &= (i < b.data.Length) ? b.data[i] : 0; output.data[i] = input; } return output; } public static BitField operator |(BitField a, BitField b) { BitField output = new BitField(Math.Max(a.Length, b.Length)); for (int i = 0; i < b.data.Length && i < a.data.Length; ++i) { long input = 0; if (i < a.data.Length) input |= a.data[i]; if (i < b.data.Length) input |= b.data[i]; output.data[i] = input; } return output; } public override bool Equals(object obj) { var o = obj as BitField; if (o != null && o.Length == this.Length) { for (int i = 0; i < o.data.Length; ++i) { if (o.data[i] != this.data[i]) { return false; } } return true; } return false; } public override int GetHashCode() { return data.Sum(d => d.GetHashCode()); } public override string ToString() { StringBuilder sb = new StringBuilder(this.Length); for (int i = 0; i < this.Length; ++i) { sb.Insert(0, this[i] ? '1' : '0'); } return sb.ToString(); } public int Length { get; private set; } } }
6e368484b34d9b6869457b7c7bdae0ab7f030d29
C#
solidify-project/engine
/src/SolidifyProject.Engine.Services/ContentReaderService/FileSystemBinaryContentReaderService.cs
2.59375
3
using System.IO; using System.Threading.Tasks; using SolidifyProject.Engine.Infrastructure.Models.Base; namespace SolidifyProject.Engine.Services.ContentReaderService { public class FileSystemBinaryContentReaderService<T> : _FileSystemContentReaderServiceBase<T> where T : BinaryContentModel, new() { public FileSystemBinaryContentReaderService(string root) : base(root) { } protected override async Task<T> LoadContentByIdAsyncInternal(string id) { var path = Path.Combine(_root, id); if (!File.Exists(path)) { return null; } using (var file = new FileStream(path, FileMode.Open)) { var model = new T(); model.Id = id; model.ContentRaw = new byte[file.Length]; await file.ReadAsync(model.ContentRaw, 0, (int)file.Length).ConfigureAwait(false); model.Parse(); return model; } } } }
365e7041a111d039ea03ed6aec68628ad99c3169
C#
jonopare/extellect-utils
/src/Extellect.Utilities/Execution/CronExpression.cs
2.59375
3
#pragma warning disable 1591 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Extellect { public class CronExpression { internal class FiringIterator { private CronExpression _cron; private readonly int _minuteIndex; private readonly int _hourIndex; private readonly int _dayIndex; private readonly int _monthIndex; private readonly bool _isDayOfMonthRestricted; private readonly bool _isDayOfWeekRestricted; private int[] _expandedDays; private DateTime _startOfMonth; public FiringIterator(CronExpression cron, int year, int minuteIndex, int hourIndex, int dayIndex, bool isDayOfMonthRestricted, bool isDayOfWeekRestricted, int monthIndex) { _cron = cron; _isDayOfMonthRestricted = isDayOfMonthRestricted; _isDayOfWeekRestricted = isDayOfWeekRestricted; _startOfMonth = new DateTime(year, _cron._expandedMonths[monthIndex], 1); var dayCount = (_startOfMonth.AddMonths(1) - _startOfMonth).Days; var firstDayOfWeekOfMonth = (int)_startOfMonth.DayOfWeek; var dayOfWeeksOfMonth = Enumerable.Range(1, dayCount) //.Select(x => new { Day = x, DayOfWeek = (x + 7 - firstDayOfWeekOfMonth) % 7 }) .Select(x => new { Day = x, DayOfWeek = (x + firstDayOfWeekOfMonth - 1) % 7 }) .Where(x => _cron._expandedDayOfWeeks.Contains(x.DayOfWeek)) .Select(x => x.Day); _minuteIndex = minuteIndex; _hourIndex = hourIndex; _dayIndex = dayIndex; _monthIndex = monthIndex; if ((_isDayOfMonthRestricted && _isDayOfWeekRestricted) || (!_isDayOfMonthRestricted && !_isDayOfWeekRestricted)) { _expandedDays = _cron._expandedDayOfMonths.Where(x => x <= dayCount).Union(dayOfWeeksOfMonth).OrderBy(x => x).ToArray(); } else if (_isDayOfMonthRestricted) { _expandedDays = _cron._expandedDayOfMonths.Where(x => x <= dayCount).OrderBy(x => x).ToArray(); } else if (_isDayOfWeekRestricted) { _expandedDays = dayOfWeeksOfMonth.OrderBy(x => x).ToArray(); } } public DateTime Current { get { return new DateTime( _startOfMonth.Year, _cron._expandedMonths[_monthIndex], _expandedDays[_dayIndex], _cron._expandedHours[_hourIndex], _cron._expandedMinutes[_minuteIndex], 0 ); } } public FiringIterator Next() { int minuteIndex = _minuteIndex; int hourIndex = _hourIndex; int dayIndex = _dayIndex; int monthIndex = _monthIndex; int year = _startOfMonth.Year; if (++minuteIndex == _cron._expandedMinutes.Length) { minuteIndex = 0; if (++hourIndex == _cron._expandedHours.Length) { hourIndex = 0; if (++dayIndex == _expandedDays.Length) { dayIndex = 0; if (++monthIndex == _cron._expandedMonths.Length) { monthIndex = 0; year++; } } } } return new FiringIterator(_cron, year, minuteIndex, hourIndex, dayIndex, _isDayOfMonthRestricted, _isDayOfWeekRestricted, monthIndex); } } internal struct Range { public int Start { get; private set; } public int End { get; private set; } public Range(int once) : this() { Start = End = once; } public Range(int start, int end) : this() { Start = start; End = end; } } private List<Range> _minutes; private List<Range> _hours; private List<Range> _dayOfMonths; private List<Range> _months; private List<Range> _dayOfWeeks; private Range _minuteRange = new Range(0, 59); private Range _hourRange = new Range(0, 23); private Range _dayOfMonthRange = new Range(1, 31); private Range _monthRange = new Range(1, 12); private Range _dayOfWeekRange = new Range(0, 6); private int[] _expandedMinutes; private int[] _expandedHours; private int[] _expandedDayOfMonths; private int[] _expandedMonths; private int[] _expandedDayOfWeeks; public DateTime MaxValue { get; private set; } /// <summary> /// If both dayOfMonth or dayOfWeek is restricted (i.e. not *) then either will match. /// If only one of dayOfMonth or dayOfWeek is restricted then only that field will match. /// If neither dayOfMonth nor dayOfWeek is restricted (i.e. both are *) then all days will match. /// </summary> /// <param name="minute"></param> /// <param name="hour"></param> /// <param name="dayOfMonth"></param> /// <param name="month"></param> /// <param name="dayOfWeek"></param> public CronExpression(string minute, string hour, string dayOfMonth, string month, string dayOfWeek) { if (!TryParseMinute(minute)) throw new ArgumentException("minute", minute); if (!TryParseHour(hour)) throw new ArgumentException("hour", hour); if (!TryParseDayOfMonth(dayOfMonth)) throw new ArgumentException("dayOfMonth", dayOfMonth); if (!TryParseMonth(month)) throw new ArgumentException("month", month); if (!TryParseDayOfWeek(dayOfWeek)) throw new ArgumentException("dayOfWeek", dayOfWeek); if (_dayOfMonths.Count > 0 && _months.Count > 0) { var maxDayCount = Expand(_months, _monthRange).Select(x => MaxDayCount(x)).Min(); if (!Expand(_dayOfMonths, _dayOfMonthRange).Any(x => x <= maxDayCount)) { throw new ArgumentException("invalid schedule detected"); } } _expandedMinutes = Expand(_minutes, _minuteRange).Distinct().OrderBy(x => x).ToArray(); _expandedHours = Expand(_hours, _hourRange).Distinct().OrderBy(x => x).ToArray(); _expandedDayOfMonths = Expand(_dayOfMonths, _dayOfMonthRange).Distinct().OrderBy(x => x).ToArray(); _expandedMonths = Expand(_months, _monthRange).Distinct().OrderBy(x => x).ToArray(); _expandedDayOfWeeks = Expand(_dayOfWeeks, _dayOfWeekRange).Distinct().OrderBy(x => x).ToArray(); } internal static int MaxDayCount(int month, int year) { return month == 2 ? (IsLeapYear(year) ? 29 : 28) : MaxDayCount(month); } internal static bool IsLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } internal static int MaxDayCount(int month) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 2: return 29; case 4: case 6: case 9: case 11: return 30; default: throw new ArgumentException(); } } private bool TryConvert<T>(string value, Func<string, T> convert, out T t) { try { t = convert(value); return true; } catch (FormatException) { t = default(T); return false; } } private bool TryParse(string value, Range valueRange, Func<string, int> convert, out List<Range> values) { values = new List<Range>(); if (string.IsNullOrEmpty(value) || value == "*") return true; var parts = value.Split(','); foreach (var part in parts) { var rangeParts = part.Split('-'); switch (rangeParts.Length) { case 1: int once; if (!int.TryParse(rangeParts[0], out once)) if (!TryConvert(rangeParts[0], convert, out once)) return false; values.Add(new Range(once)); break; case 2: int start, end; if (!int.TryParse(rangeParts[0], out start)) if (!TryConvert(rangeParts[0], convert, out start)) return false; if (start < valueRange.Start || start > valueRange.End) return false; if (!int.TryParse(rangeParts[1], out end)) if (!TryConvert(rangeParts[1], convert, out end)) return false; if (start < valueRange.Start || start > valueRange.End) return false; values.Add(new Range(start, end)); break; default: return false; } } return true; } internal bool TryParseMinute(string minute) { return TryParse(minute, _minuteRange, x => { throw new FormatException(); }, out _minutes); } internal bool TryParseHour(string hour) { return TryParse(hour, _hourRange, x => { throw new FormatException(); }, out _hours); } internal bool TryParseDayOfMonth(string dayOfMonth) { return TryParse(dayOfMonth, _dayOfMonthRange, x => { throw new FormatException(); }, out _dayOfMonths); } internal bool TryParseMonth(string month) { return TryParse(month, _monthRange, ConvertMonth, out _months); } internal bool TryParseDayOfWeek(string dayOfWeek) { return TryParse(dayOfWeek, _dayOfWeekRange, ConvertDayOfWeek, out _dayOfWeeks); } internal int ConvertMonth(string month) { switch (month) { case "Jan": return 1; case "Feb": return 2; case "Mar": return 3; case "Apr": return 4; case "May": return 5; case "Jun": return 6; case "Jul": return 7; case "Aug": return 8; case "Sep": return 9; case "Oct": return 10; case "Nov": return 11; case "Dec": return 12; default: throw new FormatException(); } } internal int ConvertDayOfWeek(string dayOfWeek) { switch (dayOfWeek) { case "Sun": return 0; case "Mon": return 1; case "Tue": return 2; case "Wed": return 3; case "Thu": return 4; case "Fri": return 5; case "Sat": return 6; default: throw new FormatException(); } } public IEnumerable<DateTime> FiringSequence(DateTime start, int maxIterations = 100) { var minuteIndex = Array.BinarySearch(_expandedMinutes, start.Minute); if (minuteIndex < 0) { minuteIndex = System.Math.Min(~minuteIndex, _expandedMinutes.Length - 1); } var hourIndex = Array.BinarySearch(_expandedHours, start.Hour); if (hourIndex < 0) { hourIndex = System.Math.Min(~hourIndex, _expandedHours.Length - 1); } // TODO: some kind of efficiency with days too? var monthIndex = Array.BinarySearch(_expandedMonths, start.Month); if (monthIndex < 0) { monthIndex = System.Math.Min(~monthIndex, _expandedHours.Length - 1); } // start at the first firing of the year var iterator = new FiringIterator(this, start.Year, minuteIndex, hourIndex, 0, _dayOfMonths.Any(), _dayOfWeeks.Any(), monthIndex); int i = 0, skipped = 0; while (i < maxIterations) { var current = iterator.Current; if (current >= start) { if (skipped >= 0) { //Console.WriteLine("Skipped {0} premature firings", skipped); skipped = -1; } yield return current; i++; } else { // seeking forward until we're ready to start returning results skipped++; } iterator = iterator.Next(); } } internal bool HasMonthFlag(DateTime when) { return !_months.Any() || _months.Any(x => x.Start <= when.Month && x.End >= when.Month); } internal DateTime NextMonth(DateTime when) { int month; if (!TryGetFirst(_months, _monthRange, x => x > when.Month, out month)) return new DateTime(when.Year + 1, month, 1); else return new DateTime(when.Year, month, 1); } internal bool HasDayOfMonthFlag(DateTime when) { return !_dayOfMonths.Any() || _dayOfMonths.Any(x => x.Start <= when.Day && x.End >= when.Day); } internal DateTime NextDayOfMonth(DateTime when) { int dayOfMonth; var overflow = !TryGetFirst(_dayOfMonths, _dayOfMonthRange, x => x > when.Day, out dayOfMonth); when = new DateTime(when.Year, when.Month, dayOfMonth); if (overflow) { if (when.Month == 12) when = new DateTime(when.Year + 1, 1, dayOfMonth); else when = new DateTime(when.Year, when.Month + 1, dayOfMonth); } return when; } internal bool HasDayOfWeekFlag(DateTime when) { return !_dayOfWeeks.Any() || _dayOfWeeks.Any(x => x.Start <= (int)when.DayOfWeek && x.End >= (int)when.DayOfWeek); } internal DateTime NextDayOfWeek(DateTime when) { var dayOfWeek = when.DayOfWeek == DayOfWeek.Saturday ? 0 : (int)when.DayOfWeek; int day; if (!TryGetFirst(_dayOfWeeks, _dayOfWeekRange, x => x > dayOfWeek, out day)) throw new NotImplementedException(); var offset = (day - (int)when.DayOfWeek + 7) % 7; return when.Date.AddDays(offset); } internal bool HasHourFlag(DateTime when) { return !_hours.Any() || _hours.Any(x => x.Start <= when.Hour && x.End >= when.Hour); } internal DateTime NextHour(DateTime when) { int hour; var overflow = !TryGetFirst(_hours, _hourRange, x => x > when.Hour, out hour); when = new DateTime(when.Year, when.Month, when.Day, hour, 0, 0); if (overflow) when = when.AddDays(1); return when; } internal bool HasMinuteFlag(DateTime when) { return !_minutes.Any() || _minutes.Any(x => x.Start <= when.Minute && x.End >= when.Minute); } internal DateTime NextMinute(DateTime when) { var m = when.Minute == _minuteRange.End ? _minuteRange.Start : when.Minute; int minute; var overflow = !TryGetFirst(_minutes, _minuteRange, x => x > m, out minute); when = new DateTime(when.Year, when.Month, when.Day, when.Hour, minute, 0); if (overflow) { when = when.Add(TimeSpan.FromHours(1)); } return when; } internal static IEnumerable<int> Expand(IEnumerable<Range> ranges, Range valueRange) { if (!ranges.Any()) { foreach (var value in Enumerable.Range(valueRange.Start, valueRange.End - valueRange.Start + 1)) yield return value; } else { foreach (var range in ranges) foreach (var value in Enumerable.Range(range.Start, range.End - range.Start + 1)) yield return value; } } /// <summary> /// Try return the first item that matched the given predicate. /// If no items matched, then return false and assign the first item from the list. /// </summary> /// <param name="ranges"></param> /// <param name="valueRange"></param> /// <param name="predicate"></param> /// <param name="first"></param> /// <returns></returns> internal static bool TryGetFirst(IEnumerable<Range> ranges, Range valueRange, Func<int, bool> predicate, out int first) { using (var e = Expand(ranges, valueRange).OrderBy(x => x).GetEnumerator()) { e.MoveNext(); if (predicate(first = e.Current)) { return true; } while (e.MoveNext()) { if (predicate(e.Current)) { first = e.Current; return true; } } return false; } } public override string ToString() { var temp = new StringBuilder(); foreach (var ranges in new[] { _minutes, _hours, _dayOfMonths, _months, _dayOfWeeks }) { if (temp.Length != 0) temp.Append(" "); if (ranges.Count == 0) temp.Append("*"); for (int r = 0; r < ranges.Count; r++) { if (r != 0) temp.Append(","); var range = ranges[r]; if (range.Start == range.End) { temp.Append(range.Start); } else { temp.Append(range.Start); temp.Append("-"); temp.Append(range.End); } } } return temp.ToString(); } } }
fbea6bf07b5bfbf3a1e47cbaaf00ac51a7611465
C#
TrifonApov/SoftUni
/2023-02-CSharp-OOP/Exams/20220822/01. Structure_Skeleton_6.0/Repositories/RoomRepository.cs
2.9375
3
using System.Collections.Generic; using System.Linq; using BookingApp.Models.Rooms.Contracts; using BookingApp.Repositories.Contracts; namespace BookingApp.Repositories { public class RoomRepository : IRepository<IRoom> { private List<IRoom> rooms; public RoomRepository() { rooms = new List<IRoom>(); } public void AddNew(IRoom room) => rooms.Add(room); public IRoom Select(string Name) => rooms.FirstOrDefault(r => r.GetType().Name == Name); public IReadOnlyCollection<IRoom> All() => rooms.AsReadOnly(); } }
26bee75b84f187a36c49b187f2c7c62e0b3922f7
C#
DejanMilicic/RavenCms
/src/RavenCms/RavenCms/Infrastructure/Helper.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; namespace RavenCms.Infrastructure { public static class Helper { public static List<string> GetRandomTags() { List<string> tags = new List<string> { "music", "business", "politics", "domestic", "international", "health" }; List<string> randomTags = new List<string>(); for (int i = 0; i < new Random().Next(1, tags.Count + 1); i++) { string tag = tags.OrderBy(x => Guid.NewGuid()).First(); randomTags.Add(tag); tags.Remove(tag); } return randomTags; } } }
7ffb9d8b3b8ef67e2745bf1e381815e3573eb46f
C#
DanielPalatinszky/CSharp-Class-9
/CSharp Class 9/Example.cs
3.15625
3
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; namespace CSharp_Class_9 { // Egy structnak is lehetnek konstruktorai és metódusai // Akkor mi a különbség a kettő között? // C#-ban valójában a típusokat két csoportra tudjuk bontani: érték és referencia típusok // Érték típus: olyan típusok, amelyből ha létrehozunk egy változót, akkor a változó memóriaterületén a típusnak megfelelő konkrét értéket találjuk // Érték típus az összes primitív típus (float, double, bool, int stb.) és a struct-ok, illetve enum-ok // Referencia típus: olyan típusok, amelyből ha létrehozunk egy változót, akkor a változó memóriaterületén nem a konkrét értéket, hanem egy memóriacímet találunk, ami az érték memóriában elfoglalt helyére mutat // Referencia típus a classok és a stringek // Vegyük észre, hogy a referencia típusok pontosat azért lehetnek null-ok, mert olyankor maga a memóriacím nem mutat sehova. Az érték típusok pedig pont azért nem lehetnek null-ok, mert a konkrét értéket tároljuk, aminél a null mint érték nem értelmezhető. struct ExampleStruct { public int example; public ExampleStruct(int example) { this.example = example; } public void Print() { Console.WriteLine(this.example); } } class ExampleClass { public int example; public static int staticExample; public ExampleClass(int example) { this.example = example; // Itt azért kell a this, mert különben a fordító azt hinné, hogy a konstruktor paraméteréről beszélünk, miközben én az aktuális objektum example adattagjáról beszélek (a paraméter magasabb prioritást élvez) } public void Print() { Console.WriteLine(this.example); } public static void StaticPrint() { // Mivel static a metódus, ezért osztályszinten vagyunk // Ebből következik, hogy a metódust nem példányon hívtuk meg // Ezáltal nincs this // Ezáltal nem érjük el a példányszintű adattagokat és metódusokat! //Console.WriteLine(this.example); // Nem megy! //Print(); // Nem megy! // A static dolgokat viszont elérjük Console.WriteLine(staticExample); // Megy! StaticExampleMethod(); // Megy! } private static void StaticExampleMethod() { } private void ExampleMethod() { // Nem static-ból viszont mindent elérünk! Console.WriteLine(example); Console.WriteLine(staticExample); Print(); StaticPrint(); } private static void StaticExampleMethodWithParameter(ExampleClass exampleClass) { // Viszont ha van egy példányom paraméterként vagy valamilyen más módon, azon static-ból is elérem a nem static dolgokat! Console.WriteLine(exampleClass.example); // Megy! exampleClass.Print(); // Megy! // Sőt, mivel az osztályon belül vagyunk, ezért a paraméter privát adattagjait és metódusait is elérjük exampleClass.ExampleMethod(); // Megy! } } struct A { private B b; // struct-ban lehet struct //private A a; // csak nem azonos típusú private C c; // struct-ban lehet class } struct B { } class C { private D d; // class-ban lehet class private C c; // akár azonos típus is, hisz alapértelmezetten null-ként jön létre private A a; // class-ban lehet struct } class D { } class ObjectCounterClass { public int counter1 = 0; public static int counter2 = 0; public ObjectCounterClass() { counter1++; counter2++; } } }
c337b064367db69cdffa95cb704269f3dace0479
C#
alakanu/GGJ2019
/Assets/Scripts/TypeWriter.cs
2.828125
3
using System.Collections; using UnityEngine; using UnityEngine.UI; class TypeWriter { public bool Writing { get { return writing; } } public IEnumerator WriteText(string text, Text uiText, AudioSource audio) { fastForward = false; writing = true; int parsedCharactersCount = 0; while (parsedCharactersCount < text.Length) { if (fastForward) { uiText.text = text; parsedCharactersCount = text.Length; fastForward = false; } else { uiText.text = text.Substring(0, ++parsedCharactersCount); yield return waitBetweenEachLetter; } audio.Play(); } writing = false; } public void FastForward() { fastForward = true; } public void Reset() { fastForward = false; writing = false; } bool fastForward; bool writing; WaitForSeconds waitBetweenEachLetter = new WaitForSeconds(0.05f); }
b3dd2304889d7b8595d1bf3deb612ba13e9dd5e5
C#
zsuzsannamangu/University-Registrar
/University/Controllers/StudentsController.cs
2.609375
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using University.Models; namespace University.Controllers { public class StudentsController : Controller { [HttpGet("/students")] public ActionResult Index() { List<Student> allStudents = Student.GetAll(); return View(allStudents); } [HttpGet("/students/new")] public ActionResult New() { return View(); } [HttpPost("/students")] public ActionResult Create(string name, string number) { Student newStudent = new Student(name, number); newStudent.Save(); List<Student> allStudents = Student.GetAll(); return View("Index", allStudents); } [HttpGet("/students/{id}")] public ActionResult Show(int id) { Dictionary<string, object> model = new Dictionary<string, object>(); Student selectedStudent = Student.Find(id); List<Course> studentCourses = selectedStudent.GetCourses(); List<Course> allCourses = Course.GetAll(); model.Add("student", selectedStudent); model.Add("studentCourses", studentCourses); model.Add("allCourses", allCourses); return View(model); } [HttpPost("/students/{studentsId}/courses/new")] public ActionResult AddCourse(int studentsId, int coursesId) { Student student = Student.Find(studentsId); Course course = Course.Find(coursesId); student.AddCourse(course); return RedirectToAction("Show", new { id = studentsId }); } } }
07ac887b522b5e0c287cc19eefef1b97b9e76316
C#
umayya154/Event-designer-system
/Event/WcfService2/WcfService2/Admin.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; namespace WcfService2 { public class Admin { private string securitycode = "admin123"; public string Securitycode { get { return securitycode; } set { securitycode = value; } } private string password = "12345"; public string Password { get { return password; } set { password = value; } } private string name = "Admin"; public string Name { get { return name; } set { name = value; } } public bool is_validAdmin(string aname, string apassword, string acode) { bool found = false; if((Name == aname)&&(Password == apassword)&&(securitycode == acode)){ found = true; } return found; } } }
8312f856507da6abb9801ef115b5fadb69813452
C#
imxingquan/DW.Framework4
/DW.Framework/Data/DataAccessor.cs
2.515625
3
/** * 缼޹˾ (C) 2007 * ļ: DataAccess.cs * : 2007.5.20 * ޸ʱ:2011.4.8 * : * ݷͨûࡣ * */ using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using System.Web; using System.Web.Caching; using System.Web.Configuration; using DW.Framework.Configuration; using DW.Framework.Pager; namespace DW.Framework.Data { public enum MaxMin { Max, Min } /// <summary> /// ij /// </summary> public abstract class DataAccessor<T> where T:new() { public string connectionString; /// <summary> /// ԣرơûָ[Table("table_name")]ʹơ /// </summary> public string TableName { get { //ԣ[Table("tablename")]ʹԣʹ TableAttribute attr = Attribute.GetCustomAttribute(typeof(T), typeof(TableAttribute)) as TableAttribute; //TableAttribute[] attr = typeof(T).GetCustomAttributes(typeof(TableAttribute), true) as TableAttribute[]; if(attr!=null){ return attr.TableName; } else{ return typeof(T).Name; } } } /// <summary> /// nullֵתݿеnullֵ /// </summary> /// <param name="obj">ҪתĶ</param> /// <returns>תĶ</returns> /// <remarks>ЩдݿֵΪnull,ݿеnullеnullͬҪת</remarks> public object ConvertDBNull(object obj) { return obj == null ? DBNull.Value : obj; } #region SQL /// <summary> /// ִSQL䣬ؽ磺롢ɾ²ȡ /// </summary> /// <param name="cmd">DbCommand</param> /// <returns>1ʾִгɹ</returns> protected int ExecuteNonQuery(DbCommand cmd) { int i = -1; try { foreach (DbParameter param in cmd.Parameters) { if (param.Direction == ParameterDirection.Input) { //˴Ҳд //param.Value = ConvertDBNull(param.Value); if (param.Value == null) param.Value = DBNull.Value; } } i = cmd.ExecuteNonQuery(); } catch (Exception ex) { string errmsg = string.Format("ִС{0}ʱ:\r\n{1}\r\nϸ:{2}", cmd.CommandText, ex.Message, ex.StackTrace); DW.Framework.Logger.Log.Write(errmsg); } return i; } /// <summary> /// ִSQL䣬ִн /// </summary> /// <param name="cmd">DbCommand</param> /// <returns>SQLĽһIDataReader</returns> protected IDataReader ExecuteReader(DbCommand cmd) { return ExecuteReader(cmd, CommandBehavior.CloseConnection); } /// <summary> /// ִSQL䣬ִн /// </summary> /// <param name="cmd">DbCommand</param> /// <param name="behavior">CommandBehavior</param> /// <returns>SQLĽһIDataReader</returns> protected IDataReader ExecuteReader(DbCommand cmd, CommandBehavior behavior) { IDataReader reader = null; try { reader = cmd.ExecuteReader(behavior); } catch (Exception ex) { string errmsg = string.Format("ִС{0}ʱ:\r\n{1}\r\nϸ:{2}", cmd.CommandText, ex.Message, ex.StackTrace); if(reader!=null)reader.Close(); DW.Framework.Utils.Helper.ShowErrorPage(errmsg); throw new Exception(errmsg); } return reader; } /// <summary> /// ִSQL䣬һֵ /// </summary> /// <param name="cmd">DbCommand</param> /// <returns>еһֵ</returns> /// <remarks>һݸ͵Ȳϡ</remarks> protected object ExecuteScalar(DbCommand cmd) { object o = null; try { o = cmd.ExecuteScalar(); } catch (Exception ex) { string errmsg = string.Format("ִС{0}ʱ:\r\n{1}\r\nϸ:{2}", cmd.CommandText, ex.Message, ex.StackTrace); DW.Framework.Logger.Log.Write(errmsg); } return o; } #endregion protected string UpFirstChar(string strvalue) { return strvalue.Substring(0, 1).ToUpper() + strvalue.Substring(1, strvalue.Length - 1); } #region ÷ʵ帳ֵ /// <summary> /// ÷ʵ帳ֵķ,Զʵ /// </summary> /// <typeparam name="T"></typeparam> /// <param name="reader"></param> /// <returns></returns> protected T ReaderTo(IDataReader reader) { T targetObj = new T(); //ʵ IDictionary<string,object>dict = null; //չֶζ //Field չֶ EtityBase System.Reflection.PropertyInfo propertyExtField = targetObj.GetType().GetProperty("Field"); for (int i = 0; i < reader.FieldCount; i++) //ݿֶ { object value = reader.GetValue(i) is DBNull ? null : reader.GetValue(i); //ǷʹԱעӳеֶ if (DataMapper.FillColumnAttribteProperty(targetObj, reader.GetName(i), value)) continue; System.Reflection.PropertyInfo propertyInfo = targetObj.GetType().GetProperty(UpFirstChar(reader.GetName(i))); if (propertyInfo != null) //ֵ { DataMapper.SetValue(targetObj, propertyInfo, value); } else if(propertyExtField != null)//ֵֵֶ { //entities û,ͨFiled["field_name"]EntityObj["filed_name"] (this) //EntityչEntityBaseжʹֵ䶨 //Field["filed_name"] = value DataMapper.SetValue(ref dict, reader.GetName(i), value); } } //չֶ if (propertyExtField != null) { propertyExtField.SetValue(targetObj, dict, null); } return targetObj; } /// <summary> /// ÷ʵ帳ֵ /// </summary> /// <param name="reader"></param> /// <param name="targetObj"></param> protected void ReaderToObject(IDataReader reader, object targetObj) { for (int i = 0; i < reader.FieldCount; i++) { System.Reflection.PropertyInfo propertyInfo = targetObj.GetType().GetProperty(reader.GetName(i)); if (propertyInfo != null) { if (reader.GetValue(i) != DBNull.Value) { if (propertyInfo.PropertyType.IsEnum) { propertyInfo.SetValue(targetObj, Enum.ToObject(propertyInfo.PropertyType, reader.GetValue(i)), null); } else { propertyInfo.SetValue(targetObj, reader.GetValue(i), null); } } } } } #endregion #region Fill from DataReader /// <summary> /// ȡIDataReaderһ /// </summary> /// <param name="reader"></param> /// <returns></returns> protected virtual T GetFromReader(IDataReader reader) { //T obj = default(T); try { return ReaderTo(reader); } catch (Exception ex) { DW.Framework.Logger.Log.Write(string.Format("{0}ֶӳʱ:{1}", typeof(T).Name, ex.Message)); //throw new Exception(string.Format("{0}ֶӳʱ:{1}", typeof(T).Name, ex.Message)); } return default(T); } /// <summary> /// IDataReaderȡ /// </summary> /// <param name="reader"></param> /// <returns>ݼ</returns> protected virtual IPagedList<T> GetListFromReader(IDataReader reader) { IPagedList<T> list = new PagedList<T>(); while (reader.Read()) { list.Add(GetFromReader(reader)); } reader.Close(); // close ſԶ output returnvalueֵ return list; } #endregion } }
49669ad8a6857b690ecaecd966b2781202b5ca13
C#
Earu/Octovisor
/Octovisor.Client/Exceptions/UnknownRemoteProcessException.cs
2.546875
3
using System; namespace Octovisor.Client.Exceptions { public class UnknownRemoteProcessException : Exception { public UnknownRemoteProcessException(string processName) { string msg = $"Process \'{processName}\' does not exist or is not available"; this.Message = msg; } public override string Message { get; } } }
0e5a44468e45a34639c17cfd13ed8b8fc00a4aa0
C#
BialekM/training
/hornets 2.0/training/HornetsTraining/HornetsTraining/Training1/HomeWork/MarcinJaniak/MarcinJaniakList.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Toci.HornetsTraining.Training1.Generics; namespace Toci.HornetsTraining.Training1.HomeWork.MarcinJaniak { class MarcinJaniakList<TListItem> : MyList<TListItem> { public override void Add(TListItem item) { if (listOfItems == null) { listOfItems = new TListItem[0]; } Index += 1; var tempList = new TListItem[Index]; for (int i = 0; i < listOfItems.Length; i++) { tempList[i] = listOfItems[i]; } tempList[Index - 1] = item; listOfItems = tempList; } } }
0cdf356579c7637c83591e98ca2a3d0e8106a0ab
C#
mikeoye25/TechAnswers
/TechAnswers.Services/TransactionService.cs
2.546875
3
using CsvHelper; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using TechAnswers.Core; using TechAnswers.Core.Interfaces; using TechAnswers.Core.Models; using TechAnswers.Core.ViewModels; namespace TechAnswers.Services { public class TransactionService : ITransactionService { private readonly IUnitOfWork UnitOfWork; public TransactionService(IUnitOfWork unitOfWork) { this.UnitOfWork = unitOfWork; } public async Task<IEnumerable<Transaction>> Get() { return await UnitOfWork.Transactions.Get(); } public async Task<Transaction> Get(string id) { return await UnitOfWork.Transactions.Get(id); } public async Task<IEnumerable<DailyTransactionsPerServiceId>> GetDailyTransactionsPerServiceId(DateTime selectedDate) { return await UnitOfWork.Transactions.GetDailyTransactionsPerServiceId(selectedDate); } public async Task<IEnumerable<DailyTransactionsPerServiceIdPerDay>> GetDailyTransactionsPerServiceIdPerDay() { return await UnitOfWork.Transactions.GetDailyTransactionsPerServiceIdPerDay(); } public async Task<IEnumerable<MonthlyTransactionsPerServiceIdPerDay>> GetMonthlyTransactionsPerServiceIdPerDay() { return await UnitOfWork.Transactions.GetMonthlyTransactionsPerServiceIdPerDay(); } public async Task<IEnumerable<DailyTransactionsPerServiceIdPerDay>> GetTransactionsPerServiceIdUsingTimeRange(DateTime startDate, DateTime endDate) { return await UnitOfWork.Transactions.GetTransactionsPerServiceIdUsingTimeRange(startDate, endDate); } public async Task<IEnumerable<DailyTransactionsPerServiceIdPerClientId>> GetTransactionsPerServiceIdPerClientIdUsingTimeRange(DateTime startDate, DateTime endDate) { return await UnitOfWork.Transactions.GetTransactionsPerServiceIdPerClientIdUsingTimeRange(startDate, endDate); } public async Task<Transaction> CreateTransaction(Transaction newTransaction) { await UnitOfWork.Transactions.AddAsync(newTransaction); return newTransaction; } public List<Transaction> ReadCsvFileToTransaction(string path) { var transactions = new List<Transaction>(); try { using (var reader = new StreamReader(path)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Context.RegisterClassMap<TransactionMap>(); transactions = csv.GetRecords<Transaction>().ToList(); } } catch (Exception e) { Console.WriteLine(e); } return transactions; } } }
eef9d6015c766953ac65f08d5f35cc430167d65a
C#
shendongnian/download4
/code10/1732496-54960407-192767612-2.cs
2.59375
3
[HttpPatch("{id}")] public IActionResult Patch(int id, [FromBody]JsonPatchDocument<Node> value) { try { //nodes collection is an in memory list of nodes for this example var result = nodes.FirstOrDefault(n => n.Id == id); if (result == null) { return BadRequest(); } value.ApplyTo(result, ModelState);//result gets the values from the patch request return NoContent(); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex); } }
b71cb96a4e7821390304689c69be372a5c52a9ef
C#
ArikMackenburg/Lab03
/Lab/Challenge2.cs
3.90625
4
using System; using System.Collections.Generic; using System.Text; namespace Lab { public class Challenge2 { public static void HandleChallenge2() { prompt: Console.WriteLine("Pick a number between 2-10"); string input = Console.ReadLine(); int length = LengthHandler(input); if( length == -1) { goto prompt; } double[] arr = new double[length]; for (int i = 0; i < arr.Length; i++) { Console.WriteLine($"Choose number {i+1} of {length}" ); string num = Console.ReadLine(); arr[i] = InputHandler(num); } Console.WriteLine(FindAverage(arr)); } public static double FindAverage(double[] arr) { double sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } double avg = sum / arr.Length; return avg; } public static double InputHandler(string input) { try { double num = Convert.ToDouble(input); if (num < 0) { num = System.Math.Abs(num); return num; } else { return num; } } catch (Exception) { double num = 0; return num; } } public static int LengthHandler(string input) { try { int arrLength; arrLength = Convert.ToInt32(input); if (arrLength > 1 && arrLength < 11) { return arrLength; } else { return -1; } } catch(Exception) { return -1; } } } }
0f23d0f5f57d725d54cb0c0736f7c1eaeb8ffc77
C#
GraemeRMcAllister/SET09102
/NBMFS/Models/MessageValidation.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBMFS.Models { class MessageValidation { public static void ValidateHeader(string header) { string typelist = ";"; if ((header.Length == 10) && (int.TryParse(header.Substring(1, 9), out int res))) // True if header is 10 and the ID is a number { foreach (Enum s in Enum.GetValues(typeof(MessageType))) // gets the preset type list in Message CLass { typelist += $" {s},"; // building the message box if function fails if (s.ToString().Substring(0, 1) == header.Substring(0, 1)) // compares the first char(string) in header, to the first char(string) in type return; } throw new Exception($"Header start must correspond to one of{typelist.TrimEnd(',')}."); // returning list of types } throw new Exception("Header must be a Message-type indicator; followed by a 9 digit ID."); // if header is 10 and the ID is a number is false } } }
5b54b8e466aa2505a8172a74602e1051c8b48c1b
C#
furaga/SketchTyping
/SketchTypingLib/SketchTypingClient.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Windows.Forms; using System.Drawing; using System.IO; using System.Runtime.InteropServices; namespace FLib { public class SketchTypingClient : IDisposable { readonly System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] resBytes = new byte[256]; System.Net.Sockets.TcpClient client; System.Net.Sockets.NetworkStream ns; System.IO.MemoryStream ms = new MemoryStream(); public SketchTypingClient(string host, int port) { client = new System.Net.Sockets.TcpClient(host, port); ns = client.GetStream(); } public void Dispose() { ms.Close(); ns.Close(); client.Close(); } public string ReadString() { try { if (!client.Connected) return ""; ms.Close(); ms = new MemoryStream(); //サーバーから送られたデータを受信する while (ns.CanRead && ns.DataAvailable) { //データの一部を受信する int resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はサーバーが切断したと判断 if (resSize == 0) { break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); } if (ms.Length <= 0) return ""; //受信したデータを文字列に変換 string text = enc.GetString(ms.ToArray()); // 受信確認用のシグナルを送信 // byte[] sendBytes = enc.GetBytes("s"); // ns.Write(sendBytes, 0, sendBytes.Length); return text.TrimEnd(';'); } catch (Exception ex) { MessageBox.Show(ex + ":" + ex.StackTrace); return ""; } } public void SendReceivedSignal() { try { if (!client.Connected) return; if (ns.CanWrite) { byte[] sendBytes = enc.GetBytes("s"); ns.Write(sendBytes, 0, sendBytes.Length); } } catch (Exception ex) { MessageBox.Show(ex + ":" + ex.StackTrace); } } } }
4704f5ea6a6c553d383191c7cdf3fe49ec83803e
C#
joshseward/HotDrinkMachine
/HotDrinksMachine/Controllers/HotDrinkController.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using HotDrinksMachine.HotDrinks; using HotDrinksMachine.Types; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace HotDrinksMachine.Controllers { [ApiController] [Route("[controller]")] public class HotDrinkController : ControllerBase { private readonly ILogger<HotDrinkController> _logger; private readonly IHotDrinkFactory _hotDrinkFactory; public HotDrinkController(ILogger<HotDrinkController> logger, IHotDrinkFactory hotDrinkFactory) { _logger = logger; _hotDrinkFactory = hotDrinkFactory; } [HttpGet("{hotDrinkId:int}")] public ActionResult<List<string>> GetHotDrink(int hotDrinkId) { try { if(hotDrinkId > 0) { var hotdrink = _hotDrinkFactory.GetHotDrink((HotDrinksEnum)hotDrinkId); return Ok(hotdrink.Create()); } else { throw new ArgumentException("Drink Id Cannot be 0"); } } catch(ArgumentException ex) { _logger.LogError(ex, "Bad Request Getting Drink"); return StatusCode(StatusCodes.Status400BadRequest, ex.Message); } catch(Exception ex) { _logger.LogError(ex, "Error When Getting Drink"); return StatusCode(StatusCodes.Status500InternalServerError); } } } }
904d5ef166132d1eaa974d7ee8366f599333701d
C#
okwisfav/TOM-fun-game
/TOM fun game/the best game five/sweet game/FavourTomGame/Instruction.cs
2.609375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FavourTomGame { public partial class INSTRUCTION : Form { public INSTRUCTION() { InitializeComponent(); } private void INSTRUCTION_Load(object sender, EventArgs e) { int counter = 0; string line; System.IO.StreamReader file = new System.IO.StreamReader(@".\inst.txt"); while ((line = file.ReadLine()) != null) { listBox1.Items.Add(line); counter++; } } private void button1_Click(object sender, EventArgs e) { new MainMenu().Show(); this.Hide(); } } }
901f76df264c756280e7664482893761de64da2e
C#
tomasking/CraftsmanshipKatas
/CalculatorKata/TicTacToeKata/Turn.cs
2.5625
3
namespace CraftsmanKata.TicTacToeKata { internal struct Turn { private readonly Column column; private readonly Row row; private readonly Symbol symbol; public Turn(Column column, Row row, Symbol symbol) { this.column = column; this.row = row; this.symbol = symbol; } } }
057da186eb2e47da1bc3ed0cc08be0af6489f1b5
C#
combit/ll-samples
/Microsoft .NET/.NET Core 3.1/WinForms/RTF Sample/Form1.cs
2.59375
3
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Windows.Forms; using combit.Reporting; namespace RTFSample { public partial class Form1 : Form { public Form1() { InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // if (!File.Exists("rtf.crd")) { Directory.SetCurrentDirectory(@"..\..\..\"); } // Preload initial file LoadFileInRTFControl(Path.Combine(Directory.GetCurrentDirectory(), "infodlg.rtf")); } private void LoadFileInRTFControl(string FileName) { // Set the contents listLabelRTFControl1.Content = File.ReadAllText(FileName, Encoding.ASCII); } /// <summary> /// Property to to get the rtf content. It's read only. /// </summary> private List<RtfContent> RtfDataSource { get { listLabelRTFControl1.ContentMode = LlRTFContentMode.Evaluated; List<RtfContent> result = new List<RtfContent>(); result.Add(new RtfContent(this.listLabelRTFControl1.Content)); return result; } } private void MenuItem5_Click(object sender, System.EventArgs e) { Close(); } private void button1_Click(object sender, EventArgs e) { // Let user choose file and display if (ofd.ShowDialog() == DialogResult.OK) { LoadFileInRTFControl(ofd.FileName); } } private void button2_Click(object sender, EventArgs e) { try { // Call designer for project "rtf.crd" listLabel1.DataSource = RtfDataSource; listLabel1.Design("Define RTF Layout", LlProject.Card, "rtf.crd", true); } catch (ListLabelException LlException) { // Catch Exceptions MessageBox.Show("Information: " + LlException.Message + "\n\nThis information was generated by a List & Label custom exception.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void button3_Click(object sender, EventArgs e) { try { // Print project "rtf.crd" listLabel1.DataSource = RtfDataSource; listLabel1.Print(LlProject.Card, "rtf.crd", false, LlPrintMode.Export, LlBoxType.StandardWait, "Printing...", true, ""); } catch (ListLabelException LlException) { // Catch Exceptions MessageBox.Show("Information: " + LlException.Message + "\n\nThis information was generated by a List & Label custom exception.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } // helper class for holding the rtf content class RtfContent { public RtfContent(string content) { Content = content; } public string Content { get; set; } } }
f64fa676e15043194f7f6010a1591a1fbeceab12
C#
waldos200/Programacion1
/UNIDAD_4/Grupo#4_Herencia/PrEjercicio2/PrEjercicio2/PrEjercicio2/Automovil.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PrEjercicio2 { class Automovil:Transporte { public string marca; public string modelo; public int motor; public Automovil(string marca, string modelo, int motor, string tipoTrans, int cantPasajeros) : base(tipoTrans, cantPasajeros) { this.marca = marca; this.modelo = modelo; this.motor = motor; } new public void Mostrar() { base.Mostrar(); Console.Write("\n\t\tMarca: {0}\n\t\tModelo: {1}\n\t\tMotor: {2}", marca, modelo, motor); } } }
fedf7b967c1252558f503b03f5872001ef52adf4
C#
cocodrips/marathon24
/marathon24_2014_problemset_and_inputs/pap/paperBoy.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using Watch = System.Diagnostics.Stopwatch; using StringBuilder = System.Text.StringBuilder; using BitVector = System.Collections.Specialized.BitVector32; class Solver { Random r = new Random(0); int last; int m; void Solve() { var n = sc.Integer(); m = sc.Integer(); var map = new HashMap<int, int>(); last = n * m; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) map[i * m + j] = i * m + j; var sw = new Watch(); var current = getScore(map); long end = 60000; long now = 0; int best=int.MaxValue; KeyValuePair<int, int>[] bestSeq = map.ToArray(); var R=10000; sw.Start(); while (now < end) { var p = r.Next() % last; var q = r.Next() % last; if (p == q) continue; var tmp = map[p]; map[p] = map[q]; map[q] = tmp; var next = getScore(map); var force = R*(end-now)>end*(r.Next()%R); if (next > current || force) { current = next; } else { map[q] = map[p]; map[p] = tmp; } if (current < best) { best = current; bestSeq = map.ToArray(); } now = sw.ElapsedMilliseconds; } //Printer.PrintLine(best); var ar = n.Enumerate(i => new int[m]); foreach (var x in bestSeq) { var p = x.Value / m; var q = x.Value % m; ar[p][q] = x.Key + 1; } foreach(var a in ar) Printer.PrintLine(a); } int getScore(HashMap<int, int> map) { var visited = new HashMap<int, int>(); var sx = map[0] / m; var sy = map[0] % m; for (int i = 1; i < last; i++) { var nx = map[i] / m; var ny = map[i] % m; var dist = Math.Abs(sx - nx) + Math.Abs(sy - ny); sx = nx; sy = ny; visited[dist]++; } var max = -1; foreach (var x in visited) { max = Math.Max(max, x.Value); } return max; } #region Main and Settings static void Main() { const string txt = @"C:\Users\camiya\Dropbox\Programming\competition\marathon24\marathon24\marathon24_2014_problemset_and_inputs\pap\pap10"; #if DEBUG var eStream = new System.IO.FileStream("debug.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write); var iStream = new System.IO.FileStream(txt + ".in", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); Console.SetIn(new System.IO.StreamReader(iStream)); #if TEST var oWriter = new System.IO.StreamWriter(new System.IO.FileStream(txt + ".out", System.IO.FileMode.Create, System.IO.FileAccess.Write)) { NewLine = "\n", AutoFlush = true }; Printer.SetOut(oWriter); #endif System.Diagnostics.Debug.AutoFlush = true; System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(new System.IO.StreamWriter(eStream) { NewLine = "\n" })); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); try { #endif var solver = new Solver(); solver.Solve(); #if DEBUG } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.ReadKey(true); return; } #endif #if TEST #elif DEBUG sw.Stop(); Console.ForegroundColor = ConsoleColor.Green; Printer.PrintLine("Time:{0}ms", sw.ElapsedMilliseconds); Console.ReadKey(true); #endif } _Scanner sc = new _Scanner(); #endregion } #region IO Helper static public class Printer { static private System.IO.TextWriter writer; static readonly private System.Globalization.CultureInfo info; static string Separator { get; set; } static Printer() { SetOut(Console.Out); info = System.Globalization.CultureInfo.InvariantCulture; Separator = " "; } public static void SetOut(System.IO.TextWriter writer) { Printer.writer = writer; Printer.writer.NewLine = "\n"; } static public void Print(int num) { writer.Write(num.ToString(info)); } static public void Print(int num, string format) { writer.Write(num.ToString(format, info)); } static public void Print(long num) { writer.Write(num.ToString(info)); } static public void Print(long num, string format) { writer.Write(num.ToString(format, info)); } static public void Print(double num) { writer.Write(num.ToString(info)); } static public void Print(double num, string format) { writer.Write(num.ToString(format, info)); } static public void Print(string str) { writer.Write(str); } static public void Print(string format, params object[] arg) { writer.Write(format, arg); } static public void Print<T>(string format, IEnumerable<T> sources) { writer.Write(format, sources.OfType<object>().ToArray()); } static public void Print(IEnumerable<char> sources) { writer.Write(sources.AsString()); } static public void Print(params object[] arg) { var res = new System.Text.StringBuilder(); foreach (var x in arg) { res.AppendFormat(info, "{0}", x); if (!string.IsNullOrEmpty(Separator)) res.Append(Separator); } writer.Write(res.ToString(0, res.Length - Separator.Length)); } static public void Print<T>(IEnumerable<T> sources) { var res = new System.Text.StringBuilder(); foreach (var x in sources) { res.AppendFormat(info, "{0}", x); if (string.IsNullOrEmpty(Separator)) res.Append(Separator); } writer.Write(res.ToString(0, res.Length - Separator.Length)); } static public void PrintLine(int num) { writer.WriteLine(num.ToString(info)); } static public void PrintLine(int num, string format) { writer.WriteLine(num.ToString(format, info)); } static public void PrintLine(long num) { writer.WriteLine(num.ToString(info)); } static public void PrintLine(long num, string format) { writer.WriteLine(num.ToString(format, info)); } static public void PrintLine(double num) { writer.WriteLine(num.ToString(info)); } static public void PrintLine(double num, string format) { writer.WriteLine(num.ToString(format, info)); } static public void PrintLine(string str) { writer.WriteLine(str); } static public void PrintLine(string format, params object[] arg) { writer.WriteLine(format, arg); } static public void PrintLine<T>(string format, IEnumerable<T> sources) { writer.WriteLine(format, sources.OfType<object>().ToArray()); } static public void PrintLine(params object[] arg) { var res = new System.Text.StringBuilder(); foreach (var x in arg) { res.AppendFormat(info, "{0}", x); if (!string.IsNullOrEmpty(Separator)) res.Append(Separator); } writer.WriteLine(res.ToString(0, res.Length - Separator.Length)); } static public void PrintLine<T>(IEnumerable<T> sources) { var res = new System.Text.StringBuilder(); foreach (var x in sources) { res.AppendFormat(info, "{0}", x); if (!string.IsNullOrEmpty(Separator)) res.Append(Separator); } writer.WriteLine(res.ToString(0, res.Length - Separator.Length)); } static public void PrintLine(System.Linq.Expressions.Expression<Func<string, object>> ex) { var res = ex.Parameters[0]; writer.WriteLine(res.Name); } } public class _Scanner { readonly private System.Globalization.CultureInfo info; readonly System.IO.TextReader reader; string[] buffer = new string[0]; int position; public char[] Separator { get; set; } public _Scanner(System.IO.TextReader reader = null, string separator = null, System.Globalization.CultureInfo info = null) { this.reader = reader ?? Console.In; if (string.IsNullOrEmpty(separator)) separator = " "; this.Separator = separator.ToCharArray(); this.info = info ?? System.Globalization.CultureInfo.InvariantCulture; } public string Scan() { if (this.position < this.buffer.Length) return this.buffer[this.position++]; do this.buffer = this.reader.ReadLine().Split(this.Separator, StringSplitOptions.RemoveEmptyEntries); while (this.buffer.Length == 0); this.position = 0; return this.buffer[this.position++]; } public string ScanLine() { if (this.position >= this.buffer.Length) return this.reader.ReadLine(); else { var sb = new System.Text.StringBuilder(); for (; this.position < buffer.Length; this.position++) { sb.Append(this.buffer[this.position]); sb.Append(' '); } return sb.ToString(); } } public string[] ScanArray(int length) { var ar = new string[length]; for (int i = 0; i < length; i++) ar[i] = this.Scan(); return ar; } public int Integer() { return int.Parse(this.Scan(), info); } public long Long() { return long.Parse(this.Scan(), info); } public double Double() { return double.Parse(this.Scan(), info); } public double Double(string str) { return double.Parse(str, info); } public int[] IntArray(int length) { var a = new int[length]; for (int i = 0; i < length; i++) a[i] = this.Integer(); return a; } public long[] LongArray(int length) { var a = new long[length]; for (int i = 0; i < length; i++) a[i] = this.Long(); return a; } public double[] DoubleArray(int length) { var a = new double[length]; for (int i = 0; i < length; i++) a[i] = this.Double(); return a; } } static public partial class EnumerableEx { static public string AsString(this IEnumerable<char> source) { return new string(source.ToArray()); } static public T[] Enumerate<T>(this int n, Func<int, T> selector) { var res = new T[n]; for (int i = 0; i < n; i++) res[i] = selector(i); return res; } } #endregion #region HashMap class HashMap<K, V> : Dictionary<K, V> { new public V this[K i] { get { V v; return TryGetValue(i, out v) ? v : base[i] = default(V); } set { base[i] = value; } } } #endregion
5de8b050a4c7c7b68a045336ed14af9be0f00bce
C#
mattche/ChsuSchedule
/src/ChsuSchedule.Data/Parser/ScheduleParser.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using AngleSharp.Parser.Html; namespace ChsuSchedule.Data.Parser { /// <summary>Парсер расписания.</summary> sealed class ScheduleParser : IScheduleParser { #region IScheduleParser implementation public IEnumerable<StudentClassesScheduleRecord> ParseStundentClassesSchedule(string htmlContent) { var parser = new HtmlParser(); var document = parser.Parse(htmlContent); var rawRecords = document.QuerySelectorAll("tr") .Skip(3) .Where(tr => tr.QuerySelectorAll("td").Count() == 14 && tr.QuerySelectorAll("td").Count(td => td.TextContent != "\n") != 0) .Select(tr => new { Weekday = tr.QuerySelector("td").TextContent.Trim(), Duration = tr.QuerySelectorAll("td") .Skip(1 * 2) .FirstOrDefault() .TextContent.Trim(), Subject = tr.QuerySelectorAll("td") .Skip(2 * 2) .FirstOrDefault() .TextContent.Trim(), Weeks = tr.QuerySelectorAll("td") .Skip(3 * 2) .FirstOrDefault() .TextContent.Trim(), Periodicity = tr.QuerySelectorAll("td") .Skip(4 * 2) .FirstOrDefault() .TextContent.Trim(), Teacher = tr.QuerySelectorAll("td") .Skip(5 * 2) .FirstOrDefault() .TextContent.Trim(), Classroom = tr.QuerySelectorAll("td") .Skip(6 * 2) .FirstOrDefault() .TextContent.Trim() }); var records = new List<StudentClassesScheduleRecord>(); foreach(var rec in rawRecords) { int weeksStart, weeksEnd; ParseWeeks(rec.Weeks, out weeksStart, out weeksEnd); Periodicity periodicity; try { periodicity = ParsePeriodicity(rec.Periodicity); } catch { return null; } DayOfWeek weekday; try { weekday = ParseDayOfWeak(rec.Weekday); } catch { return null; } records.Add(new StudentClassesScheduleRecord { Classroom = rec.Classroom, Duration = rec.Duration, Periodicity = periodicity, Subject = rec.Subject, Teacher = rec.Teacher, Weekday = weekday, WeeksStart = weeksStart, WeeksEnd = weeksEnd }); } return records; } public IEnumerable<TeacherClassesScheduleRecord> ParseTeacherClassesSchedule(string htmlContent) { var parser = new HtmlParser(); var document = parser.Parse(htmlContent); var rawRecords = document.QuerySelectorAll("tr") .Skip(3) .Where(tr => tr.QuerySelectorAll("td").Count() == 14 && tr.QuerySelectorAll("td").Count(td => td.TextContent != "\n") != 0) .Select(tr => new { Weekday = tr.QuerySelector("td").TextContent.Trim(), Duration = tr.QuerySelectorAll("td") .Skip(1 * 2) .FirstOrDefault() .TextContent.Trim(), Subject = tr.QuerySelectorAll("td") .Skip(2 * 2) .FirstOrDefault() .TextContent.Trim(), Weeks = tr.QuerySelectorAll("td") .Skip(3 * 2) .FirstOrDefault() .TextContent.Trim(), Periodicity = tr.QuerySelectorAll("td") .Skip(4 * 2) .FirstOrDefault() .TextContent.Trim(), Group = tr.QuerySelectorAll("td") .Skip(5 * 2) .FirstOrDefault() .TextContent.Trim(), Classroom = tr.QuerySelectorAll("td") .Skip(6 * 2) .FirstOrDefault() .TextContent.Trim() }); var records = new List<TeacherClassesScheduleRecord>(); foreach (var rec in rawRecords) { int weeksStart, weeksEnd; ParseWeeks(rec.Weeks, out weeksStart, out weeksEnd); Periodicity periodicity; try { periodicity = ParsePeriodicity(rec.Periodicity); } catch { return null; } DayOfWeek weekday; try { weekday = ParseDayOfWeak(rec.Weekday); } catch { return null; } records.Add(new TeacherClassesScheduleRecord { Classroom = rec.Classroom, Duration = rec.Duration, Periodicity = periodicity, Subject = rec.Subject, Group = rec.Group, Weekday = weekday, WeeksStart = weeksStart, WeeksEnd = weeksEnd }); } return records; } #endregion #region Methods private void ParseWeeks(string value, out int weeksStart, out int weeksEnd) { var substrings = value.Split(' '); int temp; if (int.TryParse(substrings[1], out temp)) weeksStart = temp; else weeksStart = 0; if (int.TryParse(substrings[3], out temp)) weeksEnd = temp; else weeksEnd = 0; } private Periodicity ParsePeriodicity(string value) { switch (value) { case "чет": return Periodicity.Even; case "нечет": return Periodicity.NotEven; case "ежен": return Periodicity.Weekly; default: throw new ArgumentException("Uncorrect periodicity value", nameof(value)); } } private DayOfWeek ParseDayOfWeak(string value) { switch(value) { case "понедельник": return DayOfWeek.Monday; case "вторник": return DayOfWeek.Tuesday; case "среда": return DayOfWeek.Wednesday; case "четверг": return DayOfWeek.Thursday; case "пятница": return DayOfWeek.Friday; case "суббота": return DayOfWeek.Saturday; case "воскресенье": return DayOfWeek.Sunday; default: throw new ArgumentException("Uncorrect day of weak value", nameof(value)); } } #endregion } }
51f759551286e896441cf2dfbed37681ff69e451
C#
chrispydizzle/coding-challenges
/BinaryTrees/RootLeafPath.cs
3.125
3
namespace CodeChallenges.BinaryTrees { internal class RootLeafPath { public bool HasPathSum(TreeNode root, int sum) { if (root == null) return false; return this.HasPathSum(root, sum, 0); } private bool HasPathSum(TreeNode root, int sum, int running) { if (root == null) return false; running += root.val; if (root.left == null && root.right == null) return sum == running; return this.HasPathSum(root.left, sum, running) || this.HasPathSum(root.right, sum, running); } } }
1648413e4ead56488313a0be5bbe29b39831aa54
C#
shendongnian/download4
/code10/1814157-53442194-186404880-2.cs
2.75
3
var length = 1000; Task.Run(() => { for (int i = 0; i <= length; i++) { Application.Current.Dispatcher.BeginInvoke(new Action(() => { lblMsg.Content = "Test" + i; }), DispatcherPriority.Render); Thread.Sleep(100); } });
6c7f04f2736d40d7725f2843e658c77124cd0c9b
C#
ccandy/SRPPipeline
/Assets/Frameworks/Common/Singleton/SingletonMonoBehaviour.cs
2.65625
3
using UnityEngine; namespace Frameworks.Common { public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour { protected static T mInstance = null; public static T Instance { get { return mInstance; } } public static T Create() { if (mInstance != null) return mInstance; GameObject obj = new GameObject(typeof(T).ToString()); mInstance = obj.AddComponent<T>(); return mInstance; } protected virtual void Awake() { if (mInstance != null) { Destroy(gameObject); return; } DontDestroyOnLoad(gameObject); } } }
0c366fbe75b822dae9860b2b86b3a48a086b4eab
C#
ibtanjeeb/Practice-some-code
/DataTypeIO/DataTypeIO/Program.cs
3.578125
4
using System; namespace DataTypeIO { class Program { static void Main(string[] args) { //(a) Integer int[] arrint = new int[5]; Console.WriteLine("Please enter the integaer elements:"); for (int i = 0; i < arrint.Length; i++) { arrint[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("Print the integaer elements:"); foreach (var elements in arrint) { Console.WriteLine(elements); } //(b) Double double[] arrDouble = new double[5]; Console.WriteLine("Please enter the Double elements:"); for (int i = 0; i < arrDouble.Length; i++) { arrDouble[i] = double.Parse(Console.ReadLine()); } Console.WriteLine("Print the Double elements:"); foreach (var elements in arrDouble) { Console.WriteLine(elements); } //(c) Float float[] arrFloat = new float[5]; Console.WriteLine("Please enter the Float elements:"); for (int i = 0; i < arrFloat.Length; i++) { arrFloat[i] = float.Parse(Console.ReadLine()); } Console.WriteLine("Print the Float elements:"); foreach (var elements in arrFloat) { Console.WriteLine(elements) ; } //(d) String string[] arrString = new string[5]; Console.WriteLine("Please enter the Strings elements:"); for (int i = 0; i < arrString.Length; i++) { arrString[i] = Console.ReadLine(); } Console.WriteLine("Print the Strings elements:"); foreach (var elements in arrString) { Console.WriteLine(elements); } //(e) DateTime DateTime[] arrdatetime = new DateTime[5]; Console.WriteLine("Please enter the DateTime elements:"); for (int i = 0; i < arrdatetime.Length; i++) { arrdatetime[i] =DateTime.Parse( Console.ReadLine()); } Console.WriteLine("Print the DateTime elements:"); foreach (var elements in arrdatetime) { Console.WriteLine(elements); } //(f) Decimal decimal[] arrDecimal = new decimal[5]; Console.WriteLine("Please enter the Decimal elements:"); for (int i = 0; i < arrDecimal.Length; i++) { arrDecimal[i] = decimal.Parse( Console.ReadLine()); } Console.WriteLine("Print the Decimal elements:"); foreach (var elements in arrDecimal) { Console.WriteLine(elements); } //(g) Long long[] arrLong = new long[5]; Console.WriteLine("Please enter the Long elements:"); for (int i = 0; i < arrLong.Length; i++) { arrLong[i] =long.Parse( Console.ReadLine()); } Console.WriteLine("Print the Long elements:"); foreach (var elements in arrLong) { Console.WriteLine(elements); } //(h) Bool bool[] arrBool = new bool[5]; Console.WriteLine("Please enter the Bool elements:"); for (int i = 0; i < arrBool.Length; i++) { arrBool[i] = bool.Parse(Console.ReadLine()); } Console.WriteLine("Print the Bool elements:"); foreach (var elements in arrBool) { Console.WriteLine(elements); } } } }
930962ca661c73e924d30187e389ea818bf27394
C#
maksimkurb/BridgeBotNext
/BridgeBotNext/Attachments/AudioAttachment.cs
2.859375
3
using System.Text; namespace BridgeBotNext.Attachments { public class AudioAttachment : DurationFileAttachment { public AudioAttachment( string url = null, object meta = null, string caption = null, string fileName = null, long fileSize = 0, string mimeType = null, string defaultMimeType = "audio/mpeg", string title = null, string performer = null, ulong? duration = null ) : base(url, meta, caption, fileName, fileSize, duration, mimeType, defaultMimeType) { Title = title; Performer = performer; } public string Title { get; } public string Performer { get; } public override string ToString() { var sb = new StringBuilder(); if (!string.IsNullOrEmpty(Performer)) { sb.Append(Performer); sb.Append(" - "); } sb.Append(!string.IsNullOrEmpty(Title) ? Title : "[audio]"); if (Duration > 5) sb.Append(ReadableDuration()); return sb.ToString(); } } }
579060ce9ef1d03f8c454c716c12d6d4f4f8d306
C#
ThanhThanh2911/Module2
/MVC/StudentMVC/StudentMVC/Models/StudentRepository.cs
3.28125
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; namespace StudentMVC.Models { public class StudentRepository : IStudentRepository { private readonly AppDbContext dbContext; public StudentRepository(AppDbContext dbContext) { this.dbContext = dbContext; } public IEnumerable<Student> GetAll { get{ return dbContext.Students.Include(g => g.Group); } } public Student Add(Student newStudent) { dbContext.Add(newStudent); return newStudent; } public int Commit() { return dbContext.SaveChanges(); } public Student Delete(int id) { var student = GetById(id); if (student != null) { dbContext.Students.Remove(student); } return student; } public Student GetById(int id) { return dbContext.Students.Include(g => g.Group).SingleOrDefault(s => s.StudentId == id); } public IEnumerable<Student> GetStudentByName(string name) { var result = from s in dbContext.Students.Include(g => g.Group) where string.IsNullOrEmpty(name) || s.Name.Contains(name) select s; return result; } public Student Update(Student updateStudent) { var entity = dbContext.Students.Attach(updateStudent); entity.State = EntityState.Modified; return updateStudent; } } }
d9ce3a52346f9f402ebaa6f5b8220cab265ef85f
C#
sapiens/cavemantools
/src/CavemanTools/Extensions/ListUtils.cs
3.59375
4
using System.Linq; namespace System { public static class ListUtils { public static bool IsEqual<T>(this T[] source, T[] other) where T : IEquatable<T> => source.IsEqualTo(other, (i1, i2) => i1.Equals(i2)); public static bool IsEqualTo<T>(this T[] source, T[] other,Func<T,T,bool> equatable) { source.MustNotBeNull(); if (source.Length != other?.Length) return false; for (var i = 0; i < source.Length; i++) { if (!equatable(source[i],other[i])) return false; } return true; } } } namespace System.Collections.Generic { public static class ListUtils { /// <summary> /// Checks if 2 enumerables have the same elements in the same order. Comparison by reference /// </summary> /// <typeparam name="T"></typeparam> /// <param name="first"></param> /// <param name="second"></param> /// <returns></returns> public static bool HasTheSameElementsAs<T>(this IEnumerable<T> first, IEnumerable<T> second) { first.MustNotBeNull(); second.MustNotBeNull(); var cnt1 = first.Count(); if (cnt1 != second.Count()) return false; T? item1 = default(T); T? item2 = default(T); for (int i = 0; i < cnt1; i++) { item1 = first.Skip(i).Take(1).First(); item2 = second.Skip(i).Take(1).First(); if (!(item1?.Equals(item2)??false)) return false; } return true; } /// <summary> /// Compares two sequences and returns the added or removed items. /// </summary> /// <typeparam name="T">Implements IEquatable</typeparam> /// <param name="fresh">Recent sequence</param> /// <param name="old">Older sequence used as base of comparison</param> /// <returns></returns> public static IModifiedSet<T> Diff<T>(this IEnumerable<T> fresh, IEnumerable<T> old) where T : IEquatable<T> { if (fresh == null) throw new ArgumentNullException("fresh"); if (old == null) throw new ArgumentNullException("old"); var mods = new ModifiedSet<T>(); foreach (var item in old) { if (!fresh.Contains(item)) mods.RemovedItem(item); } foreach (var item in fresh) { if (!old.Contains(item)) mods.AddedItem(item); } return mods; } /// <summary> /// Compares two sequences and returns the added or removed items. /// Use this when T doesn't implement IEquatable /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="fresh">Recent sequence</param> /// <param name="old">Older sequence used as base of comparison</param> /// <param name="match">function to check equality</param> /// <returns></returns> public static IModifiedSet<T> Compare<T>(this IEnumerable<T> fresh, IEnumerable<T> old, Func<T, T, bool> match) { if (fresh == null) throw new ArgumentNullException("fresh"); if (old == null) throw new ArgumentNullException("old"); if (match == null) throw new ArgumentNullException("match"); var mods = new ModifiedSet<T>(); foreach (var item in old) { if (!fresh.Any(d => match(d, item))) mods.RemovedItem(item); } foreach (var item in fresh) { if (!old.Any(d => match(d, item))) mods.AddedItem(item); } return mods; } /// <summary> /// Compares two sequences and returns the result. /// This special case method is best used when you have identifiable objects that can change their content/value but not their id. /// </summary> /// <typeparam name="T">Implements IEquatable</typeparam> /// <param name="fresh">Recent sequence</param> /// <param name="old">Older sequence used as base of comparison</param> /// <param name="detectChange">Delegate to determine if the items are identical. /// First parameter is new item, second is the item used as base for comparison</param> /// <returns></returns> public static IModifiedSet<T> WhatChanged<T>(this IEnumerable<T> fresh, IEnumerable<T> old, Func<T, T, bool> detectChange) where T : IEquatable<T> { if (fresh == null) throw new ArgumentNullException("fresh"); if (old == null) throw new ArgumentNullException("old"); if (detectChange == null) throw new ArgumentNullException("detectChange"); var mods = new ModifiedSet<T>(); foreach (var item in old) { if (!fresh.Any(d => d.Equals(item))) mods.RemovedItem(item); } foreach (var item in fresh) { if (!old.Any(d => d.Equals(item))) mods.AddedItem(item); else { var oldItem = old.First(d => d.Equals(item)); if (detectChange(item, oldItem)) { mods.ModifiedItem(oldItem, item); } } } return mods; } /// <summary> /// Updates the old collection with new items, while removing the inexistent. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="old"></param> /// <param name="fresh"></param> /// <returns></returns> public static void Update<T>(this IList<T> old, IEnumerable<T> fresh) where T : IEquatable<T> { if (old == null) throw new ArgumentNullException("old"); if (fresh == null) throw new ArgumentNullException("fresh"); var diff = fresh.Diff(old); foreach (var item in diff.Removed) { old.Remove(item); } foreach (var item in diff.Added) { old.Add(item); } } /// <summary> /// Updates the old collection with new items, while removing the inexistent. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="old"></param> /// <param name="fresh"></param> /// <returns></returns> public static void Update<T>(this IList<T> old, IEnumerable<T> fresh, Func<T, T, bool> isEqual) { if (old == null) throw new ArgumentNullException("old"); if (fresh == null) throw new ArgumentNullException("fresh"); var diff = fresh.Compare(old, isEqual); foreach (var item in diff.Removed) { var i = old.Where(d => isEqual(d, item)).Select((d, idx) => idx).First(); old.RemoveAt(i); } foreach (var item in diff.Added) { old.Add(item); } } /// <summary> /// Checks if a collection is null or empty duh! /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="items">collection</param> /// <returns></returns> public static bool IsNullOrEmpty<T>(this IEnumerable<T> items) { return items == null || !items.Any(); } public static bool HasItems<T>(this IEnumerable<T> items) { return !items.IsNullOrEmpty(); } /// <summary> /// Gets typed value from dictionary or a default value if key is missing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dic"></param> /// <param name="key"></param> /// <param name="defValue">Value to return if dictionary doesn't contain the key</param> /// <returns></returns> public static T GetValue<T>(this IDictionary<string, object> dic, string key, T defValue = default(T)) { if (dic.ContainsKey(key)) return (T) dic[key]; return defValue; } public static bool AddIfNotPresent<T>(this IList<T> list, T item) { list.MustNotBeNull(); if (!list.Contains(item)) { list.Add(item); return true; } return false; } public static void AddIfNotPresent<T>(this IList<T> list, IEnumerable<T> items) { foreach (var item in items) { AddIfNotPresent(list, item); } } /// <summary> /// Removes all items matched by predicate /// Returns number of items removed /// </summary> /// <param name="dic"></param> /// <param name="predicate"></param> /// <typeparam name="K"></typeparam> /// <typeparam name="V"></typeparam> /// <returns></returns> public static int RemoveAll<K, V>(this IDictionary<K, V> dic, Func<KeyValuePair<K, V>, bool> predicate) { predicate.MustNotBeNull(); dic.MustNotBeNull(); var keys = dic.TakeWhile(predicate).ToArray(); foreach (var kv in keys) dic.Remove(kv); return keys.Length; } /// <summary> /// Returns number of items removed /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static int RemoveAll<T>(this IList<T> items, Func<T, bool> predicate) { items.MustNotBeEmpty(); predicate.MustNotBeNull(); var removed = 0; for (int i = items.Count - 1; i >= 0; i--) { if (predicate(items[i])) { items.RemoveAt(i); removed++; } } return removed; } /// <summary> /// If there is no value for the key, it creates one, adds it to the dictionary, then returns it /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="V"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <param name="factory"></param> /// <returns></returns> public static V GetValueOrCreate<T, V>(this IDictionary<T, V> dict, T key, Func<V> factory) { V? val = default(V); if (!dict.TryGetValue(key, out val)) { val = factory(); dict[key] = val; } return val; } /// <summary> /// Creates an empty enumerable if null /// </summary> /// <typeparam name="T"></typeparam> /// <param name="src"></param> /// <returns></returns> public static IEnumerable<T> ToEmptyIfNull<T>(this IEnumerable<T> src) { return src ?? Enumerable.Empty<T>(); } public static void AddRange<T>(this IDictionary<int, T> dic, IEnumerable<T> items,int startPos=0) { var i = startPos; foreach (var item in items) { dic[i] = item; i++; } } } }
68325617e78af86f2dca388ed94fe5ed8ce26c85
C#
mmoroney/Algorithms
/Problems/BinarySearchTrees/SatisfiesBST.cs
3.15625
3
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Algorithms.DataStructures; using Utilities; namespace Problems.BinarySearchTrees { // EOPI 15.1 [TestClass] public class SatisfiesBST { [TestMethod] public void SatisfiesBSTTest() { Func<BinaryTreeNode<int>, bool>[] functions = new Func<BinaryTreeNode<int>, bool>[] { SatisfiesBST.BruteForce, SatisfiesBST.Recursive, SatisfiesBST.InOrderTraversal, SatisfiesBST.Queue }; for (int i = 0; i < 10; i++) { int[] data = ArrayUtilities.CreateRandomArray(10, 0, 20); BinaryTreeNode<int> root = new BinaryTreeNode<int>(data[0]); for(int j = 1; j < data.Length; j++) { BinarySearchTree.Insert(root, data[j]); Tests.TestFunctions(root, functions); } root = new BinaryTreeNode<int>(data[0]); for (int j = 1; j < data.Length; j++) { BinaryTreeUtilities.AddRandomNode(root, data[j]); Tests.TestFunctions(root, functions); } } } private static bool BruteForce(BinaryTreeNode<int> root) { if (root == null) return true; foreach (BinaryTreeNode<int> node in BinaryTree.InOrderTraversal(root.Left)) { if (node.Data > root.Data) return false; } foreach (BinaryTreeNode<int> node in BinaryTree.InOrderTraversal(root.Right)) { if (node.Data < root.Data) return false; } return SatisfiesBST.BruteForce(root.Left) && SatisfiesBST.BruteForce(root.Right); } private static bool Recursive(BinaryTreeNode<int> root) { return SatisfiesBST.Recursive(root, int.MinValue, int.MaxValue); } private static bool Recursive(BinaryTreeNode<int> root, int minValue = int.MinValue, int maxValue = int.MaxValue) { if (root == null) return true; if (root.Data < minValue || root.Data > maxValue) return false; return SatisfiesBST.Recursive(root.Left, minValue, root.Data) && SatisfiesBST.Recursive(root.Right, root.Data, maxValue); } private static bool InOrderTraversal(BinaryTreeNode<int> root) { int previous = int.MinValue; foreach(BinaryTreeNode<int> node in BinaryTree.InOrderTraversal(root)) { if (node.Data < previous) return false; previous = node.Data; } return true; } private static bool Queue(BinaryTreeNode<int> root) { Queue<Range> queue = new Queue<Range>(); queue.Enqueue(new Range { Node = root, Min = int.MinValue, Max = int.MaxValue }); while(queue.Count != 0) { Range range = queue.Dequeue(); int data = range.Node.Data; if (data > range.Max || data < range.Min) return false; if (range.Node.Left != null) queue.Enqueue(new Range { Node = range.Node.Left, Min = range.Min, Max = data }); if (range.Node.Right != null) queue.Enqueue(new Range { Node = range.Node.Right, Min = data, Max = range.Max }); } return true; } private class Range { public BinaryTreeNode<int> Node { get; set; } public int Min { get; set; } public int Max { get; set; } } } }
de13b3e3c817bc7a2d14a61b779f121508e1dd63
C#
rgoncalves95/taskerAI
/TaskerAI.Api/Models/Mappers/PlanMapper.cs
2.671875
3
namespace TaskerAI.Api.Mapper { using System.Collections.Generic; using System.Linq; using TaskerAI.Api.Models; using TaskerAI.Common; using TaskerAI.Domain; public class PlanMapper : IMapper<Plan, PlanModel> { public void Map(Plan from, PlanModel to) { } public PlanModel Map(Plan from) { var to = new PlanModel(); Map(from, to); return to; } public void Map(IEnumerable<Plan> from, IEnumerable<PlanModel> to) => to = from.Select(f => Map(f)).ToArray(); public IEnumerable<PlanModel> Map(IEnumerable<Plan> from) => from.Select(f => Map(f)).ToArray(); } }
57db7ec1118b4db4e4d37e083e7ebf35594ffbb1
C#
Cundalf/Stalhvik
/Assets/Scripts/Misc/Loot.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Loot : MonoBehaviour { public Vector3 offset; public GameObject lootPrefab; [Range(0f, 1f)] public float probability; public bool loot() { if(Random.value > 1 - probability) { Instantiate(lootPrefab, transform.position + offset, transform.rotation); return true; } return false; } }
2455e666440591a4f73d7c1efc6b2a5ba88f877a
C#
kraskoo/SoftUni-v3.0
/Data-Structures/Linear-DS-Lists-And-Complexity-Homework/P06ImplementTheDataStructureReversedList(T)/EntryPoint.cs
3.421875
3
namespace P06ImplementTheDataStructureReversedList_T_ { using System; public class EntryPoint { public static void Main() { ReversedList<int> reversedInts = new ReversedList<int>(); reversedInts.Add(3); reversedInts.Add(-34532); reversedInts.Add(78); reversedInts.Add(111); PrintReversedList(reversedInts); Console.WriteLine(); reversedInts.RemoveAt(2); PrintReversedList(reversedInts); } private static void PrintReversedList(ReversedList<int> reversedInts) { for (int i = 0; i < reversedInts.Count; i++) { Console.WriteLine(reversedInts[i]); } } } }
3c345f63531c13bd3aacbcc40bfa0784808759b6
C#
DonVo2020/DonVo2020.DataStructuresAlgorithms
/DonVo2020.DataStructuresAlgorithms.MVC/Controllers/UndirectedDenseGraphController.cs
3.0625
3
using System.Linq; using Microsoft.AspNetCore.Mvc; using DonVo2020.DataStrutures.NetCore31.Graphs; using Microsoft.AspNetCore.Html; using DonVo2020.DataStrutures.NetCore31.StringHelpers; namespace DonVo2020.DataStructuresAlgorithms.MVC.Controllers { public class UndirectedDenseGraphController : Controller { // GET: /<controller>/ public IActionResult Index() { string result = string.Empty; var graph = new UndirectedDenseGraph<string>(); var verticesSet1 = new string[] { "a", "z", "s", "x", "d", "c", "f", "v" }; graph.AddVertices(verticesSet1); graph.AddEdge("a", "s"); graph.AddEdge("a", "z"); graph.AddEdge("s", "x"); graph.AddEdge("x", "d"); graph.AddEdge("x", "c"); graph.AddEdge("d", "f"); graph.AddEdge("d", "c"); graph.AddEdge("c", "f"); graph.AddEdge("c", "v"); graph.AddEdge("v", "f"); var allEdges = graph.Edges.ToList(); // TEST REMOVE nodes v and f graph.RemoveVertex("v"); graph.RemoveVertex("f"); // TEST RE-ADD REMOVED NODES AND EDGES graph.AddVertex("v"); graph.AddVertex("f"); graph.AddEdge("d", "f"); graph.AddEdge("c", "f"); graph.AddEdge("c", "v"); graph.AddEdge("v", "f"); result = ("[*] Undirected Dense Graph: " + "\n\n") + "Graph nodes and edges: \n" + (graph.ToReadable() + "\n\n"); // RE-TEST REMOVE AND ADD NODES AND EDGES graph.RemoveEdge("d", "c"); graph.RemoveEdge("c", "v"); graph.RemoveEdge("a", "z"); result = result + "After removing edges (d-c), (c-v), (a-z):" + "\n"; result = result + graph.ToReadable() + "\n\n"; graph.RemoveVertex("x"); result = result + "After removing node(x):" + "\n"; result = result + graph.ToReadable() + "\n\n"; graph.AddVertex("x"); graph.AddEdge("s", "x"); graph.AddEdge("x", "d"); graph.AddEdge("x", "c"); graph.AddEdge("d", "c"); graph.AddEdge("c", "v"); graph.AddEdge("a", "z"); result = result + "Re-added the deleted vertices and edges to the graph." + "\n"; result = result + graph.ToReadable() + "\n\n"; // BFS result = result + "Walk the graph using BFS:" + "\n"; graph.BreadthFirstWalk("s"); result = result + "output: (s) (a) (x) (z) (d) (c) (f) (v)." + "\n"; result = result + "\n\n"; result = result + "***************************************************\r\n"; graph.Clear(); result = result + "Cleared the graph from all vertices and edges.\r\n"; var verticesSet2 = new string[] { "a", "b", "c", "d", "e", "f" }; result = result + "Vertices Set 2: " + "a, b, c, d, e, f" + "\n\n"; graph.AddVertices(verticesSet2); graph.AddEdge("a", "b"); graph.AddEdge("a", "d"); graph.AddEdge("b", "e"); graph.AddEdge("d", "b"); graph.AddEdge("d", "e"); graph.AddEdge("e", "c"); graph.AddEdge("c", "f"); graph.AddEdge("f", "f"); result = result + "[*] NEW Undirected Dense Graph: " + "\n"; result = result + "Graph nodes and edges:\n"; result = result + "graph.ToReadable()" + "\n\n"; result = result + "Walk the graph using DFS:\n"; graph.DepthFirstWalk(); result = result + "output: (a) (b) (e) (d) (c) (f)\n"; HtmlString html = StringHelper.GetHtmlString(result); return View(html); } } }
160e76489d0b07adf27436fc5cc1c51fb37823a2
C#
hsg77/ArcMapByCommon
/ArcMapByCommon/SelectionEx/NetColorSelection.cs
2.796875
3
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; namespace ArcMapByCommon { /// <summary> /// .Net颜色选择 管理类 /// </summary> public class NetColorSelection { private ColorDialog m_dialog = null; public NetColorSelection() { this.m_dialog = new ColorDialog(); InitializeUI(); } private void InitializeUI() { } public bool IsColorSelected() { return m_dialog.ShowDialog() == DialogResult.OK; } public System.Drawing.Color NetColor { get { return this.m_dialog.Color; } } } /// <summary> /// 颜色模板 选择 管理类 /// </summary> public class ColorPalette { private ColorDialog _colorDialog; public ColorPalette() { _colorDialog = new ColorDialog(); InitializeUI(); SetDefaultColor(); } private void InitializeUI() { _colorDialog.FullOpen = true; } private void SetDefaultColor() { _colorDialog.Color = Color.Yellow; } public bool IsColorSelected() { return _colorDialog.ShowDialog() == DialogResult.OK; } public int Red { get { return (int)_colorDialog.Color.R; } } public int Green { get { return (int)_colorDialog.Color.G; } } public int Blue { get { return (int)_colorDialog.Color.B; } } } }
3667016cc50d89bfb3cb2ccc1d00ccdecd3145bc
C#
stanley-yang/ActivityPlanner
/Models/ActivityCenter.cs
2.609375
3
using System.ComponentModel.DataAnnotations; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace ActivityCenter.Models { public class Activity { // auto-implemented properties need to match the columns in your table // the [Key] attribute is used to mark the Model property being used for your table's Primary Key [Key] public int ActivityId { get; set; } // MySQL VARCHAR and TEXT types can be represeted by a string [Required(ErrorMessage="{0} is required.")] [Display(Name = "Activity")] public string Event { get; set; } // [MinLength(2, ErrorMessage = "Person One requires at least 2 characters.")] [Display(Name = "hoursmins")] public string hoursmins { get; set; } [Required(ErrorMessage="{0} is required.")] // [DataType(DataType.Time)] // [DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)] // [MinLength(2, ErrorMessage = "Person Two requires at least 2 characters.")] [Display(Name = "Duration")] public int Duration { get; set; } [Required(ErrorMessage="{0} are required.")] [Display(Name = "Date")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] // [RestrictedDate(ErrorMessage="Date must be in the future")] public DateTime Datetime { get; set; } [Required(ErrorMessage="{0} are required.")] [Display(Name = "Time")] [DataType(DataType.Time)] [DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)] // [RestrictedDate(ErrorMessage="Time must be in the future")] public TimeSpan time { get; set; } [Required(ErrorMessage="{0} are required.")] [Display(Name = "DateTime")] [DataType(DataType.DateTime)] [DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)] // [RestrictedDate(ErrorMessage="Time must be in the future")] public TimeSpan realdatetime { get; set; } [Required(ErrorMessage="{0} is required.")] public string Description { get; set; } // The MySQL DATETIME type can be represented by a DateTime public DateTime CreatedAt {get;set;} = DateTime.Now; public DateTime UpdatedAt {get;set;} = DateTime.Now; public int UserId {get; set;} public User Planner {get; set;} public List<Rsvp> Rsvps {get; set;} } }
fc4fc04efc633997b2130018b1d1b636c6395855
C#
Aekaraman/HR-Management
/HRManagement/HRManagement.Data/Repositories/Concrete/UpcomingPaymentRep.cs
2.640625
3
using HRManagement.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; namespace HRManagement.Data.Repositories.Concrete { public class UpcomingPaymentRep { private static UpcomingPaymentRep paymentsFactory = null; private HttpClient client; public static UpcomingPaymentRep PaymentRep { get { if (paymentsFactory == null) { paymentsFactory = new UpcomingPaymentRep(); } return paymentsFactory; } } private UpcomingPaymentRep() { client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:61860/"); } public HttpResponseMessage GetUpComingPayments(out IEnumerable<Personel> upcomingPayments) { var responseTask = client.GetAsync("api/personel/YaklasanOdemeBilgileri"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { //sonuçtan gelen veriyi çekiyoruz var readTask = result.Content.ReadAsAsync<IList<Personel>>(); readTask.Wait(); //geri dönecek olan listeyi yüklüyoruz upcomingPayments = readTask.Result; return result; } else { upcomingPayments = Enumerable.Empty<Personel>(); return result; } } } }
ae6a0740a15c04162b7cb02d2c3f3d2188922283
C#
mendesbarreto/BSRescue
/Assets/Scripts/Player/InputController.cs
2.765625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public sealed class InputController : MonoBehaviour { private bool pressKeyToPlay; [SerializeField] private bool isKeyboard; public bool PressKeyToPlay { get { return pressKeyToPlay; } set { pressKeyToPlay = value; } } private const string KEY_KEYBOARD = "space"; private const float ZERO_TOUCH = 0; private float amountTouch; private void Update() { amountTouch = Input.touches.Length; ChooseConsole(); } // Choose keyboard or touch private void ChooseConsole() { if(!isKeyboard) { CheckTouch(); } else { pressKeyToPlay = Input.GetKey(KEY_KEYBOARD); } } private void CheckTouch() { if(amountTouch > ZERO_TOUCH) { pressKeyToPlay = true; } else { pressKeyToPlay = false; } } }
07b6c812bf7511fb1498b84d44a51ccf2eb03d47
C#
LilitHakobyan/MicHomeworks
/Blocknote/Blocknote/Record.cs
3.296875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blocknote { class Record { public string Name { get; set; } public string Phone { get; set; } public Record(string name, string phons) { this.Name = name; this.Phone = phons; } public override bool Equals(object obj) { Record rec = obj as Record; if (rec != null) return (rec.Name == this.Name && rec.Phone == this.Phone); return false; } public override int GetHashCode() { return 13*Name.GetHashCode()+13*Phone.GetHashCode(); } public override string ToString() { return $"Name: {Name}_______Phon: {Phone}"; } } }
c2d346e98bab6373790dd6e2036eccbf2af51536
C#
roxannekhouani/Programmation-Csharp
/Simulation de news/WindowsFormsApp1/Factory.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp1 { delegate void Handler<T>(T t); class Factory <T> where T :chap, new() { private List<T> maListe = new List<T>(); public event Handler<T> OnAdd; public event Handler<T> OnDelete; public void createElement(string name) { T t = new T(); t.Name = name; AjoutElement(t); } void AjoutElement(T t) { maListe.Add(t); if (OnAdd != null) { OnAdd(t); } } public void SuppElement(T t) { maListe.Remove(t); if (OnDelete !=null) { OnDelete(t); } } } }
734fd82aa91bead74c45f53ff68a8f33d5467939
C#
matrizzza/RandomMathExercise
/RandomMathExercise/MainWindow.xaml.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; 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.Navigation; using System.Windows.Shapes; namespace RandomMathExercise { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { private int num1, num2, num3, result; private Random random; public MainWindow() { InitializeComponent(); CommandBinding binding = new CommandBinding(ApplicationCommands.New); binding.Executed += BindingOnExecuted; this.CommandBindings.Add(binding); SetNumbers(out num1, out num2, out num3); SetExerciseToTextBlock(); } private void BindingOnExecuted(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) { SetNumbers(out num1, out num2, out num3); SetExerciseToTextBlock(); CongratsTextBlock.Visibility = Visibility.Hidden; ResultTextBox.Background = Brushes.BurlyWood; ResultTextBox.Text = String.Empty; } private void SetNumbers(out int n1, out int n2, out int n3) { random = new Random(); n1 = random.Next(1, 50); Thread.Sleep(20); random = new Random(); n2 = random.Next(1, 8); Thread.Sleep(20); random = new Random(); n3 = random.Next(1, 101); } private bool CheckResultFromExercise(int n1, int n2, int n3) { int result; if (Int32.TryParse(ResultTextBox.Text, out result)) { if (result == n1 * n2 + n3) return true; } return false; } private void SetExerciseToTextBlock() { ExerciseTextBlock.Text = $"({num1} * {num2}) + {num3} ="; } private void CheckButton_OnClick(object sender, RoutedEventArgs e) { if (CheckResultFromExercise(num1, num2, num3)) { ResultTextBox.Background = Brushes.ForestGreen; CongratsTextBlock.Text = "You did a great job!"; CongratsTextBlock.Visibility = Visibility.Visible; } else { ResultTextBox.Background = Brushes.Brown; CongratsTextBlock.Text = "Try again!"; CongratsTextBlock.Visibility = Visibility.Visible; } } private void ResultTextBox_OnGotFocus(object sender, RoutedEventArgs e) { if (sender != null) ((TextBox) sender).Background = Brushes.BurlyWood; CongratsTextBlock.Visibility = Visibility.Hidden; } private void MainWindow_OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) CheckButton_OnClick(sender, e); } } }
4811039787462b10f25b8313db69809593eee9d5
C#
RiadRepo/Cs-basic
/text replace.cs
2.984375
3
string sayHello = "Hello World!"; Console.WriteLine(sayHello); // Hello World! sayHello = sayHello.Replace("Hello", "Greetings"); Console.WriteLine(sayHello); // Greetings World!
0d200254ffc2cdfe601ef510c21527ef757486e2
C#
cr7pt0gr4ph7/pic-simulator
/PicSim.UI/Helper/ObservableSet.cs
2.953125
3
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using PicSim.Utils; namespace PicSim.UI.Helper { public class ObservableSet<T> : ISet<T>, INotifyCollectionChanged { private readonly ISet<T> m_underlyingSet; public ObservableSet() { m_underlyingSet = new HashSet<T>(); } #region ISet<T> Methods public bool Add(T item) { if (!m_underlyingSet.Add(item)) return false; RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); return true; } public void ExceptWith(IEnumerable<T> other) { foreach (var elem in other) Remove(elem); } public void IntersectWith(IEnumerable<T> other) { foreach (var notPresent in m_underlyingSet.Except(other).ToList()) Remove(notPresent); } public void SymmetricExceptWith(IEnumerable<T> other) { foreach (var elem in other) if (!Remove(elem)) Add(elem); } public void UnionWith(IEnumerable<T> other) { foreach (var elem in other) Add(elem); } public bool IsProperSubsetOf(IEnumerable<T> other) { return m_underlyingSet.IsProperSubsetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { return m_underlyingSet.IsProperSupersetOf(other); } public bool IsSubsetOf(IEnumerable<T> other) { return m_underlyingSet.IsSubsetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { return m_underlyingSet.IsSupersetOf(other); } public bool Overlaps(IEnumerable<T> other) { return m_underlyingSet.SetEquals(other); } public bool SetEquals(IEnumerable<T> other) { return m_underlyingSet.SetEquals(other); } #endregion #region ICollection<T> Methods void ICollection<T>.Add(T item) { this.Add(item); } public void Clear() { m_underlyingSet.Clear(); RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public bool Contains(T item) { return m_underlyingSet.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { m_underlyingSet.CopyTo(array, arrayIndex); } public int Count { get { return m_underlyingSet.Count; } } public bool IsReadOnly { get { return m_underlyingSet.IsReadOnly; } } public bool Remove(T item) { if (!m_underlyingSet.Remove(item)) return false; RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item)); return true; } #endregion #region IEnumerable<T> Methods public IEnumerator<T> GetEnumerator() { return m_underlyingSet.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region INotifyCollectionChanged Methods private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e) { var handler = CollectionChanged; if (handler != null) { handler(this, e); } } public event NotifyCollectionChangedEventHandler CollectionChanged; #endregion } }
935268573e85e2807125dfdf96037496b1a96053
C#
CarlFredrikAhl/SinusSkateboards
/SinusSkateboards/Models/Product.cs
2.78125
3
using System; using System.ComponentModel.DataAnnotations; namespace SinusSkateboards.Models { public class Product { [Key] public int ProductId { get; set; } //Primary key public int? OrderId { get; set; } //Foreign key public string Image { get; set; } public string Title { get; set; } public string Description { get; set; } public string Color { get; set; } public int Price { get; set; } public Product() { } public Product(string img, string title, string desc, string color, int price) { Image = img; Title = title; Description = desc; Color = color; Price = price; } } }
980097d27ceac7d73c40d80e171206b8cbada894
C#
lopes-felipe/Loja
/Solution/LojaVerity.Servicos/Entidades/Produto.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace LojaVerity.Servicos.Entidades { [DataContract(Namespace = "http://servicos.verity.com/1.0/Entidades")] public class Produto { public Produto() { } public Produto(long id, string nome, string descricao, decimal preco) { this.ID = id; this.Nome = nome; this.Descricao = descricao; this.Preco = preco; } public Produto(LojaVerity.Entidades.Produto produto) { if (produto == null) return; this.ID = produto.ID; this.Nome = produto.Nome; this.Descricao = produto.Descricao; this.Preco = produto.Preco; } [DataMember] public long ID { get; set; } [DataMember] public string Nome { get; set; } [DataMember] public string Descricao { get; set; } [DataMember] public decimal Preco { get; set; } } }
9772d323206fb8e162a6c6960413f7b1ddb71a47
C#
gstamac/AllGreen
/src/AllGreen.Core/JsMapFile.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace AllGreen.Core { public class JsMapFile { public int Version { get; set; } public string OutputFile { get; set; } public string[] SourceFiles { get; set; } public string[] Names { get; set; } public IEnumerable<JsMappingSegment> Mappings { get; set; } public static JsMapFile CreateFromString(string content) { try { JObject jObject = JObject.Parse(content); JsMapFile mapFile = new JsMapFile { Version = (int)jObject.SelectToken("version"), OutputFile = (string)jObject.SelectToken("file"), SourceFiles = ((JArray)jObject.GetValue("sources")).Select(jt => (string)jt).ToArray(), Names = ((JArray)jObject.GetValue("names")).Select(jt => (string)jt).ToArray() }; mapFile.Mappings = ParseMappings(mapFile, (string)jObject.SelectToken("mappings")); return mapFile; } catch { } return null; } private static IEnumerable<JsMappingSegment> ParseMappings(JsMapFile jsMapFile, string mappings) { int currentLine = 1; int previousSourceIndex = 0; int previousSourceStartingLine = 1; int previousSourceStartingColumn = 1; int previousSourceNameIndex = 0; foreach (string mappingLine in mappings.Split(';')) { if (!String.IsNullOrEmpty(mappingLine)) { int previousGeneratedColumn = 1; foreach (string segment in mappingLine.Split(',')) { int[] map = VLQDecode(segment); JsMappingSegment mapping = new JsMappingSegment { GeneratedLine = currentLine, GeneratedColumn = previousGeneratedColumn + map[0] }; if (map.Length > 1) { previousSourceIndex += map[1]; mapping.Source = jsMapFile.SourceFiles[previousSourceIndex]; previousSourceStartingLine += map[2]; mapping.SourceStartingLine = previousSourceStartingLine; previousSourceStartingColumn += map[3]; mapping.SourceStartingColumn = previousSourceStartingColumn; if (map.Length > 4) { previousSourceNameIndex += map[4]; mapping.SourceName = jsMapFile.Names[previousSourceNameIndex]; } } yield return mapping; previousGeneratedColumn = mapping.GeneratedColumn; } } currentLine++; } } private static int[] VLQDecode(string base64String) { List<int> res = new List<int>(); int value = 0; int shift = 0; foreach (char vlqChar in base64String) { byte digit = FromBase64Char(vlqChar); bool cont = (digit & 0x20) == 0x20; digit &= 0x1F; value = value + (digit << shift); shift += 5; if (!cont) { value = ((value & 1) == 1) ? -(value >> 1) : (value >> 1); res.Add(value); shift = 0; value = 0; } } if (shift > 0) throw new FormatException("Expected more digits in base 64 VLQ value."); if (res.Count != 1 && res.Count != 4 && res.Count != 5) throw new FormatException("Expected 1, 4 or 5 values in base 64 VLQ."); return res.ToArray(); } private static byte FromBase64Char(char c) { return (byte)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".IndexOf(c); } } public class JsMappingSegment { public int GeneratedLine { get; set; } public int GeneratedColumn { get; set; } public string Source { get; set; } public int SourceStartingLine { get; set; } public int SourceStartingColumn { get; set; } public string SourceName { get; set; } public override string ToString() { return String.Format("{5} in {2}:{3}:{4} => {0}:{1}", GeneratedLine, GeneratedColumn, Source, SourceStartingLine, SourceStartingColumn, SourceName).Trim(); } } }
8eaaebe1fc5d01efbac2f74706fd2212de26ed88
C#
the6th/UnityNativePlugin-Template
/UnitySample/Assets/Scripts/DebugLogToText.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DebugLogToText : MonoBehaviour { [SerializeField] Text logText; [SerializeField] TextMesh logTextMesh; private const int LOG_MAX = 20; private Queue<string> logStack = new Queue<string>(LOG_MAX); // Use this for initialization void Start() { Application.logMessageReceived += LogCallback; // ログが書き出された時のコールバック設定 Debug.LogWarning("DebugLogToText:start"); // テストでワーニングログをコール } // Update is called once per frame void Update() { if (this.logStack == null || this.logStack.Count == 0) return; string s = null; foreach (string log in logStack) { s += log; } if (logText) logText.text = s; if (logTextMesh) logTextMesh.text = s; } private void OnDestroy() { Application.logMessageReceived -= LogCallback; // } /// <summary> /// ログを取得するコールバック /// </summary> /// <param name="condition">メッセージ</param> /// <param name="stackTrace">コールスタック</param> /// <param name="type">ログの種類</param> public void LogCallback(string condition, string stackTrace, LogType type) { // 通常ログまで表示すると邪魔なので無視 //if (type == LogType.Log) // return; string trace = null; string color = null; switch (type) { case LogType.Log: //case LogType.Warning: // UnityEngine.Debug.XXXの冗長な情報をとる trace = stackTrace.Remove(0, (stackTrace.IndexOf("\n") + 1)); color = "white"; break; case LogType.Warning: trace = stackTrace.Remove(0, (stackTrace.IndexOf("\n") + 1)); color = "aqua"; break; case LogType.Error: case LogType.Assert: // UnityEngine.Debug.XXXの冗長な情報をとる trace = stackTrace.Remove(0, (stackTrace.IndexOf("\n") + 1)); color = "red"; break; case LogType.Exception: trace = stackTrace; color = "red"; break; } // ログの行制限 if (this.logStack.Count == LOG_MAX) this.logStack.Dequeue(); string message = string.Format("<color={0}>{1}</color>\r\n", color, condition, ""/*trace*/); this.logStack.Enqueue(message); } }
6aacc176f0eaee8b1c8fc18947c5a26aae3fd1ce
C#
harshdave71720/ShoppingCartRepo
/ShoppingCartSolution/ShoppingCartSystem/ItemManager.cs
2.734375
3
using ShoppingCartDataLayer.Repositories; using ShoppingCartLibrary; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShoppingCartSystem { public class ItemManager : ShoppingSystemManager { public ItemManager(IDataSource dataSource) : base(dataSource) { } public Item AddItem(Item item) { return DataSource.Items.Add(item); } public Item GetItem(Guid id) { return DataSource.Items.Find(new Item { Id = id }); } public Item UpdateItem(Item item) { return DataSource.Items.Update(item); } public Item RemoveItem(Guid id) { return DataSource.Items.Remove(new Item { Id = id }); } public CartItem AddItemToCart(Guid userId, Guid itemId, int Qunatity) { var user = DataSource.Users.Find(new User { Id = userId }); //temporary user check if (user == null) { return null; } //permanent code var item = DataSource.Items.Find(new Item { Id = itemId }); if (item == null) { return null; } int quantity = user.GetActiveCart().Add(item, Qunatity); DataSource.SaveChanges(); return new CartItem() { Item = item, ItemId = item.Id, Quantity = Qunatity }; } public List<Item> GetItems() { return DataSource.Items.GetAll().ToList(); } } }
d1c36f991876cdab5fc75da8a7ab27b5d16d54b2
C#
c-rblake/OOP2
/Bird.cs
3.234375
3
namespace OOP2 { public class Bird : Animal { private bool hasFeathers; public bool HasFeathers{ get; set; } public Bird(string name, double weight, int age, bool hasFeathers) : base(name, weight, age) { this.HasFeathers = hasFeathers; } public override string DoSound() { return "Squak, Shriiik"; } } }
d61b366a1c79bebed52691155e3060272c7aeccf
C#
rushidaoy/CoffeeShop
/CoffeeShopSimulation/CoffeeShopSimulation/CoffeeShopSimulation/SimulationModel.cs
2.859375
3
// Author: Mark Voong // Class Name: SimulationModel.cs // Date Created: Dec 5th 2015 // Date Modified: Dec 6th 2015 // Description: Handles all simulation logic of the coffee shop using System; using Microsoft.Xna.Framework; namespace CoffeeShopSimulation { class SimulationModel { private InputManager inputManager = new InputManager(); // Controller Class private Queue<Vector2> waypoints; // Locations that allow the customer to follow a certain path /// <summary> /// Queue that stores every customer that has entered the store /// </summary> public Queue<CustomerModel> Customers { get; private set; } private const int MAX_CUSTOMERS = 16; // Maximum number of customers inside the store public int CustomersInStore = 0; // Number of customers inside the store private int numCustomers = 0; // Number of customers that have visited the store CustomerModel[] cashiers = new CustomerModel[4]; // Cashiers which serve the customers private float simTime; // Total time the simulation has run private float respawnTimer; // Timer used to delay time between customer spawning private const float SPAWN_TIME = 6.0f; // Time in seconds between each customer attempting to enter the store private const float SIM_DURATION = 300.0f; // Time in seconds for how long the simulation should run private Random rand = new Random(); // Used to determine what type of customer to generate /// <summary> /// Stores all statistics that are tracked during the simulation /// </summary> public Statistics Statistics { get; private set; } /// <summary> /// Returns whether or not the simulation is paused /// </summary> public bool Paused { get; private set; } /// <summary> /// Returns a rounded version of the current simulation time /// </summary> public float SimTime { get { return (float)Math.Round(simTime, 2); } private set { simTime = value; } } public void Initialize() { Customers = new Queue<CustomerModel>(); // Initialize Waypoints } public void Update(float gameTime) { if (!Paused) { // Advance simulation time SimTime += gameTime; // Advance respawn timer respawnTimer += gameTime; // If the required amount of time has passed to spawn another customer if (respawnTimer >= SPAWN_TIME) { // Restart the respawn timer CustomersInStore++; CustomerModel.CustomerType customerType; int randType = rand.Next(0, 2); switch (randType) { case 0: customerType = CustomerModel.CustomerType.Coffee; break; case 1: customerType = CustomerModel.CustomerType.Food; break; case 2: customerType = CustomerModel.CustomerType.Both; break; default: customerType = CustomerModel.CustomerType.Coffee; break; } Customers.Enqueue(new Node<CustomerModel>(CustomersInStore, new CustomerModel(waypoints, customerType, numCustomers))); } // Get the next customer in the queue Node<CustomerModel> curCustomer = Customers.Peek(); // Update each customer for (int i = 0; i < Customers.Size; i++) { curCustomer.Value.Update(gameTime); switch (curCustomer.Value.CurrentState) { case CustomerModel.CustomerState.Outside: break; case CustomerModel.CustomerState.InLine: break; case CustomerModel.CustomerState.AtCashier: break; case CustomerModel.CustomerState.ExitStore: // If the customer has made it to the final waypoint if (curCustomer.Value.Waypoints.Size == 1 && curCustomer.Value.Postion == curCustomer.Value.Waypoints.Peek().Value) { // Dequeue the current customer Customers.Dequeue(); } break; } curCustomer = curCustomer.GetNext(); } } } } }
423c3a28de5f48280af5f99f944cafce189decfb
C#
nixonjoshua98/miner-maze-game
/Unity/MinerMazeGame/Assets/Scripts/Player/Modules/PlayerMining.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class PlayerMining : MonoBehaviour { public GameObject mineRoot; public GameObject floorTile; public GameObject wallTile; public Text blockCountTxt; private int blockCount = 0; public void Awake() { blockCountTxt.text = "BLOCKS LEFT: " + blockCount; } public void Mine() { GameObject tile = null; if (GetTile(ref tile)) { TileHealth tileHP = tile.GetComponent<TileHealth>(); tileHP.TakeDamage(Time.deltaTime); if (tileHP.IsDestroyed()) { blockCount++; Instantiate(floorTile, tile.transform.position, Quaternion.identity, mineRoot.transform); Destroy(tile); blockCountTxt.text = "BLOCKS LEFT: " + blockCount; } } } public void PlaceBlock() { if (blockCount == 0) return; Vector3 pos = Vector3.zero; if (GetTilePlacementPos(ref pos)) { RaycastHit2D hit = Physics2D.Raycast(transform.position + pos, Vector3.forward, 1, LayerMask.GetMask("FloorTiles")); Debug.DrawLine(transform.position, transform.position + pos); if (hit.collider && hit.collider.CompareTag("FloorTile")) { blockCount--; Instantiate(wallTile, hit.collider.gameObject.transform.position, Quaternion.identity, mineRoot.transform); Destroy(hit.collider.gameObject); blockCountTxt.text = "BLOCKS LEFT: " + blockCount; } } } private bool GetTile(ref GameObject tile) { List<Vector3> directions = new List<Vector3>() { Vector3.up, Vector3.right, Vector3.down, Vector3.left, }; GameObject breakTile; foreach (Vector3 v in directions) { RaycastHit2D hit = Physics2D.Raycast(transform.position, v, 1, LayerMask.GetMask("BreakableTiles")); Debug.DrawLine(transform.position, transform.position + v); if (hit.collider && hit.collider.CompareTag("BreakTile")) { tile = hit.collider.gameObject; return true; } } return false; } private bool GetTilePlacementPos(ref Vector3 pos) { KeyCode[] keys = { KeyCode.LeftArrow, KeyCode.RightArrow, KeyCode.UpArrow, KeyCode.DownArrow }; foreach (KeyCode k in keys) { if (Input.GetKeyDown(k)) { Vector3 dir = Vector3.zero; switch (k) { case KeyCode.LeftArrow: dir = Vector3.left; break; case KeyCode.RightArrow: dir = Vector3.right; break; case KeyCode.UpArrow: dir = Vector3.up; break; case KeyCode.DownArrow: dir = Vector3.down; break; } pos = dir; return true; } } return false; } }
edb28d0a250c53a35b28cfe626cafdc33815eb75
C#
vioan12/Verificarea-si-Testarea-Sistemelor-de-Calcul
/Homework5/Lab1/QuadraticEquation.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab1 { public class QuadraticEquation { //ax^2 + bx + c = 0 public Coefficients Coefficients { private set; get; } public double Delta { get { EmpiricalTestingConsole.Write(new string[2] { "public double Delta", "get" }); return (double)(Math.Pow(Coefficients.B, 2) - 4 * Coefficients.A * Coefficients.C); } } public QuadraticEquation (Coefficients coefficients) { EmpiricalTestingConsole.Write(new string[1] { "public QuadraticEquation (Coefficients coefficients)" }); EmpiricalTestingConsole.Write(new string[1] { "coefficients=" + coefficients.ToString() }); EmpiricalTestingConsole.Write(new string[3] { "A=" + coefficients.A, "B=" + coefficients.B, "C=" + coefficients.C }); if (coefficients != null) { EmpiricalTestingConsole.Write(new string[1] { "if (coefficients != null)" }); Coefficients = coefficients; EmpiricalTestingConsole.Write(new string[1] { "Coefficients = coefficients" }); EmpiricalTestingConsole.Write(new string[1] { "Coefficients=" + Coefficients.ToString() }); EmpiricalTestingConsole.Write(new string[3] { "A=" + Coefficients.A, "B=" + Coefficients.B, "C=" + Coefficients.C }); } else { EmpiricalTestingConsole.Write(new string[1] { "else" }); throw new Exception("'coefficients' cannot be null"); } } public Solution SolveWithRealSolutions() { EmpiricalTestingConsole.Write(new string[1] { "public Solution SolveWithRealSolutions()" }); Solution solution = null; EmpiricalTestingConsole.Write(new string[1] { "Solution solution = null" }); if (Delta.Equals(0)) { EmpiricalTestingConsole.Write(new string[1] { "if (Delta.Equals(0))" }); solution = new Solution( (double)(-Coefficients.B) / (double)(2 * Coefficients.A), (double)(-Coefficients.B) / (double)(2 * Coefficients.A) ); EmpiricalTestingConsole.Write(new string[4] { "solution = new Solution(", "(double)(-Coefficients.B) / (double)(2 * Coefficients.A),", "(double)(-Coefficients.B) / (double)(2 * Coefficients.A)", ")" }); EmpiricalTestingConsole.Write(new string[1] { "solution=" + solution.ToString() }); EmpiricalTestingConsole.Write(new string[2] { "solution.Root1=" + solution.Root1.ToString(), "solution.Root2=" + solution.Root2.ToString() }); } if (Delta > 0) { EmpiricalTestingConsole.Write(new string[1] { " if(Delta > 0)" }); solution = new Solution( (double)(-Coefficients.B + Math.Sqrt(Delta)) / (double)(2 * Coefficients.A), (double)(-Coefficients.B - Math.Sqrt(Delta)) / (double)(2 * Coefficients.A) ); EmpiricalTestingConsole.Write(new string[4] { "solution = new Solution(", "(double)(-Coefficients.B + Math.Sqrt(Delta)) / (double)(2 * Coefficients.A),", "(double)(-Coefficients.B - Math.Sqrt(Delta)) / (double)(2 * Coefficients.A)", ")" }); EmpiricalTestingConsole.Write(new string[1] { "solution=" + solution.ToString() }); EmpiricalTestingConsole.Write(new string[2] { "solution.Root1=" + solution.Root1.ToString(), "solution.Root2=" + solution.Root2.ToString() }); } if (Delta < 0) { EmpiricalTestingConsole.Write(new string[1] { " if (Delta < 0)" }); throw new Exception("the equation do not have a real solution"); } return solution; } } }
8f2ccc19b644e00e337c1bfe33f16a3958b07760
C#
zenithplatform/Core
/src/Zenith.Core.Models/VirtualObservatory/Objects/ObjectModel.cs
2.546875
3
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zenith.Core.Models.VirtualObservatory.Objects { public class CelestialObject { List<DataItemBase> _objectData = null; public CelestialObject() { _objectData = new List<DataItemBase>(); } [JsonProperty("object_data")] public List<DataItemBase> ObjectData { get { return _objectData; } set { _objectData = value; } } } public class ValueBase { [JsonProperty("value")] public object Value { get; set; } } public class ComplexValue : ValueBase { [JsonProperty("unit")] public string Unit { get; set; } [JsonProperty("error")] public object Error { get; set; } public override string ToString() { string ret = ""; ret += " " + this.Value + this.Unit; return ret; } } public class DataItemBase { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("kind")] public string Kind { get; set; } [JsonProperty("values")] public List<ValueBase> Values { get; set; } } public class SimpleItem : DataItemBase { } public class ComplexItem : DataItemBase { } public class CompositeItem : DataItemBase { } public class MultiItem : DataItemBase { } public class MultiComplexItem : DataItemBase { } }
acc035865e3ed9c8c20957b7a97a30adb0ffa9c0
C#
avalanchus/GooglePhotoSync
/GooglePhotoSyncLib/PhotoSync.cs
2.921875
3
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; namespace GooglePhotoSyncLib { public class PhotoSync { private readonly Configuration _configuration; /// <summary> /// Секунды (1000 миллисекунд) /// </summary> // ReSharper disable once InconsistentNaming private const int sec = 1000; /// <summary> /// Таймер для задания периода сканирования каталога /// </summary> private Timer _timer; /// <summary> /// Получение в указанной папке файлы с указанным расширением /// </summary> /// <param name="folder"> Папка из которой получаем файлы </param> /// <param name="extension"> Расширение, по которому получаем файлы </param> /// <returns> Список файлов </returns> private List<string> GetFiles(string folder, string extension) { var files = Directory.EnumerateFiles(folder, $"*.{extension}", SearchOption.TopDirectoryOnly).ToList(); return files; } /// <summary> /// Список каталого с картинками (жипег и пр) , исключаемые при построения дерева в директории-приёмнике /// </summary> public List<string> Exclusions; /// <summary> /// Список расширений для создания жёсткой ссылки в папке-приёмнике /// </summary> public List<string> Extensions; /// <summary> /// Период проверки каталога /// </summary> public int Period; /// <summary> /// Папка-источник /// </summary> public string SourceFolder; /// <summary> /// Папка-приёмник /// </summary> public string DestFolder; /// <summary> /// Создание жёсткой ссылки /// https://stackoverflow.com/questions/3387690/how-to-create-a-hardlink-in-c /// </summary> /// <param name="lpFileName"> Имя файла-ссылки </param> /// <param name="lpExistingFileName"> Имя файла-источника </param> /// <param name="lpSecurityAttributes"></param> /// <returns> Успешность создания ссылки </returns> [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] private static extern bool CreateHardLink( string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); /// <summary> /// Получить доступ к общему файлу конфигурации для всех сборок /// </summary> /// <returns></returns> public static Configuration GetConfiguration() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (assemblyFolder != null) map.ExeConfigFilename = Path.Combine(assemblyFolder, "Config.file"); Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); return config; } /// <summary> /// Сканирование директории источника и постороение аналогичной иерархии папок в директории-приёмнике. /// Проверка на соответствие файлов в источнике и приёмнике. Если есть различия - создаются жёсткие ссылки /// </summary> /// <param name="sourcePath"> Полный путь к папке-источнику </param> /// <param name="destPath"> Полный путь к папке-приёмнику </param> public void SyncFoldersTree(string sourcePath, string destPath) { string slash = "\\"; // Считывание из настроек списка папок ислючённых из построение дерева Exclusions = _configuration.AppSettings.Settings[nameof(Exclusions)].Value.Split(';').ToList(); // Считываение из настроек расширений, для которых создаются жёсткие ссылки Extensions = _configuration.AppSettings.Settings[nameof(Extensions)].Value.Split(';').ToList(); var subFolders = Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories) .Where(d => !Exclusions.Exists(e => e == Path.GetFileName(d))) .ToList(); // Добавляем слеш в конец папки-приёмника, если отсутствует if (destPath.Substring(destPath.Length - 1) == slash) destPath = destPath.Substring(0, destPath.Length - 1); Exclusions.Add(String.Empty); foreach (var sourceSubFolder in subFolders) { // Относительный путь в папке-источнике var subPath = sourceSubFolder.Substring(sourcePath.Length); // Путь к папке-приёмнику var destSubFolder = destPath + subPath; // Создание папки (если не существует) Directory.CreateDirectory(destSubFolder); foreach (var exclusion in Exclusions) { var sourceJpgFolder = Path.Combine(sourceSubFolder, exclusion); if (Directory.Exists(sourceJpgFolder)) { foreach (var extension in Extensions) { var sourceFiles = GetFiles(sourceJpgFolder, extension); if (sourceFiles.Count > 0) { var destFiles = GetFiles(destSubFolder, extension); var missingFiles = sourceFiles.Except(destFiles).ToList(); // Создание ссылки на файл foreach (var missingFile in missingFiles) { var missingFileName = Path.GetFileName(missingFile); if (missingFileName != null) { var newFileName = Path.Combine(destSubFolder, missingFileName); CreateHardLink(newFileName, missingFile, IntPtr.Zero); } } } } } } } } /// <summary> /// Начало сканирования каталога на наличие изменений /// </summary> public void StartChecking() { SourceFolder = _configuration.AppSettings.Settings[nameof(SourceFolder)].Value; DestFolder = _configuration.AppSettings.Settings[nameof(DestFolder)].Value; TimerCallback timerCallback = state => { SyncFoldersTree(SourceFolder, DestFolder); }; Period = 0; var period = _configuration.AppSettings.Settings[nameof(Period)].Value; Int32.TryParse(period, out Period); // создаем таймер _timer = new Timer(timerCallback, null, 0, Period * sec); } /// <summary> /// Окончание сканирования каталога /// </summary> public void StopChecking() { _timer.Dispose(); } public PhotoSync() { _configuration = GetConfiguration(); } } }
f876410f94d9a485de22d41bd6e358bd5fa9c496
C#
ChrisConnell1/Tech-Academy-Projects
/VisualStudio/ChallengeHeroMonsterClassesPt1/ChallengeHeroMonsterClassesPt1/Default.aspx.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ChallengeHeroMonsterClassesPt1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Character Hero = new Character(); Character Monster = new Character(); Hero.Name = "Hiro"; Hero.Health = 100; Hero.DamageMaximum = 25; Hero.AttackBonus = true; Monster.Name = "Gort"; Monster.Health = 85; Monster.DamageMaximum = 20; Monster.AttackBonus = false; Dice dice = new Dice(); while (Hero.Health > 0 && Monster.Health > 0) { int monsterDamage = Monster.Attack(dice); int heroRemainingHealth = Hero.Defend(monsterDamage); resultLabel.Text += String.Format("{0} attacks {1} for {2} damage, leaving him with {3} health!<br /><br />", Monster.Name, Hero.Name, monsterDamage, heroRemainingHealth); int heroDamage = Hero.Attack(dice); int monsterRemainingHealth = Monster.Defend(heroDamage); resultLabel.Text += String.Format("Battle continues, {0} strikes {1} for {2} damage, leaving him with {3} health!<br /><br />", Hero.Name, Monster.Name, heroDamage, monsterRemainingHealth); } displayResult(Hero, Monster); } public void displayResult(Character opponenent1, Character opponent2) { if (opponenent1.Health > 0 && opponent2.Health < 0) resultLabel.Text += String.Format("The winner is {0} having vanquished {1}!", opponenent1.Name, opponent2.Name); else if (opponent2.Health > 0 && opponenent1.Health < 0) resultLabel.Text += String.Format("The winner is {0} having vanquished {1}", opponent2.Name, opponenent1.Name); else resultLabel.Text += "They both died!"; } public class Character { public string Name { get; set; } public int Health { get; set; } public int DamageMaximum { get; set; } public bool AttackBonus { get; set; } public int Attack(Dice dice) { dice.Sides = this.DamageMaximum; int inflictedDamage = dice.Roll(); return inflictedDamage; } public int Defend(int inflictedDamage) { this.Health -= inflictedDamage; return Health; } } public class Dice { Random random = new Random(); public int Sides { get; set; } public int Roll() { int roll = random.Next(1, Sides); return roll; } } } }
67aeb0d9af0cd6ca748061e9cfd8520efdbfb9ab
C#
mayureshkrishna/dotnetCustomerAccount
/Cox.BusinessLogic/ExceptionFormatter.cs
2.984375
3
using System; using System.Collections; using Cox.Validation; namespace Cox.BusinessLogic { /// <summary> /// Summary description for ExceptionFormatter. /// </summary> public class ExceptionFormatter { #region constants /// <summary> /// header for message to be returned. /// </summary> private const string __header="The following errors occurred:\r\n"; #endregion constants #region member variables /// <summary> /// Exception we are formatting. /// </summary> protected Exception _exception=null; /// <summary> /// The formatter. /// </summary> protected IValidatorFormatProvider _formatProvider=null; #endregion member variables #region ctors /// <summary> /// The default constructor. /// </summary> /// <param name="exception"></param> public ExceptionFormatter(Exception exception) { _exception=exception; MultiItemFormatProvider provider=new MultiItemFormatProvider(); provider.HeaderText=__header; _formatProvider=(IValidatorFormatProvider)provider; } /// <summary> /// Constructor taking a different format provider. /// </summary> /// <param name="exception"></param> /// <param name="formatProvider"></param> public ExceptionFormatter(Exception exception,IValidatorFormatProvider formatProvider) { _exception=exception; _formatProvider=formatProvider; } #endregion ctors #region methods /// <summary> /// Workhorse of class. This methods performs the actual formatting /// of the exception information. /// </summary> /// <returns></returns> public string Format() { ArrayList arrList=new ArrayList(); Exception exc=_exception; while(exc!=null) { arrList.Add(exc.Message); exc=exc.InnerException; } return _formatProvider.Format(arrList); } #endregion methods } }
67c76786460d3ad2c0a90e553ea74d2605409dd8
C#
psotirov/TelerikAcademyProjects
/Web Services/Homework 2 - WCF/WCFStringCompare/StringCount.cs
3.015625
3
using System; namespace WCFStringCompare { public class StringCount : IStringCount { public int GetSubstringCount(string input, string substring) { int count = 0; int startIndex = input.IndexOf(substring); while (startIndex >= 0) { count++; startIndex = input.IndexOf(substring, startIndex + 1); } return count; } } }
67b0648f012ae936d137f86bab355680684fca9c
C#
Kjelloo/PetShop
/CrashCourse.PetShop.Infrastructure.Data/Repositories/PetTypeRepository.cs
2.890625
3
using System.Collections.Generic; using System.Linq; using CrashCourse.PetShop.Core.IRepositories; using CrashCourse.PetShop.Core.Models; using CrashCourse.PetShop.Infrastructure.Data.Entities; namespace CrashCourse.PetShop.Infrastructure.Data.Repositories { public class PetTypeRepository : IPetTypeRepository { private readonly PetShopContext _ctx; public PetTypeRepository(PetShopContext ctx) { _ctx = ctx; } public PetType Create(PetType createPetType) { var entity = new PetTypeEntity { Name = createPetType.Name }; var savedEntity = _ctx.PetTypes.Add(entity).Entity; _ctx.SaveChanges(); return new PetType { Id = savedEntity.Id, Name = savedEntity.Name }; } public PetType GetById(int id) { return _ctx.PetTypes .Select(pt => new PetType { Id = pt.Id, Name = pt.Name }) .FirstOrDefault(type => type.Id == id); } public IEnumerable<PetType> GetAll() { return _ctx.PetTypes .Select(p => new PetType { Id = p.Id, Name = p.Name }).ToList(); } public PetType Update(PetType updatePetType) { var entity = new PetTypeEntity { Id = updatePetType.Id, Name = updatePetType.Name }; var savedEntity = _ctx.PetTypes.Update(entity).Entity; _ctx.SaveChanges(); return new PetType { Id = savedEntity.Id, Name = savedEntity.Name }; } public PetType Delete(int id) { var petTypeDeleted = _ctx.PetTypes.Remove(new PetTypeEntity() {Id = id}); _ctx.SaveChanges(); return new PetType { Id = petTypeDeleted.Entity.Id, Name = petTypeDeleted.Entity.Name }; } } }
a446598aa62dfb87adfed87193dcdb6c025eee2c
C#
kaoandrew/GetUsGrub
/CSULB.GetUsGrub/CSULB.GetUsGrub.BusinessLogic/Strategies/ValidationStrategies/CreateRestaurantPreLogicValidationStrategy.cs
2.734375
3
using CSULB.GetUsGrub.Models; using System.Collections.Generic; namespace CSULB.GetUsGrub.BusinessLogic { /// <summary> /// The <c>CreateRestaurantPreLogicValidationStrategy</c> class. /// Defines a strategy for validating models before processing business logic for creating a restaurant. /// <para> /// @author: Jennifer Nguyen /// @updated: 03/20/2018 /// </para> /// </summary> public class CreateRestaurantPreLogicValidationStrategy { private readonly RegisterRestaurantDto _registerRestaurantDto; private readonly BusinessHourDtoValidator _businessHourDtoValidator; private readonly BusinessHourValidator _businessHourValidator; private readonly RestaurantDetailValidator _restaurantDetailValidator; public CreateRestaurantPreLogicValidationStrategy(RegisterRestaurantDto registerRestaurantDto) { _registerRestaurantDto = registerRestaurantDto; _businessHourDtoValidator = new BusinessHourDtoValidator(); _businessHourValidator = new BusinessHourValidator(); _restaurantDetailValidator = new RestaurantDetailValidator(); } /// <summary> /// The ExecuteStrategy method. /// Contains the logic to validate a data transfer object for creating a restaurant user. /// <para> /// @author: Jennifer Nguyen /// @updated: 03/20/2018 /// </para> /// </summary> /// <returns>ResponseDto</returns> public ResponseDto<bool> ExecuteStrategy() { ResponseDto<bool> result; var validationWrappers = new List<IValidationWrapper>() { new ValidationWrapper<RestaurantProfileDto>(_registerRestaurantDto.RestaurantProfileDto, "CreateUser", new RestaurantProfileDtoValidator()), new ValidationWrapper<Address>(_registerRestaurantDto.RestaurantProfileDto.Address, "CreateUser", new AddressValidator()), new ValidationWrapper<RestaurantDetail>(_registerRestaurantDto.RestaurantProfileDto.Details, "CreateUser", _restaurantDetailValidator) }; foreach (var businessHourDto in _registerRestaurantDto.BusinessHourDtos) { validationWrappers.Add(new ValidationWrapper<BusinessHourDto>(businessHourDto, "CreateUser", _businessHourDtoValidator)); } foreach (var validationWrapper in validationWrappers) { result = validationWrapper.ExecuteValidator(); if (!result.Data) { return result; } } // Validate BusinessHour foreach (var businessHourDto in _registerRestaurantDto.BusinessHourDtos) { result = _businessHourDtoValidator.CheckIfDayIsDayOfWeek(businessHourDto.Day); if (!result.Data) { result.Error = "Day must be either Sunday, Monday, Tuesday, Wednesday, Thursday, Friday or Saturday."; return result; } result = _businessHourDtoValidator.CheckIfOpenTimeIsBeforeCloseTime(businessHourDto.OpenTime, businessHourDto.CloseTime); if (!result.Data) { result.Error = "Opening time must be less than closing time."; return result; } } result = _restaurantDetailValidator.CheckIfFoodTypeIsRestaurantFoodType(_registerRestaurantDto.RestaurantProfileDto.Details.FoodType); if (!result.Data) { result.Error = "Food type must be a valid restaurant food type."; return result; } return new ResponseDto<bool>() { Data = true }; } } }
9fcb7cf1382469404d004a09f339fb450f6f5af0
C#
juliavav/CG
/LabsCG/LabsCG/Helpers/StringToDoubleConverter.cs
3
3
namespace LabsCG.Helpers { using System; using System.Globalization; using System.Windows.Data; public class StringToDoubleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var v = value as double? ?? 0d; return v; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var stringValue = value as string; if (string.IsNullOrEmpty(stringValue)) return 0d; return !double.TryParse(stringValue, out var amount) ? 0d : amount; } } }
4826a56750741c0648edc79d0dfe1c0d2da07f01
C#
XiaoXiangJianKe/DesignPattern
/06-BuilderPattern/CharacterSystem/FemanHeroBuilder.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuilderPattern.CharacterSystem { class FemanHeroBuilder : CharacterBuilder { private Character character = new Character(); public override void BuilderId() { character.Id = 20001; } public override void BuilderName() { character.Name = "貂蝉"; } public override void BuilderType() { character.Type = "舞姬"; } public override void BuilderSex() { character.Sex = "女"; } public override Character GetCharacter() { return character; } } }
25bfa3c6c22b1b5c046023c1db6f8c8af4a0c46a
C#
PranikNikose/C-Sharp
/w3resource.com/Basic Exercise/Exercise20.cs
3.484375
3
using System; namespace skd { public class Exercise20 { public static void Main() { Console.WriteLine("Sum :{0}", Abosolute(13,40)); Console.WriteLine("Sum :{0}", Abosolute(50, 21)); Console.WriteLine("Sum :{0}", Abosolute(0, 23)); } public static int Abosolute(int FN, int SN) { if (FN>SN) { return (FN - SN)*2; } return (FN - SN); } } }
310ac9cd5561196221da175842b755c88a34f242
C#
lar-dragon/tweak
/TaskTemp.cs
2.71875
3
using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Tweak { public class TaskTemp: ITask { private readonly IEnumerable<FileInfo> _files; public ulong Weight { get; } public bool ClearTemp { get; set; } public bool ClearCache { get; set; } public TaskTemp() { _files = Program .GetDirectoryInfo(EnumKnownDirectories.Temp) .EnumerateFiles("*", SearchOption.AllDirectories); Weight = _files .Aggregate<FileInfo, ulong>(0, (current, fileInfo) => current + (ulong) fileInfo.Length); } public void Apply() { if (ClearTemp) foreach (var file in _files) file.Delete(); if (ClearCache) new Process { EnableRaisingEvents = false, StartInfo = { FileName = "rundll32.exe", Arguments = "InetCpl.cpl,ClearMyTracksByProcess 8", WindowStyle = ProcessWindowStyle.Hidden, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true } }.Start(); } public override string ToString() { return "Обслуживание врекменных файлов"; } } }
8aaa983909e18971d389232799b8857023b4ae82
C#
nirzaf/ProfessionalCSharp2021
/2_Libs/LoggingAndMetrics/MetricsSample/NetworkService.cs
2.78125
3
using Microsoft.Extensions.Logging; using System; using System.Net.Http; using System.Threading.Tasks; namespace MetricsSample { class NetworkService { private readonly ILogger<NetworkService> _logger; private readonly HttpClient _httpClient; public NetworkService( HttpClient httpClient, ILogger<NetworkService> logger) { _httpClient = httpClient; _logger = logger; _logger.LogTrace("ILogger injected into {0}", nameof(NetworkService)); } public async Task NetworkRequestSampleAsync(Uri requestUri) { var stopWatch = MetricsSampleSource.Log.RequestStart(); try { _logger.LogInformation(LoggingEvents.Networking, "NetworkRequestSampleAsync started with uri {0}", requestUri.AbsoluteUri); string result = await _httpClient.GetStringAsync(requestUri); MetricsSampleSource.Log.RequestStop(stopWatch); Console.WriteLine($"{result[..50]}"); _logger.LogInformation(LoggingEvents.Networking, "NetworkRequestSampleAsync completed, received {0} characters", result.Length); } catch (HttpRequestException ex) { _logger.LogError(LoggingEvents.Networking, ex, "Error in NetworkRequestSampleAsync, error message: {0}, HResult: {1}", ex.Message, ex.HResult); MetricsSampleSource.Log.Error(); } finally { MetricsSampleSource.Log.RequestStop(stopWatch); } } } }
bc6a4f82e813dd3fc7c5e3478ee0de1968ed5042
C#
omg3011/Human-Jam
/Human Jam/Assets/PlayerMovement/PlayerMovement.cs
2.5625
3
using UnityEngine; public class PlayerMovement : MonoBehaviour { public Rigidbody rb; //acceleration speed(TESTING ONLY TO SEE THE SIMULATION, WILL CLEAN UP BEFORE SUBMITTING) public float ForwardSpeed = 400f; //LEFT RIGHT turn speed... will trial and error to make it more realistic public float LRSpeed = 800f; public float rotateSpeed = 3.0F; //rotation of x,y,z to look like player is making a turn... float rotx = 60f; float roty = 40f; float rotz = 10f; float minRotationX = -45, maxRotationX = 45; float currentAngle; float MaxForce = 500f; float rotationX, rotationY; // Update is called once per frame void FixedUpdate() { //Debug.Log(transform.eulerAngles.y); // left direction which is also input key 'A' if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { //transform in this case to rotate the player to turn left to be more realistic transform.Rotate(rotx * Time.deltaTime, 0, 0); rb.AddForce(-LRSpeed * Time.deltaTime, 0, 0); transform.Rotate(0, -roty * Time.deltaTime, 0); } // right direction which is also input key 'D' if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { //transform in this case to rotate the player to turn right to be more realistic transform.Rotate(-rotx * Time.deltaTime, 0, 0); rb.AddForce(LRSpeed * Time.deltaTime, 0, 0); transform.Rotate(0, roty * Time.deltaTime, 0); } // Up direction which is also input key 'W' if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) { rb.AddForce(0, 0, ForwardSpeed * Time.deltaTime); } // deceleration(TESTING ONLY TO SEE THE SIMULATION, WILL CLEAN UP BEFORE SUBMITTING) // direction which is also input key 'S' if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) { rb.AddForce(0, 0, -ForwardSpeed * Time.deltaTime); } } // collision for between player and enemy void OnCollisionEnter(Collision col) { // if tagged is Enemy, then it will get the rigidbody component if (col.collider.tag == "Enemy") { Rigidbody enemyRB = col.gameObject.GetComponent<Rigidbody>(); if (enemyRB) { // formula for calculating the collision between player and enemy. mat140... Vector3 dir = (enemyRB.transform.position - transform.position).normalized; enemyRB.AddForce(dir * 50, ForceMode.Impulse); } } } }
f1964b6cc26c5067d0e22c011fa39c055282ab8c
C#
ShmukaDuk/GeneralSkills
/StoreTxt.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; public class StoreTxt : MonoBehaviour { public static void WriteUser(string text) { string path = Application.persistentDataPath + "/user.txt"; //Write some text to the test.txt file StreamWriter writer = new StreamWriter(path, true); writer.WriteLine(text); writer.Close(); StreamReader reader = new StreamReader(path); Debug.Log(reader.ReadToEnd()); reader.Close(); } public static void ReadString() { string path = Application.persistentDataPath + "/test.txt"; //Read the text from directly from the test.txt file StreamReader reader = new StreamReader(path); Debug.Log(reader.ReadToEnd()); reader.Close(); } }
df9000ceffc3dca5ea5837eda61b1df5b3dd26c7
C#
BrendowLincoln/DIO.GamesApi
/ApiCaatalogoJogos/InputModel/GameInputModel.cs
2.734375
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace ApiCaatalogoJogos.InputModel { public class GameInputModel { [Required] [StringLength(100, MinimumLength = 3, ErrorMessage = "O nome do jogo deve conter entre 3 a 100 caracteres")] public string Name { get; set; } [Required] [StringLength(100, MinimumLength = 2, ErrorMessage = "O nome da produtora do jogo deve conter entre 2 a 100 caracteres")] public string Producer { get; set; } [Required] [Range(1,1000, ErrorMessage = "O preço do jogo deve estar entre no mínimo 1 real e no máximo 1000 reais")] public double Price { get; set; } } }
77d41c12212574e604885ab7ad944eaba2ca188d
C#
cedi-code/VertexProject
/ch04_HelloVertex_Net/Cube.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ch03_HelloCube_Net { /// <summary> /// creates a 3D Cube out of a Mesh /// </summary> class Cube : Mesh { private float size = 1.0f; private SLVec3f[] vectors; private SLVec3f front, back, left, right, top, bottom; /// <summary> /// creates new Cube /// 24 vertices /// 36 indices /// </summary> /// <param name="size">length of the lines</param> public Cube(float size) : base(24,36) { vectors = new SLVec3f[8]; vectors[0] = new SLVec3f(-1f, -1f, 1f); // front lower left vectors[1] = new SLVec3f( 1f, -1f, 1f); // front lower right vectors[2] = new SLVec3f( 1f, 1f, 1f); // front upper right vectors[3] = new SLVec3f(-1f, 1f, 1f); // front upper left vectors[4] = new SLVec3f(-1f, -1f, -1f); // back lower left vectors[5] = new SLVec3f( 1f, -1f, -1f); // back lower right vectors[6] = new SLVec3f( 1f, 1f, -1f); // back upper left vectors[7] = new SLVec3f(-1f, 1f, -1f); // back upper right front = new SLVec3f(0, 0, 1); back = new SLVec3f(0, 0, -1); left = new SLVec3f(-1, 0, 0); right = new SLVec3f(1, 0, 0); top = new SLVec3f(0, 1, 0); bottom = new SLVec3f(0, -1, 0); modelMatrix.Scale(size,size,size); build(); } public override void build() { #region setUpVertices int ii = 0; vertices[ii++] = new SLVertex(vectors[0], front, color); vertices[ii++] = new SLVertex(vectors[1], front, color); vertices[ii++] = new SLVertex(vectors[2], front, color); vertices[ii++] = new SLVertex(vectors[3], front, color); vertices[ii++] = new SLVertex(vectors[3], left, color); vertices[ii++] = new SLVertex(vectors[7], left, color); vertices[ii++] = new SLVertex(vectors[4], left, color); vertices[ii++] = new SLVertex(vectors[0], left, color); vertices[ii++] = new SLVertex(vectors[7], back, color); vertices[ii++] = new SLVertex(vectors[6], back, color); vertices[ii++] = new SLVertex(vectors[5], back, color); vertices[ii++] = new SLVertex(vectors[4], back, color); vertices[ii++] = new SLVertex(vectors[1], right, color); vertices[ii++] = new SLVertex(vectors[5], right, color); vertices[ii++] = new SLVertex(vectors[6], right, color); vertices[ii++] = new SLVertex(vectors[2], right, color); vertices[ii++] = new SLVertex(vectors[2], top, color); vertices[ii++] = new SLVertex(vectors[6], top, color); vertices[ii++] = new SLVertex(vectors[7], top, color); vertices[ii++] = new SLVertex(vectors[3], top, color); vertices[ii++] = new SLVertex(vectors[0], bottom, color); vertices[ii++] = new SLVertex(vectors[4], bottom, color); vertices[ii++] = new SLVertex(vectors[5], bottom, color); vertices[ii++] = new SLVertex(vectors[1], bottom, color); #endregion #region setUpIndices int start = 0; int up = 1; for (int i = 0; i < 36; i += 6) { for (int s = 0; s < 4; s += 3) { for (int d = 1; d < 3; d++) { indices[i + s + d] = up; up++; } up--; indices[i + s] = start; } start += 4; up = start + 1; } #endregion } /// <summary> /// change size of cube /// </summary> /// <param name="s">new size</param> public void setSize(float s) { this.size = s; modelMatrix.Scale(size, size, size); } } }
a2e30628079e07aab378de2d8173ed61f4db8e8a
C#
asazonova/Randomchaos-MonoGame-Samples
/RandomchaosMGBase/BaseClasses/PostProcessing/PostProcess/RadialBlur.cs
2.609375
3
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace RandomchaosMGBase.BaseClasses.PostProcessing { public class RadialBlur : BasePostProcess { public float Scale; public RadialBlur(Game game, float scale) : base(game) { Scale = scale; } public override void Draw(GameTime gameTime) { if (effect == null) effect = Game.Content.Load<Effect>("Shaders/PostProcessing/RadialBlur"); effect.Parameters["radialBlurScaleFactor"].SetValue(Scale); effect.Parameters["windowSize"].SetValue(new Vector2(BackBuffer.Height, BackBuffer.Width)); // Set Params. base.Draw(gameTime); } } }
2b751edcb20348818d3ae453eee8ef7b45e0325a
C#
duospeak/IdentityService
/src/Domain/Check.cs
3
3
 namespace System { public static class Check { public static T NotNull<T>(this T obj, string parameterName) where T : class { if (obj.IsNull()) { NotNull(parameterName, nameof(parameterName)); throw new ArgumentNullException(parameterName); } return obj; } public static bool IsNull<T>(this T obj) where T : class => obj is null; } }
292a5051f9fe5a1571459f453367ec70b6ef79ab
C#
OliviaDenbuW/Desktop
/Nackademin år1/Färdiga kurser/C#/Lösningar Jan/kap01/ex1-9.cs
3.234375
3
using System; class Nastlade { static void Main () { Console.Write("Antal rader? "); string s = Console.ReadLine(); int n = int.Parse(s); for (int i=n; i>0; i=i-1) { for (int j=1; j<=i; j=j+1) Console.Write('+'); Console.WriteLine(); } } }
08b95dc1ac02ed6d41ffa47d5c5225c84d262f2b
C#
shendongnian/download4
/code10/1864390-55468970-194910746-2.cs
2.984375
3
public void WithReadLock(Action action) { var lockAcquired = false; try { try { } finally { _Lock.EnterReadLock(); lockAcquired = true; } action(); } finally { if (lockAcquired) _Lock.ExitReadLock(); } }
b273a17d30875d64235433245103ee0d1200044c
C#
HiraokaHyperTools/PDFsharp
/PDFsharp/dev/XGraphicsLab-WPF/TestBezier.cs
3.015625
3
using System; using System.Collections.Generic; using System.Text; namespace XDrawing { static class TestBezier { public static void Test() { const double κ = 0.552284749f; // := 4/3 * (1 - cos(-π/4)) / sin(π/4)) <=> 4/3 * sqrt(2) - 1 //XRect rect = new XRect(x, y, width, height); double δx = 1; double δy = 1; double fx = δx * κ; double fy = δy * κ; //double x0 = rect.X + δx; //double y0 = rect.Y + δy; double start = 0; double stop = Math.PI / 2; for (double α = start; α <= stop; α += (Math.PI / 3600)) { double x = Math.Cos(α); double y = Math.Sin(α); } } } }
f83d5ddaa7a951b53e9a87d65bd79fffe1a98726
C#
aerodinamicc/AutoRent
/Client/Commands/Loading/LoadOfficesCommand.cs
2.90625
3
using Client.Commands.Contracts; using Data.Context; using Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; namespace Client.Commands.Listing { public class LoadOfficesCommand : ICommand { private readonly IAutoRentContext context; public LoadOfficesCommand(IAutoRentContext context) { this.context = context ?? throw new ArgumentNullException("context"); } public string Execute(IList<string> parameters) { using (var contextDb = new AutoRentContext()) { var json = File.ReadAllText(@"offices.json"); var list = JsonConvert.DeserializeObject<List<Office>>(json); foreach (var office in list) { contextDb.Offices.Add(office); } contextDb.SaveChanges(); } return "Offices loaded from JSON to database!"; } } }
3de2b08376b7455f578861754bd845bc540fd363
C#
SpartyInDetroit/EFthis
/EFthis/Program.cs
2.96875
3
using System; using System.Data.SqlClient; using CommandLine; using EFthis.CodeGeneration; namespace EFthis { class Program { static void Main(string[] args) { Parser.Default.ParseArguments<Options>(args) .WithParsed(options => { ControlFlow(options); }); } private static void ControlFlow(Options options) { if (string.IsNullOrWhiteSpace(options.ConnectionString)) { Console.WriteLine("Connection string or YAML input required"); return; } BuildSingleEntity(options.ConnectionString, options.Table, options.Schema, options.Output); } private static void BuildSingleEntity(string connectionString, string table, string schema, bool output) { if (output) { Console.WriteLine("Output to directory not implemented yet"); } try { var connection = new SqlConnection(connectionString); var tableMetadata = new TableMetaDataBuilder(connection); var tableProperties = tableMetadata.GetProperties(table, schema); var entity = EntityBuilder.BuildEntity(table, schema, tableProperties); Console.Write(entity); } catch (Exception e) { Console.WriteLine($"Something went wrong:{Environment.NewLine}{e}"); } } } }
5f4410ba3583b261b9e5fc58c05d323dd5cc77d1
C#
devnixs/CSharpClassesToSQLServerTable
/ObjectScriptingExtensions/Relation.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ObjectScriptingExtensions { public class Relation : ICloneable { public TableDefinition Table { get; set; } public TableDefinition ForeignTable { get; set; } public string Name { get; set; } public RelationshipType Type { get; set; } public string Override { get; set; } public string Grouping { get { if (String.Compare(Table.Index,ForeignTable.Index) < 1) return Table.Index + ForeignTable.Index + Override.GetValueOrDefault(String.Empty); else return ForeignTable.Index + Table.Index + Override.GetValueOrDefault(String.Empty); } } public object Clone() { Relation relation = new Relation(); relation.Type = this.Type; relation.ForeignTable = this.ForeignTable; relation.Name = this.Name; relation.Table = this.Table; relation.Override = this.Override; return relation; } } }