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
38fd4594876a4f83e7a5f1321b3b0bf2acf1ed52
C#
SesticM/tf-net
/Core/Src/NetTopologySuite/Geometries/Utilities/LinearComponentExtracter.cs
3.25
3
using System; using System.Collections; using System.Text; using Topology.Geometries; namespace Topology.Geometries.Utilities { /// <summary> /// Extracts all the 1-dimensional (<c>LineString</c>) components from a <c>Geometry</c>. /// </summary> public class LinearComponentExtracter : IGeometryComponentFilter { /// <summary> /// Extracts the linear components from a single point. /// If more than one point is to be processed, it is more /// efficient to create a single <c>LineExtracterFilter</c> instance /// and pass it to multiple geometries. /// </summary> /// <param name="geom">The point from which to extract linear components.</param> /// <returns>The list of linear components.</returns> public static IList GetLines(IGeometry geom) { IList lines = new ArrayList(); geom.Apply(new LinearComponentExtracter(lines)); return lines; } private IList lines; /// <summary> /// Constructs a LineExtracterFilter with a list in which to store LineStrings found. /// </summary> /// <param name="lines"></param> public LinearComponentExtracter(IList lines) { this.lines = lines; } /// <summary> /// /// </summary> /// <param name="geom"></param> public void Filter(IGeometry geom) { if (geom is ILineString) lines.Add(geom); } } }
acb63bdeae2d939df9dc5d54e865d4dcb6b55b95
C#
dealproc/CredentialManagement
/source/WebHost/ModelMappers/ValueResolvers/MasterAccountResolver.cs
2.53125
3
using AutoMapper; using DataModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebHost.ModelMappers.ValueResolvers { public class MasterAccountResolver : ValueResolver<int, DataModel.MasterAccount> { IDataContext _DbContext; public MasterAccountResolver(IDataContext db) { if (db == null) { throw new ArgumentNullException("db"); } _DbContext = db; } protected override DataModel.MasterAccount ResolveCore(int source) { return _DbContext.Accounts .OfType<DataModel.MasterAccount>() .SingleOrDefault(x => x.Id == source); } } }
1a46e327aa133c95729636c8f2b2e0133b6dd2d6
C#
hamzahazaimeh/studentmanagementBackend
/Controllers/StudentInfoesController.cs
2.6875
3
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using StudentManagementSystem.Models; namespace StudentManagementSystem.Controllers { [Route("api/[controller]")] [ApiController] public class StudentInfoesController : ControllerBase { private readonly StudentSystemContext _context; public StudentInfoesController(StudentSystemContext context) { _context = context; } // GET: api/StudentInfoes [HttpGet] public async Task<ActionResult<IEnumerable<StudentInfo>>> GetStudentInfo() { return await _context.StudentInfo.ToListAsync(); } // GET: api/StudentInfoes/5 [HttpGet("{id}")] public async Task<ActionResult<StudentInfo>> GetStudentInfo(int id) { var studentInfo = await _context.StudentInfo.FindAsync(id); if (studentInfo == null) { return NotFound(); } return studentInfo; } // PUT: api/StudentInfoes/5 [HttpPut("{id}")] public async Task<IActionResult> PutStudentInfo(int id, StudentInfo studentInfo) { if (id != studentInfo.Id) { return BadRequest(); } _context.Entry(studentInfo).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StudentInfoExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/StudentInfoes [HttpPost] public async Task<ActionResult<StudentInfo>> PostStudentInfo(StudentInfo studentInfo) { _context.StudentInfo.Add(studentInfo); await _context.SaveChangesAsync(); return CreatedAtAction("GetStudentInfo", new { id = studentInfo.Id }, studentInfo); } // DELETE: api/StudentInfoes/5 [HttpDelete("{id}")] public async Task<ActionResult<StudentInfo>> DeleteStudentInfo(int id) { var studentInfo = await _context.StudentInfo.FindAsync(id); if (studentInfo == null) { return NotFound(); } _context.StudentInfo.Remove(studentInfo); await _context.SaveChangesAsync(); return studentInfo; } private bool StudentInfoExists(int id) { return _context.StudentInfo.Any(e => e.Id == id); } } }
039ec445c2b781236f3e2a46d4e9a27cc61242a4
C#
lukaszWroc/University
/Materiały/POO/Lista3/Zadanie1/Zadanie1/Zad1.cs
3.515625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* 1. Creator - Shape Factory przechowuje i tworzy na zamówienie obiekty typu Shape 2. Information Expert - Figury same liczą swoje pola - zobowiązania są przydzielane tym obiektom które mają informacje konieczne do ich realizacji. 3.Low Coupling - Pozwala na dodawanie pracowników, bo każdy pracownik wie, jakie figury może tworzyć i posiada kod tworzący te figury. Dzięki temu zwiększamy możliwość reużywania kodu 4. Polymorphizm - Skoro dla różnych figur sposób liczenia pola/obwodu jest rózny, to każda figura dziedziczy z klasy bazowej i nadpisuje metody, by nie robić case'ów 5.Protected Variations - Stabilny interfejs IFactoryWorker dzięki któremu możemy zmieniać poszczególne sposoby obliczania bądź dodawać/usuwać figury, i nie ma to wpływu na resztę figur. */ namespace Zadanie1 { class Zad1 { public static void Main(string[] args) { ShapeFactory factory = new ShapeFactory(); TriangleWorker tworker = new TriangleWorker(); SquareWorker sworker = new SquareWorker(); factory.AddWorker(sworker); factory.AddWorker(tworker); Shape t = factory.CreateShape("Triangle", 10); Shape s = factory.CreateShape("Square", 10); t.PrintInfo(); Console.WriteLine("Pole: {0}, Obwód: {1}", t.ComputeArea(), t.ComputePerimeter()); s.PrintInfo(); Console.WriteLine("Pole: {0}, Obwód: {1}", s.ComputeArea(), s.ComputePerimeter()); Console.ReadLine(); } } public abstract class Shape { public abstract double ComputeArea(); public abstract double ComputePerimeter(); public abstract void PrintInfo(); } public class Triangle : Shape { public double Side { get; set; } public override double ComputeArea() { return (Side * Side * Math.Sqrt(3)) / 4; } public override double ComputePerimeter() { return 3 * Side; } public override void PrintInfo() { Console.WriteLine("Trójkąt o boku {0}", Side); } } public class Square : Shape { public double Side { get; set; } public override double ComputeArea() { return Side * Side; } public override double ComputePerimeter() { return 4 * Side; } public override void PrintInfo() { Console.WriteLine("Kwadrat o boku {0}", Side); } } public interface IFactoryWorker { bool Parameter(string parameter); Shape Create(double Side); } public class TriangleWorker : IFactoryWorker { public bool Parameter(string parameter) { return parameter.Equals("Triangle"); } public Shape Create(double Side) { return new Triangle() { Side = Side }; } } public class SquareWorker : IFactoryWorker { public bool Parameter(string parameter) { return parameter.Equals("Square"); } public Shape Create(double Side) { return new Square() { Side = Side }; } } public class ShapeFactory { List<IFactoryWorker> workers; public ShapeFactory() { workers = new List<IFactoryWorker>(); } public void AddWorker(IFactoryWorker worker) { workers.Add(worker); } public Shape CreateShape(string type, double Side) { foreach (IFactoryWorker worker in workers) { if (worker.Parameter(type)) { Shape newShape = worker.Create(Side); return newShape; } } return null; } } }
6bb162315beda0ec3bde3a9f56f5595ecae60bbb
C#
lxkbest/SexyColor.Net
/SexyColor.CommonComponents/Users/UserService.cs
2.625
3
using System.Collections.Generic; using SexyColor.BusinessComponents; namespace SexyColor.CommonComponents { public class UserService : IUserService { public IUserRepository userRepository { get; set; } /// <summary> /// 根据帐号邮箱获取用户 /// </summary> /// <param name="accountEmail">帐号邮箱</param> public User FindUserByEmail(string accountEmail) { long userId = userRepository.GetUserIdByEmail(accountEmail); return GetUser(userId); } /// <summary> /// 根据手机号获取用户 /// </summary> /// <param name="accountMobile">手机号</param> public User FindUserByMobile(string accountMobile) { long userId = userRepository.GetUserIdByMobile(accountMobile); return GetUser(userId); } /// <summary> /// 获取用户根据用户Id /// </summary> /// <param name="userId">用户Id</param> public User GetUser(long userId) { if (userId <= 0) return null; return userRepository.GetUser(userId); } /// <summary> /// 获取用户根据用户名 /// </summary> /// <param name="userName">用户名</param> public User GetUser(string userName) { long userId = userRepository.GetUserIdByUserName(userName); return GetUser(userId); } /// <summary> /// 根据昵称获取昵称 /// </summary> /// <param name="nickName">昵称</param> public User GetUserByNickName(string nickName) { long userId = userRepository.GetUserIdByNickName(nickName); return GetUser(userId); } /// <summary> /// 根据用户Id集合获取用户对象集合 /// </summary> /// <param name="userIds">用户Id集合</param> /// <returns>用户对象集合</returns> public IEnumerable<User> GetUsers(IEnumerable<long> userIds) { if (userIds == null) return new List<User>(); return userRepository.GetModelByIds<long>(w => w.UserId, userIds); } /// <summary> /// 根用户Id集合删除用户 /// </summary> /// <param name="userIds">用户Id集合</param> public void DeleteUsers(IEnumerable<long> userIds) { List<User> users = new List<User>(); foreach (var userId in userIds) { User user = userRepository.GetUser(userId); if (user == null) continue; var result = userRepository.DeleteCache(user); if (result) { UserIdToUserNameDictionary.RemoveUserId(userId); UserIdToUserNameDictionary.RemoveUserName(user.UserName); } } } /// <summary> /// 删除用户 /// </summary> /// <param name="userId">用户Id</param> public void DeleteUser(long userId) { User user = userRepository.GetUser(userId); var result = userRepository.DeleteCache(user); if (result) { UserIdToUserNameDictionary.RemoveUserId(userId); UserIdToUserNameDictionary.RemoveUserName(user.UserName); } } /// <summary> /// 编辑用户 /// </summary> /// <param name="entity"></param> /// <returns></returns> public bool EditUser(User entity) { return userRepository.UpdateCache(entity); } } }
625e01dbd499ee09a8033818af51f177a1a87070
C#
ethiele/TickTackToe
/Program.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TickTackToe { class Program { static void Main(string[] args) { Game g = new Game(); Console.Write(g.ShowGameState()); Console.ReadLine(); AI ai1 = new AI(); AI ai2 = new AI(); ai1.Init("X"); ai2.Init("O"); while (g.StateOfGame == GameState.Running) { ai1.MakeMove(new GameControl(g)); Console.Write(g.ShowGameState()); //Console.ReadLine(); if (g.StateOfGame != GameState.Running) break; ai2.MakeMove(new GameControl(g)); Console.Write(g.ShowGameState()); //Console.ReadLine(); } Console.WriteLine("STATUS: " + g.StateOfGame); Console.WriteLine("Game Terminated"); Console.ReadLine(); } } }
5d1af99983b672c98cf3d16842a5edcffe8eef1e
C#
1cekrim/flower
/Assets/Scripts/ItemScripts/ItemFactory.cs
2.703125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemFactory : MonoBehaviour { private Dictionary<string, Item> allItems; public void CreateAllItems() { allItems = new Dictionary<string, Item>(); foreach (Transform child in transform) { IItemFactory factory = child.gameObject.GetComponent<IItemFactory>(); Debug.Log("OperateFactory: " + child.name); OperateFactory(factory); } // for debug // foreach (Item item in allItems.Values) // { // InventoryManager.Instance.GetItem(item); // } } private void OperateFactory(IItemFactory factory) { factory.AppendItems(ref allItems); } }
62975054589481f93034c185b6543d00cd2bedb0
C#
Pinkuburu/Simple_G_J_K
/Assets/Scripts/PhysicSystem/Suppot Scripts/SemisphereSupport.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace PhysicalSystem { public class SemisphereSupport : MonoBehaviour, ISupport { public float radius; public float center_to_base; public Vector3 Support(Vector3 direction) { Vector3 base_center = transform.position + transform.right.normalized * center_to_base; if (direction.normalized == transform.right.normalized) { return base_center; } else if (Vector3.Dot(transform.right, direction) > 0) { Vector3 horiz = Vector3.ProjectOnPlane(direction.normalized, transform.right).normalized; return base_center + horiz * radius; } else { return base_center + direction.normalized * radius; } } } }
07118349e8ab867e14d669be655ffe0649954b9b
C#
KayYowanu/TheKingdomproject
/Concrete/PostService.cs
2.71875
3
using Dapper; using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using TheGospel.Contracts; using TheGospel.Entities; namespace TheGospel.Concrete { public class PostService : IPostService { private readonly IPostRepo _postrepo; public PostService(IPostRepo _postrepo) { this._postrepo = _postrepo; } public Task<int> CreatePost(TKAPosts tkaposts, string Username) { var dbPara = new DynamicParameters(); dbPara.Add("Title", tkaposts.Title, DbType.String); dbPara.Add("Description", tkaposts.Description, DbType.String); dbPara.Add("Username", Username, DbType.String); var PostId = Task.FromResult(_postrepo.InsertPost<int>("[dbo].[Create_Post]", dbPara, commandType: CommandType.StoredProcedure)); return PostId; } public Task<TKAPosts> GetPostById(int id) { var tkaposts = Task.FromResult(_postrepo.GetPost<TKAPosts>($"select * from [TKAPosts] where PostId = {id}", null, commandType: CommandType.Text)); return tkaposts; } public Task<int> DeletePost(int id) { var deletepost = Task.FromResult(_postrepo.ExecutePost($"Delete from [TKAPosts] where PostId = {id}", null, commandType: CommandType.Text)); return deletepost; } public Task<int> CountPost(string search) { var totArticle = Task.FromResult(_postrepo.GetPost<int>($"select COUNT(*) from [TKAPosts] WHERE Title like '%{search}%'", null, commandType: CommandType.Text)); return totArticle; } public Task<List<TKAPosts>> ListAllPosts(int skip, int take, string orderBy, string direction = "DESC", string search = "") { var posts = Task.FromResult(_postrepo.GetAllPosts<TKAPosts> ($"SELECT * FROM [TKAPosts] WHERE Title like '%{search}%' ORDER BY {orderBy} {direction} OFFSET {skip} ROWS FETCH NEXT {take} ROWS ONLY; ", null, commandType: CommandType.Text)); return posts; } public Task<List<TKAPosts>> ListAllUserPosts(string username, int skip, int take, string orderBy, string direction = "DESC", string search = "") { var posts = Task.FromResult(_postrepo.GetAllPosts<TKAPosts> ($"SELECT * FROM [TKAPosts] WHERE Username = '{username}' ORDER BY {orderBy} {direction} OFFSET {skip} ROWS FETCH NEXT {take} ROWS ONLY; ", null, commandType: CommandType.Text)); return posts; } public Task<int> UpdatePost(TKAPosts tkapost) { var dbPara = new DynamicParameters(); dbPara.Add("PostId", tkapost.PostId); dbPara.Add("Title", tkapost.Title, DbType.String); dbPara.Add("Description", tkapost.Description, DbType.String); var updatepost = Task.FromResult(_postrepo.UpdatePost<int>("[dbo].[Update_Post]", dbPara, commandType: CommandType.StoredProcedure)); return updatepost; } /*FOR COMMENTS IMPLEMENTATIONS*/ public Task<int> CreateComment(TKAComments tkacomments, TKAPosts tkaposts, string Username) { var dbPara = new DynamicParameters(); dbPara.Add("Comment", tkacomments.Comment, DbType.String); dbPara.Add("PostId", tkaposts.PostId, DbType.String); dbPara.Add("Username", Username, DbType.String); var CommentId = Task.FromResult(_postrepo.InsertComment<int>("[dbo].[Add_Comment]", dbPara, commandType: CommandType.StoredProcedure)); return CommentId; } public Task<TKAComments> GetCommentById(int id) { var comments = Task.FromResult(_postrepo.GetComment<TKAComments>($"select * from [TKAComments] where CommentId = {id}", null, commandType: CommandType.Text)); return comments; } public Task<int> DeleteComment(int id) { var deletecomment = Task.FromResult(_postrepo.ExecuteComment($"Delete from [TKAComments] where CommentId = {id}", null, commandType: CommandType.Text)); return deletecomment; } public Task<int> CountComment(string search) { var tcount = Task.FromResult(_postrepo.GetComment<int>($"select COUNT(*) from [TKAComments] WHERE Comment like '%{search}%'", null, commandType: CommandType.Text)); return tcount; } public Task<List<TKAComments>> ListAllComments() { var comments = Task.FromResult(_postrepo.GetAllComments<TKAComments> ($"SELECT * FROM [TKAComments] ", null, commandType: CommandType.Text)); return comments; } public Task<List<TKAComments>> ListAllComments(int Id) { var comments = Task.FromResult(_postrepo.GetAllComments<TKAComments> ($"SELECT * FROM [TKAComments] where PostId = {Id}", null, commandType: CommandType.Text)); return comments; } public Task<int> UpdateComment(TKAComments tkacomment) { var dbPara = new DynamicParameters(); dbPara.Add("CommentId", tkacomment.CommentId); dbPara.Add("Comment", tkacomment.Comment, DbType.String); var updatecomment = Task.FromResult(_postrepo.UpdateComment<int>("[dbo].[Update_Comment]", dbPara, commandType: CommandType.StoredProcedure)); return updatecomment; } //Email public Task<List<TKAComments>> GetUserEmail(int Id) { var userEmail = Task.FromResult(_postrepo.GetUserEmail<TKAComments> ($"SELECT Username FROM [TKAPosts] where PostId = {Id}", null, commandType: CommandType.Text)); return userEmail; } } }
93d61986cd1d6316fb8cf860a9bcce238d828682
C#
XaLVaUA/projects
/Task4/Task4/Task4/Program.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task4 { class Program { static void Main(string[] args) { var arr = new ArbitraryArray<int>(-2, 3) {[-2] = 5, [-1] = 10, [0] = 3, [1] = 9, [2] = 11, [3] = 4}; foreach (var item in arr) { Console.WriteLine(item); } Console.ReadLine(); } } }
86dacc18cae91e77681f55a3f9b1952cfd1e9bbc
C#
gergelykoncz/Patterns.Specification
/BusinessLayer/Specification/Person/Simple/PersonJobTitleSpecification.cs
2.78125
3
using BusinessLayer.Specification.Abstract; namespace BusinessLayer.Specification.Person.Simple { using Person = BusinessLayer.Entity.Person; public class PersonJobTitleSpecification : CompositeSpecification<Person> { private readonly string _jobTitleFragment; public PersonJobTitleSpecification(string jobTitleFragment) { this._jobTitleFragment = jobTitleFragment; } public override bool IsSatisfiedBy(Person item) { if (string.IsNullOrEmpty(_jobTitleFragment)) { return true; } else { return item.JobTitle.ToUpper().Contains(_jobTitleFragment.ToUpper()); } } } }
e96f207df0df73a8095126a090ebf079aa4e3452
C#
CmdBianchi/EXERCICIO-02---ESTRUTURA-FOR
/EXERCICIO 02 - ESTRUTURA FOR/Program.cs
3.859375
4
using System; namespace EXERCICIO_02___ESTRUTURA_FOR{ class Program{ /// -------> START / MAIN ///////////////////////////////////////////////////////////////////////////////////////////// static void Main(string[] args){ Msg(); Conditional(); } /// -------> FUNCTIONS ///////////////////////////////////////////////////////////////////////////////////////////// static void Msg(){ Console.WriteLine("Mostre quantos destes valores X estão dentro do intervalo [10,20]."); } //------------------------------------------------------------------------------------------// static void Conditional(){ Console.Write("Digite o tamanho do intervalo: "); int n = int.Parse(Console.ReadLine()); //------> Tamanho do intervalo int cont_in = 0; int cont_out = 0; for(int i = 0; i < n; i++){ int x = int.Parse(Console.ReadLine()); //------> X é os números do intervalo if (x >= 10 && x <= 20){ cont_in = cont_in + 1; //------> Contador de números dentro } else{ cont_out = cont_out + 1; //------> Contador de números fora } } Console.WriteLine(cont_in + " in"); Console.WriteLine(cont_out + " out"); } ///////////////////////////////////////////////////////////////////////////////////////////// /// -------> END } }
12914450d604f4f3c7fc0ff27dc87d71229eccda
C#
Grouts/Grout
/Main/Base/Grout.Base.DataClasses/SelectedColumn.cs
2.671875
3
namespace Grout.Base.DataClasses { /// <summary> /// Model class for column in select statement /// </summary> public class SelectedColumn { /// <summary> /// Gets or sets the table name from which the column need to be selected( Need to set only if the column belongs to a /// different table in join query) /// </summary> public string TableName { get; set; } /// <summary> /// Gets or sets the column name /// </summary> public string ColumnName { get; set; } /// <summary> /// Gets or sets the column Alias name /// </summary> public string AliasName { get; set; } /// <summary> /// Gets or sets the aggrigation method to apply on the column /// </summary> public AggregateMethods Aggregation { get; set; } /// <summary> /// Gets or sets whether the returned column should be distinct /// </summary> public bool IsDistinct { get; set; } public string JoinAliasName { get; set; } } }
844820aeb9390430cc91ea6b932da0d9e92954a7
C#
ElshadaiK/Object-Oriented-Programming-II_Lab
/Assignment-1/44.NewStringOdd.cs
3.640625
4
using System; using System.Linq; namespace HelloWorld{ class NewStringOdd { public void newStringOdd(){ Console.Write("Input a string : "); string str = Console.ReadLine(); var result = string.Empty; for (var i = 0; i < str.Length; i++) { if (i % 2 == 0) result += str[i]; } Console.WriteLine(result); } } }
47c1a34a0fdae5b9d6db22e9cbeae0b64a181e09
C#
camjm/BeyondEarthApp
/src/BeyondEarthApp.Data.SqlServer/QueryProcessors/AllGamesQueryProcessor.cs
2.765625
3
using BeyondEarthApp.Data.Entities; using BeyondEarthApp.Data.QueryProcessors; using NHibernate; namespace BeyondEarthApp.Data.SqlServer.QueryProcessors { /// <summary> /// Packages data from database into QueryResult. /// </summary> public class AllGamesQueryProcessor : IAllGamesQueryProcessor { private readonly ISession _session; public AllGamesQueryProcessor(ISession session) { _session = session; } public QueryResult<Game> GetGames(PagedDataRequest requestInfo) { // IQueryOver instance provides queryable access to the table: haven't fetched any data from database yet. var query = _session.QueryOver<Game>(); // Queries the database var totalItemCount = query.ToRowCountQuery().RowCount(); var startIndex = ResultsPagingUtility.CalculateStartIndex(requestInfo.PageNumber, requestInfo.PageSize); // Only 1 page of data is fetched from the database var games = query.Skip(startIndex).Take(requestInfo.PageSize).List(); var queryResult = new QueryResult<Game>(games, totalItemCount, requestInfo.PageSize); return queryResult; } } }
f3416ee8652bbeeb918de045763973da65050bd9
C#
henrikfroehling/Trakt.NET
/Source/Lib/Trakt.NET/Requests/Handler/ResponseMessageHelper.cs
2.5625
3
namespace TraktNet.Requests.Handler { using System.IO; using System.Net.Http; using System.Threading.Tasks; internal static class ResponseMessageHelper { internal static async Task<Stream> GetResponseContentStreamAsync(HttpResponseMessage responseMessage) => responseMessage.Content != null ? await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false) : default; internal static async Task<string> GetResponseContentAsync(HttpResponseMessage responseMessage) => responseMessage.Content != null ? await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false) : string.Empty; } }
2917a375da925bdc9fa9e007debf41ca86acd98e
C#
volokontsev/HW_UI_6.2
/Assets/Scripts/ObjectWithHealth.cs
2.734375
3
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; public class ObjectWithHealth : MonoBehaviour { [SerializeField] private float _maxHealth; [SerializeField] private HealthBar _healthBar; private float _objectHealth; public float MaxHealth => _maxHealth; public float ObjectHealth { get => _objectHealth; private set => _objectHealth = value;} private void Awake() { ObjectHealth = _maxHealth; } public void ChangeHealth(bool rize, float value) { StartCoroutine(ChangeHealthSlow(rize, value)); } private IEnumerator ChangeHealthSlow(bool rize, float value) { var waitingTime = new WaitForSeconds(0.05f); for (int i = 0; i < value; i++) { if (rize && ObjectHealth<_maxHealth) ObjectHealth++; else if(!rize && ObjectHealth>0) ObjectHealth--; _healthBar.UpdateValue(); yield return waitingTime; } } }
eab40053470229213421f10a7f0e0374eda31561
C#
Anton25121995/MyRepos
/TaskManager (Xamarin.Forms)/HelloMvxForms/HelloMvxForms/Converters/FromPathToImageSourceConverter.cs
2.53125
3
using MvvmCross.Platform.Converters; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using Xamarin.Forms; namespace HelloMvxForms.Converters { public class FromPathToImageSourceConverter : MvxValueConverter { public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (File.Exists((string)value)) { return ImageSource.FromFile((string)value); } var uriString = "https://storage.googleapis.com/appconfig-media/appconfig-content/uploads/2016/04/xamarin-app-logo2.png"; return ImageSource.FromUri(new Uri(uriString)); } } }
152302300794d3f17cbfc2f3670e1d072af50f60
C#
davefancher/NETAsync
/Async/Examples/15_AsyncAwaitCancellationAndExceptions.cs
3
3
using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using static Async.Logger; namespace Async.Examples { public static class AsyncAwaitCancellationAndExceptionExample { private static Func<double, Task> DoResize(CancellationToken cToken ,ImageProcessor processor, string outputFolderPath) => ratio => Task .Factory .StartNew( () => { LogWarning($"Resizing image to {ratio:P2}"); var newImage = processor.ResizeSafe(ratio); LogInfo($"Done resizing image to {ratio:P2}"); return newImage; }, cToken) .ContinueWith( a => { throw new Exception("Fail"); var image = a.Result; var fileName = $"{image.Width}x{image.Height}.jpg"; LogWarning($"Saving {fileName} image"); Path .Combine( outputFolderPath, fileName) .Apply(image.Save); LogInfo($"Done saving {fileName} image"); }, cToken); public static async Task Run(string sourceFileName, string outputFolderPath, double[] ratios) { using (var processor = ImageProcessor.FromFile(sourceFileName)) { var cTokenSource = new CancellationTokenSource(); //cTokenSource.CancelAfter(TimeSpan.FromSeconds(0.25)); var cToken = cTokenSource.Token; try { await ratios .Select(DoResize(cToken, processor, outputFolderPath)) .ToArray() .Pipe(Task.WhenAll); } catch (TaskCanceledException ex) { LogError(ex.Message); } catch (Exception ex) { LogError(ex.Message); } } } } }
57be21a761945bbc9e0de0350d618a1f62092de6
C#
TrickyTriangles/StraightUpGameJam1_DownToTheWire
/Assets/Scripts/Utils/MovementUtils.cs
2.859375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class MovementUtils { public static Direction CheckMovementDirection(Vector2 looking) { Direction direction; if (looking.x == 0f && looking.y > 0f) { direction = Direction.NORTH; } else if (looking.x > 0f && looking.y == 0f) { direction = Direction.EAST; } else if (looking.x == 0f && looking.y < 0f) { direction = Direction.SOUTH; } else if (looking.x < 0f && looking.y == 0f) { direction = Direction.WEST; } else { direction = Direction.NONE; } return direction; } }
7dbe1009afa60bb3d6a14a1f07d0137315660313
C#
cemeyer/t1bootstrap
/src/Lexer.cs
3.21875
3
using System; using System.IO; using System.Text; /* * Basic lexer. * * Tokens are: * * word: sequence of printable non-space characters (ASCII 33 to 126), * excluding ()[]{}`'"# * * literal string: starts with double-quote, followed by string contents * (escapes have been interpreted, and there is no final double-quote) * * literal character: starts with backquote, followed by a single code point * (escapes have been interpreted) * * single-letter word: one of ()[]{}' * * Whitespace separates tokens; whitespace is any sequence of control * characters (ASCII 0 to 31) and space (ASCII 32). * * The lexer skips comments. A comment starts with # and extends to the end * of the line, but does not include the end-of-line (thus, a comment counts * as whitespace). * * Code points 127+ may appear only in literal strings and characters. */ class Lexer { TextReader r; int delayedChar; internal Lexer(TextReader r) { this.r = r; delayedChar = -1; } /* * Utility method: append a code point to a StringBuilder. This * handles splitting into surrogate pairs when necessary. */ static void AppendCP(StringBuilder sb, int cp) { if (cp >= 0 && cp <= 0xFFFF) { sb.Append((char)cp); } else if (cp >= 0x10000 && cp <= 0x10FFFF) { cp -= 0x10000; sb.Append((char)(0xD800 + (cp >> 10))); sb.Append((char)(0xDC00 + (cp & 0x3FF))); } else { throw new Exception("invalid code point: " + cp); } } /* * Get next word/token. * Returns null on end-of-stream. */ internal string Next() { int x; for (;;) { x = NextChar(); if (x == '#') { for (;;) { x = NextChar(); if (x < 0 || x == '\n') { break; } } } if (x < 0) { return null; } if (!IsWS(x)) { break; } } if (IsSingleCharToken(x)) { return "" + (char)x; } if (x == '`') { return ReadLiteralChar(); } else if (x == '"') { return ReadLiteralString(); } else if (IsWordChar(x)) { StringBuilder sb = new StringBuilder(); AppendCP(sb, x); for (;;) { x = NextChar(); if (!IsWordChar(x)) { break; } AppendCP(sb, x); } Unread(x); return sb.ToString(); } else { throw new Exception(string.Format( "forbidden source character: U+{0:X4}", x)); } } /* * Get next code point. Some processing is applied: * * - Surrogate pairs are reassembled into code points in the * upper planes (U+10000 to U+10FFFF). Unmatched surrogates * trigger exceptions. * * - Lone CR, and CR+LF pairs, are converted to LF. */ int NextChar() { int x = delayedChar; if (x >= 0) { delayedChar = -1; return x; } if (r == null) { return -1; } x = r.Read(); if (x < 0) { r = null; return -1; } if (x == '\r') { x = r.Read(); if (x < 0) { r = null; } else if (x != '\n') { delayedChar = x; } x = '\n'; } else if (x >= 0xD800 && x <= 0xDBFF) { int y = r.Read(); if (y < 0) { r = null; } if (y < 0xDC00 || x > 0xDFFF) { throw new Exception("unmatched surrogate"); } x = ((x & 0x3FF) << 10) + (y & 0x3FF) + 0x10000; } return x; } /* * Unread the provided code point. It will be returned by the * next NextChar() call. Beware that there may be only one * "unread" code point at a time; moreover, when a LF is * returned by NextChar(), there may be an unread code point. */ void Unread(int x) { delayedChar = x; } /* * A backquote was read, for a literal character constant. This * method reads the rest of the constant; returned value is * a string consisting in a backquote character followed by * a single code point (which may use a surrogate pair). This * method interprets escape sequences. */ string ReadLiteralChar() { StringBuilder sb = new StringBuilder(); sb.Append('`'); int x = NextChar(); if (x < 0 || IsWS(x)) { throw new Exception("invalid literal character"); } if (x != '\\') { AppendCP(sb, x); } else { x = NextChar(); if (x < 0) { throw new Exception("invalid literal character"); } ParseEscape(sb, x); } return sb.ToString(); } /* * A double-quote was read, for a literal string. This method * reads the rest of the string. Returned value is a string that * starts with a double-quote, followed by the string contents; * escape sequences are interpreted by this method. */ string ReadLiteralString() { StringBuilder sb = new StringBuilder(); sb.Append('"'); for (;;) { int x = NextChar(); if (x < 0) { throw new Exception("unfinished literal string"); } if (x == '"') { return sb.ToString(); } if (x != '\\') { sb.Append((char)x); continue; } x = NextChar(); if (x < 0) { throw new Exception("unfinished literal string"); } if (x == '\n') { for (;;) { x = NextChar(); if (x < 0) { throw new Exception("unfinished literal string"); } if (x == '"') { break; } if (x == '\n' || !IsWS(x)) { throw new Exception("invalid newline escape"); } } } else { ParseEscape(sb, x); } } } void ParseEscape(StringBuilder sb, int x) { switch (x) { case 's': x = ' '; break; case 't': x = '\t'; break; case 'r': x = '\r'; break; case 'n': x = '\n'; break; case '\'': break; case '`': break; case '"': break; case '\\': break; case 'x': x = ReadEscapeHex(2); break; case 'u': x = ReadEscapeHex(4); break; case 'U': x = ReadEscapeHex(4); break; default: throw new Exception(string.Format("invalid escape U+{0:X4}", x)); } AppendCP(sb, x); } int ReadEscapeHex(int num) { int v = 0; while (num -- > 0) { int x = NextChar(); if (x >= '0' && x <= '9') { x -= '0'; } else if (x >= 'A' && x <= 'F') { x -= ('A' - 10); } else if (x >= 'a' && x <= 'f') { x -= ('a' - 10); } else { if (x < 0) { throw new Exception("end-of-stream in hexadecimal data"); } else { throw new Exception(string.Format("invalid hex digit U+{0:X4}", x)); } } v = (v << 4) + x; } return v; } /* * Whitespace is any code point between 0 and 32, inclusive * (i.e. all ASCII control characters, and ASCII space). */ static bool IsWS(int cp) { return cp <= 32; } static bool IsSingleCharToken(int cp) { return cp == '(' || cp == ')' || cp == '[' || cp == ']' || cp == '{' || cp == '}' || cp == '\''; } static bool IsWordChar(int cp) { return cp >= 33 && cp <= 126 && !IsSingleCharToken(cp) && cp != '"' && cp != '`' && cp != '#'; } }
6a5ed78ba73b53a500e5e545f6dba7a8f44858be
C#
ArnaudDebaene/LSMEmprunts
/LSMEmprunts/BorrowStateToStringConverter.cs
2.90625
3
using System; using System.Globalization; using System.Windows.Data; using LSMEmprunts.Data; namespace LSMEmprunts { class BorrowStateToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var state = (BorrowingState) value; switch (state) { case BorrowingState.Open: return "En cours"; case BorrowingState.GearReturned: return "Clos"; case BorrowingState.ForcedClose: return "Clos de force"; } throw new ArgumentOutOfRangeException(nameof(value)); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
744da50434d768af4d3610d922f8ae64f54bfc8d
C#
PonWer/DnDTextDecryptor
/DnDTextDecryptor/Program.cs
2.96875
3
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("DnDTextDecryptor.Test")] namespace DnDTextDecryptor { internal class Program { internal static List<char> vokaler = new List<char>() { 'A', 'O', 'U', 'Å', 'E', 'I', 'Y', 'Ä', 'Ö' }; static void Main(string[] args) { void WriteResult(string inTestName, int i, string result) { Console.WriteLine($"Result of {inTestName} with offset: {i}!"); Console.WriteLine(); Console.WriteLine(result); _ = Console.ReadKey(); Console.WriteLine(); Console.WriteLine(); } for (int i = 0; i < 28; i++) { var result = SimpleOffset(Resources.OriginalText.ToUpper(), i); WriteResult("SimpleOffset", i, result); } for (int i = 0; i < 28; i++) { var result = IncreaseOffsetWithEachNewChar(Resources.OriginalText.ToUpper(), i); WriteResult("IncreaseOffsetWithEachNewChar", i, result); } for (int i = 0; i < 28; i++) { var result = IncreaseOffsetWithEachNewVOKAL(Resources.OriginalText.ToUpper(), i); WriteResult("IncreaseOffsetWithEachNewVOKAL", i, result); } for (int i = 0; i < 28; i++) { var result = IncreaseOffsetWithEachNewWord(Resources.OriginalText.ToUpper(), i); WriteResult("IncreaseOffsetWithEachNewWord", i, result); } } internal static string SimpleOffset(string inText, int inOffset) { using (StringWriter writer = new StringWriter()) { foreach (char c in inText) { if (c == '\\' || c == 'n' || c == 'r' || c == '.' || c == ',' || c == ':' || c == ' ') writer.Write(c); else writer.Write(OffsetChar(c, inOffset)); } return writer.ToString(); } } internal static string IncreaseOffsetWithEachNewChar(string inText, int inInitialOffset) { var offset = inInitialOffset; using (StringWriter writer = new StringWriter()) { foreach (char c in inText) { if (c == '\\' || c == 'n' || c == 'r' || c == '.' || c == ',' || c == ':' || c == ' ') writer.Write(c); else writer.Write(OffsetChar(c, offset++)); } return writer.ToString(); } } internal static string IncreaseOffsetWithEachNewVOKAL(string inText, int inInitialOffset) { var offset = inInitialOffset; using (StringWriter writer = new StringWriter()) { foreach (char c in inText) { if (c == '\\' || c == 'n' || c == 'r' || c == '.' || c == ',' || c == ':' || c == ' ') writer.Write(c); else { if (vokaler.Contains(c)) { offset++; } writer.Write(OffsetChar(c, offset)); } } return writer.ToString(); } } internal static string IncreaseOffsetWithEachNewWord(string inText, int inInitialOffset) { inText = inText.Replace(" ", " "); var offset = inInitialOffset; using StringWriter writer = new StringWriter(); foreach (char c in inText) { if (c == '\\' || c == 'n' || c == 'r' || c == '.' || c == ',' || c == ':') writer.Write(c); else { if (c == ' ') { offset++; writer.Write(c); continue; } writer.Write(OffsetChar(c, offset)); } } return writer.ToString(); } internal static char OffsetChar(char inChar, int inOffset) { return IntToChar(CharToInt(inChar) + inOffset); } internal static int CharToInt(char inChar) { //urg swedish switch (inChar) { case 'Å': return 26; case 'Ä': return 27; case 'Ö': return 28; default: return (int)inChar - 65; } } internal static char IntToChar(int inChar) { inChar %= 29; switch (inChar) { case 26: return 'Å'; case 27: return 'Ä'; case 28: return 'Ö'; default: return (char)(inChar + 65); } } } }
60e1766d69f452e7f06e36661bc03cf6c68e0fbe
C#
15so42/SandTableWar
/Assets/Behavior Designer Samples/MiniGauntlet/Scripts/FireSphere.cs
2.796875
3
using UnityEngine; namespace BehaviorDesigner.Samples { public class FireSphere : MonoBehaviour { public Transform sphereGroup; public Vector3 force; // When the agent enters the trigger shoot the group of spheres at the agent public void OnTriggerEnter(Collider other) { if (sphereGroup.GetComponent<Rigidbody>() != null) { Fire(sphereGroup.GetComponent<Rigidbody>()); } for (int i = 0; i < sphereGroup.childCount; ++i) { if (sphereGroup.GetChild(i).GetComponent<Rigidbody>() != null) { Fire(sphereGroup.GetChild(i).GetComponent<Rigidbody>()); } } } // Fire with the specified force public void Fire(Rigidbody sphereRigidbody) { sphereRigidbody.isKinematic = false; sphereRigidbody.AddForce(force, ForceMode.VelocityChange); } } }
5a50c609c5be9f66678f2efca75774b7407be4f0
C#
regulus33/PrivateVoid
/Assets/Scripts/PickupItem.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PickupItem : MonoBehaviour { private GameObject dialogBox; private Text dialogText; public bool timeToGetDialogGoing; public float letterPaused = 0.1f; public bool typing = false; public string[] dialogLines; public int currentLine = 0; public bool used = false; public Sprite openedSprite; public bool canPickUp = false; // Start is called before the first frame update void Start() { dialogBox = GameObject.FindWithTag("itemDialogBox"); Debug.Log(dialogBox + "..."); dialogText = dialogBox.gameObject.transform.GetChild(0).gameObject.transform.GetChild(0).GetComponent<Text>(); dialogText.text = dialogLines[currentLine]; } // Update is called once per frame void Update() { if(!used && canPickUp) { if(Input.GetButtonDown("Fire1") && PlayerController.instance.canMove) { if(AcceptItem()) { dialogBox.gameObject.transform.GetChild(0).gameObject.SetActive(true); timeToGetDialogGoing = true; } else { } } if(timeToGetDialogGoing) { TickThroughDialog(); } } } public void OnTriggerEnter2D(Collider2D collision) { if(collision.tag == "Player") { canPickUp = true; } } public void OnTriggerExit2D(Collider2D collision) { if(collision.tag == "Player") { canPickUp = true; } } public bool AcceptItem() { if(PlayerController.instance.CanAddItem(GetComponent<Item>().itemType)) { return true; } else { return false; } } public IEnumerator TypeText(string message) { typing = true; // wipe text blank before next print dialogText.text = ""; //Split each char into a char array foreach (char letter in message.ToCharArray()) { AudioManager.instance.PlayCoins(4); //Add 1 letter each dialogText.text += letter; yield return 0; yield return new WaitForSeconds(letterPaused); } typing = false; } public void TickThroughDialog() { //is user clicking? and no animation is haappening and dialog box is active if (!typing && dialogBox.activeInHierarchy && (Input.GetButtonDown("Fire1") || Input.GetKeyDown(KeyCode.M))) { Debug.Log("THE END OF DIALOG PART IS RUNNING"); // We are at last index, set box false if (currentLine >= dialogLines.Length) { //open present, make bleep sound and close dialog boxxx dialogBox.gameObject.transform.GetChild(0).gameObject.SetActive(false); PlayerController.instance.canMove = true; AudioManager.instance.PlayUI(0); gameObject.GetComponent<SpriteRenderer>().sprite = openedSprite; PlayerController.instance.AddItem(GetComponent<Item>().itemType); currentLine = 0; used = true; } // we are still deep in the dialog loop, check if name and type lines! else { Debug.Log("THE COROUTINE PART IS RUNNING"); // dialogText.text = dialogLines[currentLine]; StartCoroutine (TypeText(dialogLines[currentLine])); } currentLine++; } } }
110233af6c003f4776c21f7ce42ec11d6cb2c986
C#
gordonmleigh/msbuildversioning
/MSBuildVersioning/SvnInfoProvider.cs
2.84375
3
using System; using System.Collections.Generic; namespace MSBuildVersioning { /// <summary> /// Provides Subversion information for a particular file path, by executing and scraping /// information from the svn.exe command-line program. /// </summary> public class SvnInfoProvider : SourceControlInfoProvider { private const string ExecutableName = "svn"; private int? revisionNumber; private bool? isMixedRevisions; private bool? isWorkingCopyDirty; private string repositoryUrl; private string repositoryRoot; public override string SourceControlName { get { return "Subversion"; } } public virtual int GetRevisionNumber() { if (revisionNumber == null) { SvnInfoParser parser = new SvnInfoParser(); ExecuteCommand(ExecutableName, "info -R", parser.ReadLine, null); revisionNumber = parser.maxRevisionNumber; isMixedRevisions = parser.isMixedRevisions; } return (int)revisionNumber; } public virtual bool IsMixedRevisions() { if (isMixedRevisions == null) { GetRevisionNumber(); } return (bool)isMixedRevisions; } public virtual bool IsWorkingCopyDirty() { if (isWorkingCopyDirty == null) { SvnStatusParser parser = new SvnStatusParser(); ExecuteCommand(ExecutableName, "status", parser.ReadLine, null); isWorkingCopyDirty = parser.isWorkingCopyDirty; } return (bool)isWorkingCopyDirty; } public virtual string GetRepositoryUrl() { if (repositoryUrl == null) { IList<string> svnInfo = ExecuteCommand(ExecutableName, "info"); foreach (string line in svnInfo) { if (line.StartsWith("URL: ")) { repositoryUrl = line.Substring("URL: ".Length); } else if (line.StartsWith("Repository Root: ")) { repositoryRoot = line.Substring("Repository Root: ".Length); } } } return repositoryUrl; } public virtual string GetRepositoryRoot() { if (repositoryRoot == null) { GetRepositoryUrl(); } return repositoryRoot; } public virtual string GetRepositoryPath() { string path = GetRepositoryUrl().Substring(GetRepositoryRoot().Length); if (path.Length == 0) { return "/"; } else { return path; } } public virtual string GetRepositorySubDirectory(string directory) { string[] pathComponents = GetRepositoryPath().Split('/'); for (int i = 0; i < pathComponents.Length - 1; i++) { if (pathComponents[i] == directory) { return pathComponents[i + 1]; } } return ""; } public virtual string GetBranch() { return GetRepositorySubDirectory("branches"); } public virtual string GetTag() { return GetRepositorySubDirectory("tags"); } private class SvnInfoParser { public int maxRevisionNumber = -1; public bool isMixedRevisions = false; public void ReadLine(string line) { if (line.StartsWith("Revision: ")) { int revision = int.Parse(line.Substring("Revision: ".Length)); if (maxRevisionNumber >= 0 && maxRevisionNumber != revision) { isMixedRevisions = true; } maxRevisionNumber = Math.Max(revision, maxRevisionNumber); } } } private class SvnStatusParser { public bool isWorkingCopyDirty = false; public void ReadLine(string line) { isWorkingCopyDirty = true; } } } }
044409bbb46f83336e78b58a3a09809f504c5a0a
C#
Jpstilley/InheritanceExercise
/Inheritance/Reptile.cs
2.625
3
using System; namespace Inheritance { public class Reptile : Animal { internal bool IsColdBlooded { get; } = true; internal bool HasScales { get; } = true; internal bool Oviparous { get; } = true; internal int NumberOfLungs { get; set; } public Reptile() { Legs = 4; IsVertabrate = true; } } }
4650faab46ffe8c084d9f680f64fb0fb1bf084f0
C#
izzeking10/Ritboken
/Ritboken/Ritverktyg.cs
2.875
3
using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Ritboken { public class Coordinate { public int X { get; set; } public int Y { get; set; } public Coordinate(int x, int y) { X = x; Y = y; } } public abstract class DrawingTool { protected PictureBox pictureBox1; protected List<Coordinate> listOfXY; static public Pen pen = new Pen(Color.Black); protected bool penDown = false; protected List<Image> oldBitmaps = new List<Image>(); public DrawingTool(PictureBox pictureBox) { this.pictureBox1 = pictureBox; if (pictureBox1.BackgroundImage == null) { Bitmap pict = new Bitmap(pictureBox1.Width, pictureBox1.Height); pictureBox1.BackgroundImage = pict; } this.listOfXY = new List<Coordinate>(); } public abstract void MouseDown(int x, int y); public abstract void MouseUp(int x, int y); public abstract void MouseDrag(int x, int y); public abstract void Draw(Pen p, Graphics g); public void Undo() { oldBitmaps.RemoveAt(oldBitmaps.Count - 1); if (oldBitmaps.Count == 0) { Bitmap pict = new Bitmap(pictureBox1.Width, pictureBox1.Height); oldBitmaps.Add(pict); } pictureBox1.BackgroundImage = oldBitmaps[oldBitmaps.Count - 1]; } } }
39115f95ad5969b6a7c6ba65e17c41aff276c771
C#
gongchengshi/mimeo
/Mimeo/Utils/Mimeograph.cs
2.671875
3
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Gongchengshi; namespace Mimeo.Utils { /// <summary> /// Take all URLs and rewrite them to be absolute URLs to their Mimeo equivalents. /// </summary> static public class Mimeograph { private static readonly Dictionary<string, List<KeyValuePair<Regex, string>>> _replacements = new Dictionary<string, List<KeyValuePair<Regex, string>>>(); public static void Initialize(IDictionary<string, HashSet<string>> domains) { foreach (var jobNameDomain in domains) { var replacementsList = new List<KeyValuePair<Regex, string>>(); _replacements[jobNameDomain.Key] = replacementsList; replacementsList.AddRange(jobNameDomain.Value.Select( domain => new KeyValuePair<Regex, string>( new Regex("https?(://|&#x3a;&#x2f;&#x2f;)" + domain), "/" + jobNameDomain.Key + "/" + domain))); } } private static readonly string[] _replaceableApplicationMimiTypes = { "xhtml", "javascript", "atom", "rss", "rdf", "ecmascript", "soap", "dtd" }; private static readonly string[] _replaceableTextMimiTypes = { "css", "html", "javascript" }; public static bool IsContentTypeWithReplaceableLinks(string contentType) { return ((contentType.StartsWith("text/") && _replaceableTextMimiTypes.Any(contentType.Substring("text/".Length).Contains)) || ((contentType.StartsWith("application/") && _replaceableApplicationMimiTypes.Any(contentType.Substring("application/".Length).Contains)))); } public static string Execute(Stream input, string jobName) { using (var reader = new StreamReader(input)) { return reader.ReadToEnd().ReplaceAll(_replacements[jobName]); } } } }
e261fa3a0d474b2ac4b4fe09001607277f089805
C#
hmoss333/TommyTurtleRobot
/Assets/STEMDashScripts/TimeManager.cs
2.578125
3
using System; using System.Collections; using UnityEngine; using System.Collections.Generic; using SimpleJSON; using UnityEngine.SceneManagement; /********************************************************************** * * This class is used as the time manager. It uses the * singleton design pattern. At some point it may be better * to use Toolbox but for now singleton works. It is supposed * to initialize the AppEvent subclass, start and stop the timer * and initalizse the dates. * * Syntax: * Manager.Instance.<METHOD NAME> * * ********************************************************************/ public class TimeManager : Singleton<TimeManager> { protected TimeManager () {} // guarantee this will be always a singleton only - can't use the constructor! #region Private Variables private DateTime AppStarted; private DateTime AppEnded; private TimeSpan elapsedTime; //Used to calculated the total minutes private string activeUser; private string playerName; private string playerEmail; private bool timeStarted = false; private int index; private int playerCounter; private string appName = "Default"; //Public variable that is used to store the name of the game. private string gameData; private string gameMode; private float min; #endregion #region Public Variables public float time; #endregion public void initializeAppEvent(string appName, string gameMode) { this.appName = appName; activeUser = SaveAndLoad.dashEmail; playerName = PlayerPrefs.GetString("CurrentPlayer"); index = SaveAndLoad.listOfPlayers.IndexOf(playerName); playerEmail = playerName + "_" + SaveAndLoad.dashEmail; playerEmail = playerEmail.ToLower(); playerCounter = PlayerPrefs.GetInt("PlayerCounter" + index); gameData = ""; this.gameMode = gameMode; } public void init() { GameStatusEventHandler.startedGame += gameWasStarted; GameStatusEventHandler.stoppedGame += gameWasStopped; } void gameWasStarted() { if (LoginToPortal.Instance.userIsLoggedIn) { Debug.Log("Game has started"); if (!timeStarted) StartTimer(); } } void gameWasStopped() { Debug.Log("Game has stopped"); if(LoginToPortal.Instance.userIsLoggedIn) StopTimer(); } void Update() { if(timeStarted) { time += Time.deltaTime; } } //Used to check if the user has started playing //If the user has started playing, then the timer has started public void StartTimer() { if (!timeStarted) { Debug.Log("Adult Email: " + SaveAndLoad.dashEmail); Debug.Log("Child current player : " + SaveAndLoad.currentPlayerArr[0]); timeStarted = true; time = 0f; //Checks to see if the current parse user is null //If its not null, it starts the app event timer and passes all the necessary //values to it. Has to start when the game first loads. string mode; if (activeUser != null) { if (gameMode == "challenge") { PointHandler.init(); Debug.Log("Active Scene: " + SceneManager.GetActiveScene().name); mode = "Challenge"; } else { mode = "Freeplay"; } DateTime date = DateTime.Now; string Message; Message = playerName + " started playing " + appName + " " + mode + " at " + date.ToLocalTime().ToShortDateString() + " at " + date.ToLocalTime().ToShortTimeString(); WWWForm form = new WWWForm(); //Creates the form Debug.Log("Current Player: " + playerName); form.AddField("username", playerName); form.AddField("email", playerEmail); form.AddField("objectId", SaveAndLoad.dashObjectId); form.AddField("type", 0); form.AddField("appName", appName); form.AddField("message", Message); form.AddField("received", "false"); form.AddField("data", 0); form.AddField("gameData", ""); WWW www = new WWW(ServerURL.appEvent, form); //Sends the data to server StartCoroutine(WaitForRequest(www)); //Listen for the response AppStarted = DateTime.Now; Debug.Log("Start Time: " + AppStarted); // determineDate(AppStarted, activeUser.Username); } else { Debug.Log("User does not exist"); } } } public void saveScores() { int index = PlayerPrefs.GetInt(playerName); //Current index of the player var playerData = JSON.Parse(SaveAndLoad.currentPlayerArr[index]); string dateEarned = System.DateTime.Now.Month + "/" + System.DateTime.Now.Day + "/" + System.DateTime.Now.Year + " " + System.DateTime.Now.TimeOfDay.Hours + ":" + System.DateTime.Now.TimeOfDay.Minutes; playerData["correctPercentage"].AsFloat = PointHandler.correctPercentage; playerData["incorrectPercentage"].AsFloat = PointHandler.incorrectPercentage; playerData["dateEarned"].Value = dateEarned; playerData["completionTime"].Value = min.ToString(); SaveAndLoad.currentPlayerArr[index] = playerData.ToString(); /*loop through the dictionary and add it to array then pass the array to join and send to the server*/ gameData = "{"; gameData += "\"percentData\": [" + string.Join(",", SaveAndLoad.currentPlayerArr) + "]"; //Convert to JSON Array gameData += "}"; index++; if (index > 4) index = 0; PlayerPrefs.SetInt(playerName, index); SaveAndLoad.updateGameDataList(); Debug.Log("Saved"); } //Logs the total minutes the player has played the game //It tracks the dates and calculates the total minutes played. public void StopTimer() { if (activeUser != null) { if (timeStarted) { Debug.Log("Stop called"); PlayerPrefs.SetInt("timeStarted", 0); string ender = ""; timeStarted = false; float timePlayed = 0f; AppEnded = DateTime.Now; Debug.Log("End Time: " + AppEnded); elapsedTime = AppEnded - AppStarted; timePlayed = (float)elapsedTime.TotalMinutes; double minutes = Math.Round((double)timePlayed); string mode = ""; Debug.Log("End time from delta" + time); min = (float) Math.Round(time / 60f); //minutes stored using Time.Delta ender = minutes > 1 ? "minutes" : "minute"; if (gameMode == "challenge") { PointHandler.calculatePercentages(); saveScores(); Debug.Log("Game Data: " + gameData); mode = "Challenge"; } else { gameData = ""; mode = "Freeplay"; } Debug.Log("Total minutes: " + min); string Message = playerName + " stopped playing " + appName + " " + mode + " after " + min + " " + ender; WWWForm form = new WWWForm(); //Creates the form form.AddField("username", playerName); form.AddField("email", playerEmail); form.AddField("objectId", SaveAndLoad.dashObjectId); form.AddField("type", 0); form.AddField("appName", appName); form.AddField("message", Message); form.AddField("received", "true"); form.AddField("data", min.ToString()); form.AddField("gameData", gameData); //Debug.Log(gameData); PointHandler.resetPoints(); WWW www = new WWW(ServerURL.appEvent, form); //Sends the data to server StartCoroutine(WaitForRequest(www)); //Listen for the response Debug.Log("Stop Time: " + AppEnded); } } else { Debug.Log("User does not exist"); } } //Logs the total minutes the player has played the game //It tracks the dates and calculates the total minutes played. public void sendData(int correct, int incorrect) { if (activeUser != null) { if (timeStarted) { PlayerPrefs.SetInt("timeStarted", 0); string ender = ""; timeStarted = false; float timePlayed = 0f; AppEnded = DateTime.Now; Debug.Log("End Time: " + AppEnded); elapsedTime = AppEnded - AppStarted; timePlayed = (float)elapsedTime.TotalMinutes; double minutes = Math.Round((double)timePlayed); string mode = ""; float min = (float) Math.Floor((controlHours.childTimes[playerEmail] * 60.0f)); //minutes stored using Time.Delta //float min = (float) Math.Floor(time / 60f); //minutes stored using Time.Delta Debug.Log("Minutes in time manager: " + min); ender = minutes > 1 ? "minutes" : "minute"; if (gameMode == "challenge") { saveScores(); mode = "Challenge"; } else { gameData = ""; mode = "Drill"; } Debug.Log("Total minutes: " + min); string Message; Message = playerName + " stopped playing " + appName + " " + mode + " after " + min + " " + ender; WWWForm form = new WWWForm(); //Creates the form form.AddField("username", playerName); form.AddField("email", playerEmail); form.AddField("objectId", SaveAndLoad.dashObjectId); form.AddField("type", 0); form.AddField("appName", appName); form.AddField("message", Message); form.AddField("received", "true"); form.AddField("data", min.ToString()); form.AddField("gameData", gameData); //Debug.Log(gameData); WWW www = new WWW(ServerURL.appEvent, form); //Sends the data to server StartCoroutine(WaitForRequest(www)); //Listen for the response } } else { Debug.Log("User does not exist"); } } //Coroutine to determine if the was saved successfully or not IEnumerator WaitForRequest(WWW www) { yield return www; // check for errors if (www.error == null) { Debug.Log(www.text); } else { Debug.Log(www.error); } } }
c5e66cc5ea825048013e10c2608e9379fa05da7e
C#
marufn17/C-.NetFinalProject
/PassLock/Username.cs
2.6875
3
using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; namespace PassLock { public partial class Username : Form { public static SqlConnection sqlCon; public Username() { InitializeComponent(); } /* * will take back to Login page */ private void BackToLoginBtn_Click(object sender, EventArgs e) { this.Hide(); Login f1 = new Login(); f1.Show();//Login page shows } private void SubmitBtn_Click(object sender, EventArgs e) { try { Warning1_label.Visible = false; Warning2_label.Visible = false; sqlCon = new SqlConnection("Data Source=DESKTOP-BDDENA3;Initial Catalog=testdb;Integrated Security=true "); sqlCon.Open(); SqlDataAdapter sdata = new SqlDataAdapter("Select [Username] from [testdb].[dbo].[Users]" + " where Email='" + EmailTB.Text + "' and [FirstName] ='" + FirstNameTB.Text + "' and [LastName] ='" + LastNameTB.Text + "'", sqlCon); DataTable dataTable = new DataTable(); sdata.Fill(dataTable); string username = dataTable.Rows[0][0].ToString(); MessageBox.Show("Your username is " + username + ". Please use your username to login."); this.Hide(); PassLock.Login form1 = new PassLock.Login(); form1.Show(); } catch (System.IndexOutOfRangeException sioex) { Warning1_label.Visible = true; Warning2_label.Visible = true; } finally { sqlCon.Close(); } } } }
8a2897d26715539c893031f75cf4e29370accc79
C#
JannyM85/SparkleXrm
/spkl.fakes/Microsoft.Crm.Sdk.Fakes/FakeOrganzationService.cs
2.65625
3
using FakeItEasy; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; using System; using System.Collections.Generic; namespace Microsoft.Crm.Sdk.Fakes { public class FakeOrganzationService : IOrganizationService { #region Private memebers private IOrganizationService _realService; private List<OrganizationServiceStep> _operations = new List<OrganizationServiceStep>(); #endregion #region Properties public int CallCount { get; private set; } public IOrganizationService FakeService { get; set; } #endregion #region Constructors public FakeOrganzationService() : this(null) { } public FakeOrganzationService(IOrganizationService realService) { FakeService = A.Fake<IOrganizationService>(a => a.Strict()); _realService = realService; CallCount = 0; } #endregion #region Private Methods private void ThrowIncorrectStepType(string called, OrganizationServiceStep expectedCall) { string expectedCallName = "empty"; if (expectedCall.Associate!=null) { expectedCallName = "Associate"; } else if (expectedCall.Create!=null) { expectedCallName = "Create"; } else if (expectedCall.Delete !=null) { expectedCallName = "Delete"; } else if (expectedCall.Disassociate != null) { expectedCallName = "Disassociate"; } else if (expectedCall.Execute != null) { expectedCallName = "Execute"; } else if (expectedCall.RetrieveMultiple != null) { expectedCallName = "RetrieveMultiple"; } else if (expectedCall.Retrieve != null) { expectedCallName = "Retrieve"; } else if (expectedCall.Update != null) { expectedCallName = "Update"; } throw new Exception(String.Format("Fake Organization Service expected '{0}' but '{1}' was called", expectedCallName, called)); } private OrganizationServiceStep GetNextStep() { CallCount++; if (_operations.Count<CallCount) { throw new Exception(String.Format("Fake Organization Service has no more predefined steps at step {0}", CallCount)); } return _operations[CallCount-1]; } #endregion #region Public Methods public FakeOrganzationService ExpectAssociate(AssociateDelegate action) { _operations.Add(new OrganizationServiceStep() { Associate = action }); return this; } public FakeOrganzationService ExpectDisassociate(DisassociateDelegate action) { _operations.Add(new OrganizationServiceStep() { Disassociate = action }); return this; } public FakeOrganzationService ExpectCreate(CreateDelegate action) { _operations.Add(new OrganizationServiceStep() { Create = action }); return this; } public FakeOrganzationService ExpectDelete(DeleteDelegate action) { _operations.Add(new OrganizationServiceStep() { Delete = action }); return this; } public FakeOrganzationService ExpectExecute(ExecuteDelegate action) { _operations.Add(new OrganizationServiceStep() { Execute = action }); return this; } public FakeOrganzationService ExpectRetrieve(RetrieveDelegate action) { _operations.Add(new OrganizationServiceStep() { Retrieve = action }); return this; } public FakeOrganzationService ExpectRetrieveMultiple(RetrieveMultipleDelegate action) { _operations.Add(new OrganizationServiceStep() { RetrieveMultiple = action }); return this; } public FakeOrganzationService ExpectUpdate(UpdateDelegate action) { _operations.Add(new OrganizationServiceStep() { Update = action }); return this; } public void AssertExpectedCalls() { Assert.IsTrue(ExpectedCalls(), String.Format("FakeOrganizationService expected {0} calls, but only {1} were made", _operations.Count, CallCount)); } public bool ExpectedCalls() { return _operations.Count == CallCount; } public void ResetCalls() { CallCount = 0; } public Guid Create(Entity entity) { if (_realService != null) { CallCount++; return _realService.Create(entity); } if (entity == null) throw new ArgumentNullException("entity"); if (String.IsNullOrEmpty(entity.LogicalName)) throw new ArgumentNullException("LogicalName"); var nextStep = GetNextStep(); if (nextStep.Create == null) ThrowIncorrectStepType("Create", nextStep); return nextStep.Create(entity); } public Entity Retrieve(string entityName, Guid id, ColumnSet columnSet) { if (_realService != null) { CallCount++; return _realService.Retrieve(entityName, id, columnSet); } if (String.IsNullOrEmpty(entityName)) throw new ArgumentNullException("entityName"); if (id == Guid.Empty) throw new ArgumentNullException("id"); var nextStep = GetNextStep(); if (nextStep.Retrieve == null) ThrowIncorrectStepType("Retrieve", nextStep); return nextStep.Retrieve(entityName, id, columnSet); } public void Update(Entity entity) { if (_realService != null) { CallCount++; _realService.Update(entity); return; } if (entity == null) throw new ArgumentNullException("query"); if (entity.Id == Guid.Empty) throw new ArgumentNullException("Id"); if (string.IsNullOrEmpty(entity.LogicalName)) throw new ArgumentNullException("LogicalName"); var nextStep = GetNextStep(); if (nextStep.Update == null) ThrowIncorrectStepType("Update", nextStep); nextStep.Update(entity); } public void Delete(string entityName, Guid id) { if (_realService != null) { CallCount++; _realService.Delete(entityName, id); return; } if (String.IsNullOrEmpty(entityName)) throw new ArgumentNullException("entityName"); if (id == Guid.Empty) throw new ArgumentNullException("id"); var nextStep = GetNextStep(); if (nextStep.Delete == null) ThrowIncorrectStepType("Delete", nextStep); nextStep.Delete(entityName, id); } public OrganizationResponse Execute(OrganizationRequest request) { if (_realService != null) { CallCount++; return _realService.Execute(request); ; } if (request == null) throw new ArgumentNullException("request"); var nextStep = GetNextStep(); if (nextStep.Execute == null) ThrowIncorrectStepType("Execute", nextStep); return nextStep.Execute(request); } public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { if (_realService != null) { CallCount++; _realService.Associate(entityName, entityId, relationship, relatedEntities); return; } if (String.IsNullOrEmpty(entityName)) throw new ArgumentNullException("entityName"); if (entityId == Guid.Empty) throw new ArgumentNullException("entityId"); if (relationship == null) throw new ArgumentNullException("relationship"); if (relationship.SchemaName == null) throw new ArgumentNullException("SchemaName"); if (relatedEntities == null) throw new ArgumentNullException("relatedEntities"); if (relatedEntities.Count == 0) throw new Exception("relatedEntities empty"); var nextStep = GetNextStep(); if (nextStep.Associate == null) ThrowIncorrectStepType("Associate", nextStep); nextStep.Associate(entityName, entityId, relationship, relatedEntities); } public void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { if (_realService != null) { CallCount++; _realService.Disassociate(entityName, entityId, relationship, relatedEntities); return; } if (String.IsNullOrEmpty(entityName)) throw new ArgumentNullException("entityName"); if (entityId == Guid.Empty) throw new ArgumentNullException("entityId"); if (relationship == null) throw new ArgumentNullException("relationship"); if (relationship.SchemaName == null) throw new ArgumentNullException("SchemaName"); if (relatedEntities == null) throw new ArgumentNullException("relatedEntities"); if (relatedEntities.Count == 0) throw new Exception("relatedEntities empty"); var nextStep = GetNextStep(); if (nextStep.Disassociate == null) ThrowIncorrectStepType("Disassociate", nextStep); nextStep.Disassociate(entityName, entityId, relationship, relatedEntities); } public EntityCollection RetrieveMultiple(QueryBase query) { if (_realService != null) { CallCount++; return _realService.RetrieveMultiple(query); } if (query == null) throw new ArgumentNullException("query"); var nextStep = GetNextStep(); if (nextStep.RetrieveMultiple == null) ThrowIncorrectStepType("RetrieveMultiple", nextStep); return nextStep.RetrieveMultiple(query); } #endregion } }
4ec747c9bb5a3af234bbd9be532555fbc41be729
C#
Hap120/ClassFinder
/KidsClassFinder/KidsClass.cs
2.890625
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KidsClassFinder { public enum City { Redmond, Sammammish, Bellevue, Kirkland, Issaquah } public enum Timeframe { Spring, Summer, Fall, Winter, Yearround } public enum ClassType { Soccer, Swimming, Art, Dance, Gymnastics, Music } class KidsClass { #region Statics #endregion #region Properties [Key] public Timeframe Session { get; set; } public City Location { get; set; } public int Age { get; set; } public double Price { get; private set; } public string Address { get; set; } public int TotalSpots { get; private set; } public string Name { get; set; } public ClassType ClsType { get; set; } #endregion #region Methods public KidsClass( ClassType clType, Timeframe clSession, City clLocation, int clAge, double clPrice, string clAddress, int spotsTotal, string clName) { ClsType = clType; Session = clSession; Location = clLocation; Age = clAge; Price = clPrice; Address = clAddress; TotalSpots = spotsTotal; Name = clName; } #endregion } }
884f65a23e46392a2c3294fd69b14df1f7881419
C#
tingwei628/MCC
/Source/Compiler.cs
2.984375
3
using System; using System.Linq; using System.IO; namespace MCC { static class Compiler { static void Main(string[] args) { string inputfilename = "return_int.c"; if (args.Count() > 0) { inputfilename = args[0]; } if(!File.Exists(inputfilename)) { Console.WriteLine("File \"" + inputfilename + "\" is not available."); return; } string src = File.ReadAllText(inputfilename); Token[] tokens = Lexer.Tokenize(src); AbstractSyntaxTree ast = Parser.Parse(tokens); string outfilename = inputfilename.Replace(".c", ".s"); Generator.Write(outfilename, tokens, ast); } } }
481c2fb14278237fe5cc73cbc1e2b36a88ea64e8
C#
brian070597/HeladeriaRepositorio
/Heladeria/Heladeria/Server/Controllers/UsuariosController.cs
2.671875
3
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Heladeria.Shared.Modelos; using System.Security.Cryptography; using System.Text; namespace Heladeria.Server.Controllers { [ApiController] [Route("[controller]")] public class UsuariosController : ControllerBase { private readonly HeladeriaContext context; public UsuariosController(HeladeriaContext context) { this.context = context; } [HttpGet] public async Task<ActionResult<List<Usuario>>> Get() { try { return await context.Usuarios.ToListAsync(); } catch (Exception ex) { throw ex; } } [HttpGet("{id}", Name = "obtenerUsuario")] public async Task<ActionResult<Usuario>> Get(int id) { try { return await context.Usuarios.FirstOrDefaultAsync(x => x.Idusuario == id); } catch (Exception ex) { throw ex; } } [HttpPost] public async Task<ActionResult> Post(Usuario usuario) { try { context.Add(usuario); await context.SaveChangesAsync(); return new CreatedAtRouteResult("obtenerUsuario", new { Id = usuario.Idusuario, usuario }); } catch (Exception ex) { throw ex; } } [HttpPut] public async Task<ActionResult> Put(Usuario usuario) { try { context.Entry(usuario).State = EntityState.Modified; await context.SaveChangesAsync(); return NoContent(); } catch (Exception ex) { throw ex; } } [HttpDelete("{id}")] public async Task<ActionResult> Delete(int id) { try { var usuario = new Usuario { Idusuario = id }; context.Remove(usuario); await context.SaveChangesAsync(); return NoContent(); } catch (Exception ex) { throw ex; } } [HttpGet("{id}", Name = "logueoUsuario")] public async Task<ActionResult<Usuario>> Get(string nombre, string password ) { try { var pass = HashearPassword(password); return await context.Usuarios.FirstOrDefaultAsync(x => x.NombreUsuario == nombre && x.Contraseña == pass ); } catch (Exception ex) { throw ex; } } public static byte[] HashearPassword(string password) { return SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(password)); } } }
e9a68975a6781673d4d2f8cb97b4508ec7630cc8
C#
dracjump/ProyectoTallerAutosDavid2021
/ProyectoTallerAutos.Datos/Repositorios/Modelos/RepositorioTipoVehiculos.cs
2.765625
3
using ProyectoTallerAutos.Datos.Repositorios.Modelos.Interfaces; using ProyectoTallerAutos.Entidades.Entidades; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoTallerAutos.Datos.Repositorios.Modelos { public class RepositorioTipoVehiculos : IRepositorioTipoVehiculos { private readonly SqlConnection _sqlConnection; public RepositorioTipoVehiculos(SqlConnection sqlConnection) { _sqlConnection = sqlConnection; } public void Borrar(int id) { try { string cadenaComando = "DELETE FROM TiposDeVehiculos WHERE TipoDeVehiculoId=@id"; SqlCommand comando = new SqlCommand(cadenaComando, _sqlConnection); comando.Parameters.AddWithValue("@id", id); comando.ExecuteNonQuery(); } catch (Exception e) { throw new Exception(e.Message); }; } public bool EstaRelacionado(TipoVehiculo tipo) { try { var cadenaComando = "SELECT COUNT(*) FROM Modelos WHERE TipoDeVehiculoId=@id"; var comando = new SqlCommand(cadenaComando, _sqlConnection); comando.Parameters.AddWithValue("@id", tipo.TipoVehiculoId); int cantidadRegistros = (int)comando.ExecuteScalar(); if (cantidadRegistros > 0) { return true; } return false; } catch (Exception e) { throw new Exception(e.Message); } } public bool Existe(TipoVehiculo tipo) { try { SqlCommand comando; if (tipo.TipoVehiculoId == 0) { string cadenaComando = "SELECT TipoDeVehiculoId,Descripcion FROM TiposDeVehiculos WHERE Descripcion=@nombre"; comando = new SqlCommand(cadenaComando, _sqlConnection); comando.Parameters.AddWithValue("@nombre", tipo.Descripcion); } else { string cadenaComando = "SELECT TipoDeVehiculoId,Descripcion FROM TiposDeVehiculos WHERE Descripcion=@nombre AND TipoDeVehiculoId<>@id "; comando = new SqlCommand(cadenaComando, _sqlConnection); comando.Parameters.AddWithValue("@nombre", tipo.Descripcion); comando.Parameters.AddWithValue("@id", tipo.TipoVehiculoId); } SqlDataReader reader = comando.ExecuteReader(); return reader.HasRows; } catch (Exception e) { throw new Exception(e.Message); } } public List<TipoVehiculo> GetLista() { List<TipoVehiculo> lista = new List<TipoVehiculo>(); try { string cadenaComando = "select TipoDeVehiculoId, Descripcion from TiposDeVehiculos"; SqlCommand comando = new SqlCommand(cadenaComando, _sqlConnection); SqlDataReader reader = comando.ExecuteReader(); while (reader.Read()) { TipoVehiculo tipo = ConstruirTipoVehiculo(reader); lista.Add(tipo); } reader.Close(); return lista; } catch (Exception e) { throw new Exception(e.Message); } } private TipoVehiculo ConstruirTipoVehiculo(SqlDataReader reader) { return new TipoVehiculo { TipoVehiculoId = reader.GetInt32(0), Descripcion = reader.GetString(1), }; } public TipoVehiculo GetTipoPorId(int id) { throw new NotImplementedException(); } public void Guardar(TipoVehiculo tipo) { if (tipo.TipoVehiculoId == 0) //Si no extiste TIpo, entonces me va a agregar uno. {//Nuevo Tipo try { string cadenaComando = "INSERT INTO TiposDeVehiculos VALUES(@nombre)"; SqlCommand comando = new SqlCommand(cadenaComando, _sqlConnection); comando.Parameters.AddWithValue("@nombre", tipo.Descripcion); comando.ExecuteNonQuery(); cadenaComando = "SELECT @@IDENTITY"; comando = new SqlCommand(cadenaComando, _sqlConnection); tipo.TipoVehiculoId = (int)(decimal)comando.ExecuteScalar(); } catch (Exception e) { throw new Exception(e.Message); } } else {//Editar Tipo string cadenaComando = "UPDATE TiposDeVehiculos SET Descripcion=@nombre WHERE TipoDeVehiculoId=@id "; SqlCommand comando = new SqlCommand(cadenaComando, _sqlConnection); comando.Parameters.AddWithValue("@nombre", tipo.Descripcion); comando.Parameters.AddWithValue("@id", tipo.TipoVehiculoId); comando.ExecuteNonQuery(); } } } }
cac3d6e3a8cffc42108cb05cecf9d0a9c4391e91
C#
gjsduarte/TamTam.Trailers
/src/TamTam.Trailers.Services.YouTube/YoutubeVideoService.cs
2.5625
3
namespace TamTam.Trailers.Services.YouTube { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Google.Apis.Services; using Google.Apis.YouTube.v3; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Options; using TamTam.Trailers.Infrastructure; using TamTam.Trailers.Infrastructure.Extensions; using TamTam.Trailers.Infrastructure.Model; using TamTam.Trailers.Infrastructure.Services; using TamTam.Trailers.Services.YouTube.Options; public class YoutubeVideoService : IVideoService { #region Fields private readonly IMovieService movieService; private readonly IDistributedCache cache; private readonly YouTubeService youtubeService; private readonly DistributedCacheEntryOptions cacheOptions; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="YoutubeVideoService" /> class. /// </summary> /// <param name="movieService">The movie service.</param> /// <param name="cache">The current cache store.</param> /// <param name="options">The options.</param> public YoutubeVideoService(IMovieService movieService, IDistributedCache cache, IOptions<YoutubeOptions> options) { this.movieService = movieService; this.cache = cache; // TODO: Read this from options cacheOptions = new DistributedCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(5d) }; var initializer = new BaseClientService.Initializer { ApiKey = options.Value.ApiKey, ApplicationName = options.Value.ApplicationName }; youtubeService = new YouTubeService(initializer); } #endregion #region Public Methods and Operators /// <inheritdoc /> public async Task<IEnumerable<Video>> Search(string id) { // Fetch the movie with the specified id var movie = await movieService.Get(id); // Yeah, not very intelligent, but it does the job :) var query = $"{movie.Title} {movie.Year} trailer"; // Try getting the result from the cache var videos = await cache.GetAsJsonAsync<IEnumerable<Video>>(query).ToList(); if (videos == null) { var searchListRequest = youtubeService.Search.List("snippet"); searchListRequest.Q = query; searchListRequest.MaxResults = 50; searchListRequest.Type = "video"; // Call the search.list method to retrieve results matching the specified query term. var searchListResponse = await Policies.Retry.ExecuteAsync(() => searchListRequest.ExecuteAsync()); // Parse the results videos = searchListResponse.Items.Select(searchResult => new Video { Name = searchResult.Snippet.Title, Key = searchResult.Id.VideoId, Type = VideoType.YouTube }).ToList(); // Store the values in the cache await cache.SetAsJsonAsync(query, videos, cacheOptions); } return videos; } #endregion } }
88182f657032b70fd0d809cb2eb7e5a8fa5d7151
C#
waterstonemf/Windows
/docs/PE File Format/Sample/ConsoleApplication4/ConsoleApplication4/Program.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApplication4 { [Flags] enum NodeType { None = 0, Single = -1, Double = -2, Three = -4 } class Program { static void Main(string[] args) { NodeType t = NodeType.Single | NodeType.Three; if (t == NodeType.None) { Console.WriteLine("Hello None"); }else { Console.WriteLine(t.ToString()); } Console.Read(); } } }
c347a843da4e6124d9466357aa7ba56846a97d2b
C#
fodysuli/Lost-Cities
/Assets/Scripts/PlayerController.cs
2.578125
3
using UnityEngine; using System.Collections.Generic; using System.Collections; public class PlayerController : MonoBehaviour { public GameObject handLocation; public GameObject expeditionLocation; List<int> m_handCards; List<int>[] m_playedCards; public void Init() { GameObject obj = null; float xPos = 0.0f; m_handCards = new List<int> (); m_playedCards = new List<int>[5]; int x = 0; List<GameObject> expeditionBase = GameManager.instance.expeditionBasePrefab; expeditionBase.ForEach(delegate (GameObject basePrefab) { obj = Instantiate(basePrefab, expeditionLocation.transform) as GameObject; xPos = basePrefab.transform.localScale.x + 2.0f; Vector3 offset = new Vector3(xPos * x, 0.0f, 0.0f); obj.transform.position = expeditionLocation.transform.position + offset; }); } public void AddCard(int index) { GameObject card = GameManager.instance.m_deckManager.GetCard(index); card.SetActive(true); float xPos = card.transform.localScale.x + 1.0f; Vector3 offset = new Vector3(xPos * m_handCards.Count, 0.0f, 0.0f); card.transform.position = handLocation.transform.position + offset; Camera cam = GameObject.Find("Main Camera").GetComponent<Camera>(); Vector3 camRotation = cam.transform.rotation.eulerAngles; card.transform.rotation *= Quaternion.Euler(0.0f, camRotation.y + 180.0f, 0.0f); m_handCards.Add(index); } public void PlayCard(GameObject card) { m_handCards.Remove(GameManager.instance.m_deckManager.GetCardIndex(card)); RearrangeCard(); this.AddCard(GameManager.instance.m_deckManager.DrawCard()); GameManager.instance.EndTurn(); } void RearrangeCard() { int x = 0; GameObject card = null; Vector3 newPos; Vector3 offset; float xPos = 0.0f; for (x = 0; x < m_handCards.Count; x++) { card = GameManager.instance.m_deckManager.GetCard(m_handCards[x]); xPos = card.transform.localScale.x + 1.0f; offset = new Vector3(xPos * x, 0.0f, 0.0f); newPos = handLocation.transform.position + offset; card.GetComponent<Rigidbody>().MovePosition(newPos); } } }
fea0ee1d7e94973d1aa82124f130265a1c2055f1
C#
KaedeKasai/RoboSurvive
/RoboSurvive_demo0.9/Assets/Resources/YokoboriScripts/item.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class item : MonoBehaviour { string[] stone = new string[] { "Rock2","Rock3","Rock4" }; GameObject dropMaterial; GameObject dm; private float hard = 0.0f; private float hit = 0.0f; // Start is called before the first frame update void Start() { switch (this.gameObject.name) { case "rock1": hard = Random.Range(2,6); break; case "scrap": hard = 3; break; }; } // Update is called once per frame void Update() { } public static bool Probability(float fPer) { float fRate = UnityEngine.Random.value * 100.0f; if (fRate < fPer) { return true; } else { return false; } } public GameObject Drop(GameObject dropMaterial) { int x = Random.Range(0, 2); int z = Random.Range(0, 2); dm = Instantiate(dropMaterial, new Vector3( transform.position.x+x, transform.position.y, transform.position.z+z), Quaternion.identity); return dm; } private void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag == "Tool") { hit++; if (hit >= hard) { switch (this.name) { case "rock1": if (hard <= 0) { dropMaterial = (GameObject)Resources.Load(stone[0]); Drop(dropMaterial); dm.name = "rock"; if (Probability(60)) { dropMaterial = (GameObject)Resources.Load(stone[1]); Drop(dropMaterial); dm.name = "stone"; } if (Probability(30)) { dropMaterial = (GameObject)Resources.Load(stone[2]); Drop(dropMaterial); dm.name = "FrakedStone"; } Destroy(this.gameObject); } break; } hard--; } } } }
930de36579fa18d0a50c2692eefdd8bdb6a13b84
C#
mknizewski/SportStore
/SportStore.Domain/Concrete/EFDbInitializer.cs
2.765625
3
using SportStore.Domain.Entities; using SportStore.Domain.SqlFiles; using System; using System.Data.Entity; using System.IO; namespace SportStore.Domain.Concrete { /// <summary> /// Autor: Mateusz Kniżewski /// Opis: Klasa inicjalizująca bazę danych gdy jej nie ma /// Data: 17.10.15 /// </summary> public class EFDbInitializer : CreateDatabaseIfNotExists<EFDbContext> { /// <summary> /// Dane inicializujące podczas tworzenia bazy danych /// </summary> /// <param name="context">Zmienna bazowa</param> protected override void Seed(EFDbContext context) { var tablePath = AppDomain.CurrentDomain.BaseDirectory.Split(new string[] { "SportStore.Web" }, StringSplitOptions.RemoveEmptyEntries); string path = tablePath[0] + @"/SportStore.Domain/SqlFiles/Initialization"; var sqlFiles = Directory.GetFiles(path, "*.sql"); foreach (var file in sqlFiles) context.Database.ExecuteSqlCommand(File.ReadAllText(file)); //zdjęcia path = tablePath[0] + @"/SportStore.Domain/SqlFiles/Pictures"; var imageFiles = Directory.GetFiles(path, "*.jpg"); int iterator = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 3; j++) { var image = new items_picutures { Id_Item = (i + 1), PictureData = HelperClass.Img2Byte(imageFiles[iterator]), PictureMimeType = "picture/jpeg" }; iterator++; context.ItemsPictures.Add(image); } } var random = new Random(); //ilosc itemów w sklepach for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 11; j++) { var quantity = new items_quantity { Id_Shop = i, Id_Item = j, Quantity = random.Next(1, 50) }; context.ItemsQuantity.Add(quantity); } } context.SaveChanges(); } } }
9a311fcb8ab905c0d64796041b9b10abeb6d0211
C#
Clement-R/game_jam_template_2D
/Assets/Packages/Cake/Opera/Data/Sounds.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; namespace Cake.Opera.Data { [CreateAssetMenu(fileName = "Sounds", menuName = "Audio/Sounds", order = 0)] public class Sounds : ScriptableObject { public List<SFX> Values = new List<SFX>(); public SFXSound Get(SFXEvent p_event) { SFX entry = Values.FirstOrDefault(e => e.Event == p_event); if (entry == null) return null; return entry.Sound; } public SFXSound Get(string p_eventName) { SFX entry = Values.FirstOrDefault(e => e.Event.Value == p_eventName); if (entry == null) return null; return entry.Sound; } [ContextMenu("Populate")] private void Populate() { Type soundEventsType = typeof(SoundEvents); List<FieldInfo> eventsFields = soundEventsType.GetFields().ToList(); var values = eventsFields.Select(e => (string) e.GetValue(null)); List<string> currentValues = Values.Select(e => e.Event.Value).ToList(); // Find old values and remove them var oldValues = currentValues.Except(values); foreach (var eventName in oldValues) { var entry = Values.FirstOrDefault(e => e.Event.Value == eventName); Values.Remove(entry); } // Find missing values and create entries var missingValues = values.Except(currentValues); foreach (var value in missingValues) { Values.Add(new SFX(new SFXEvent(value))); } } } }
dab8cdc4bb62dc84b0eecb700fcd2ec6c5b18ebc
C#
Spoertm/ddstats-scraper
/DdstatsScraper/Program.cs
2.734375
3
using DdstatsScraper; using DdstatsScraper.Responses; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; Console.WindowWidth = 120; while (true) { uint playerId = 0; while (playerId == 0) { Console.Write("Enter your player ID and press enter: "); _ = uint.TryParse(Console.ReadLine(), out playerId); } Console.WriteLine($"\nFetching games for player with ID {playerId}..."); DdstatsResponse? response = await CacheHelper.GetPlayerData(playerId); if (response is null) { Console.WriteLine("Failed to obtain player data."); return; } Console.WriteLine($"Found {response.TotalGameCount} games for player '{response.PlayerName}'.{Environment.NewLine}"); if (response.TotalGameCount < 1) continue; Game[] games = response.Games .Where(g => g.Spawnset == "v3") .ToArray(); List<AllStatsResponse> statsList = RunAnalyzer.GetAllStats(games); for (int i = 0; i < statsList.Count; i++) Console.WriteLine($"{statsList[i].StatName,-24} {(statsList[i].StatResponse.Run == null ? "N/A" : $"https://ddstats.com/games/{statsList[i].StatResponse.Run?.Id}"),-32} {statsList[i].StatResponse.StatValue,20}"); Console.WriteLine(); }
42e0f2f71723b986f7154bbc1184b533e0abc809
C#
class-snct-rikitakelab/muphic
/muphic old version/LinkMake/Dialog/LinkFileWriter.cs
2.890625
3
using System; using System.Collections; using System.IO; using System.Text; using System.Windows.Forms; //TJ̒܂[ namespace muphic.LinkMake.Dialog { public class LinkFileWriter { ArrayList AnimalList; int Tempo; int Level; int Filenum; String Name; StreamWriter sw = null; public LinkFileWriter(ArrayList AnimalList, int tempo, String name, int filenum, int level) { this.AnimalList = AnimalList; this.Tempo = tempo; this.Name = name; this.Filenum = filenum; this.Level = level; } /// <summary> /// t@C݃\bh /// </summary> /// <param name="name">t@CɂȂ镶</param> /// <returns>ݐۂ</returns> public bool Write() { // t@C string filename = DecideFilename(Filenum); String[] code = {"A","B","C","D","E","F","G","H"}; // t@C擾Ɏsꍇ ݎs if(filename == null) return false; try { System.Console.WriteLine("muphicMDLt@C " + filename + " ֏o"); // ݃obt@̐ݒ sw = new StreamWriter(filename, false, Encoding.GetEncoding("Shift_JIS")); } catch(FileNotFoundException e) { // t@CI[vɎsꍇ ݎs MessageBox.Show("pIt@CJȂ"); return false; } int maxplace = 0; String str = ""; // sw.WriteLine(Name); sw.WriteLine(Level); sw.WriteLine(Tempo); //ől擾 for(int i=0; i<AnimalList.Count; i++) { Animal a = (Animal)AnimalList[i]; if (maxplace < a.place) { maxplace = a.place; } } int temp = 8; //1߂Ƃɏ for (int i = 0; i <= maxplace/8; i++) { for (int j = 0; j < AnimalList.Count; j++) { Animal a = (Animal)AnimalList[j]; if (a.place < temp && a.place > temp-9) { str += code[a.place%8] + " " + (a.code-1) + " "; } } temp += 8; sw.WriteLine(str); str = ""; } // N[Y sw.Close(); // ݐ return true; } /// <summary> /// ^ꂽ񂩂t@C𐶐郁\bh /// </summary> /// <param name="filename"></param> /// <returns>t@C</returns> public static string DecideFilename(int filenum) { if (filenum < 10) { for(int i=10; i<37564; i++) { // 0珇Ԃ"_ԍ.msd"݂邩`FbNĂ string filename = "LinkData\\QuesPatt_" + i.ToString() + ".mdl"; // ݂Ȃt@C΂Ɍ if( !File.Exists(filename) ) return filename; } } else { string filename = "LinkData\\QuesPatt_" + filenum.ToString() + ".mdl"; return filename; } return null; } } }
12a1d3bd8089a3e49f00a90d21b701b0da9376b7
C#
bigmlcom/bigml-csharp
/BigML/BatchPrediction/BigMLClientBatchPredictions.cs
2.734375
3
using System.Threading.Tasks; namespace BigML { public partial class Client { /// <summary> /// Create a batch prediction using supplied arguments. /// </summary> public Task<BatchPrediction> CreateBatchPrediction(BatchPrediction.Arguments arguments) { return Create<BatchPrediction>(arguments); } /// <summary> /// Create a BatchPrediction. /// </summary> /// <param name="dataset">A DataSet instance</param> /// <param name="name">The name you want to give to the new batch predictions. </param> /// <param name="arguments">Specifies the id of the field that you want to predict.</param> public Task<BatchPrediction> CreateBatchPrediction(DataSet dataset, string name = null, BatchPrediction.Arguments arguments = null) { arguments = arguments ?? new BatchPrediction.Arguments(); if (!string.IsNullOrWhiteSpace(name)) arguments.Name = name; arguments.DataSet = dataset.Resource; return Create<BatchPrediction>(arguments); } /// <summary> /// List all the Batch Predictions /// </summary> public Query<BatchPrediction.Filterable, BatchPrediction.Orderable, BatchPrediction> ListBatchPredictions() { return new BatchPredictionListing(List<BatchPrediction>); } } }
e4a1c5c6509acafde851d8297d4818a584318fd1
C#
bnynova/C_Sharp
/Telerik_Academy_HW/3. OperatorsExpressionsStatements/11. ModifyingToHoldValueAtPosition/ModifyingToHoldValueAtPosition.cs
2.53125
3
using System; class ModifyingToHoldValueAtPosition { static void Main() { int n = int.Parse(Console.ReadLine()); int p = int.Parse(Console.ReadLine()); int v = int.Parse(Console.ReadLine()); int mask = 1 << p; ..... } }
1b8aea6842e751448e68e76f322ff2f688abcbab
C#
LordJZ/Kamilla
/Kamilla/Network/Viewing/ViewerItemEventArgs.cs
2.9375
3
using System; namespace Kamilla.Network.Viewing { /// <summary> /// Represents the method that handles an event /// related to a <see cref="Kamilla.Network.Viewing.ViewerItem"/>. /// </summary> /// <param name="sender"> /// The object that raised the event. /// </param> /// <param name="e"> /// Information about the event. /// </param> public delegate void ViewerItemEventHandler(object sender, ViewerItemEventArgs e); /// <summary> /// Provides data for an event related to a <see cref="Kamilla.Network.Viewing.ViewerItem"/>. /// </summary> public sealed class ViewerItemEventArgs : EventArgs { ViewerItem m_item; /// <summary> /// Initializes a new instance of <see cref="Kamilla.Network.Viewing.ViewerItemEventArgs"/> /// for the specified <see cref="Kamilla.Network.Viewing.ViewerItem"/>. /// </summary> /// <param name="item"> /// The <see cref="Kamilla.Network.Viewing.ViewerItem"/> related to the event. /// </param> public ViewerItemEventArgs(ViewerItem item) { m_item = item; } /// <summary> /// Gets the <see cref="Kamilla.Network.Viewing.ViewerItem"/> related to the event. /// </summary> public ViewerItem Item { get { return m_item; } } } }
e5b381869af7753a140e0e4c1f8116d16ddf72f2
C#
tamirdresher/Ignite2017_MSAIDevBootcamp_Pre-day
/examples/06_Vision/01_vision/Bot/Services/CustomVisionService.cs
2.84375
3
using Newtonsoft.Json; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace Bot.Services { /// <summary> /// Service to call the Custom Vision API /// </summary> public class CustomVisionService { private static readonly HttpClient Client = new HttpClient(); private readonly string _endpoint; private readonly string _key; public CustomVisionService() { _endpoint = $"https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/{ConfigurationManager.AppSettings["CustomVisionProjectId"]}/image"; _key = ConfigurationManager.AppSettings["CustomVisionKey"]; } //public async Task<CustomVisionResponse> Analyze(string imageUrl) //{ // // Fetch image // var image = await Client.GetByteArrayAsync(imageUrl); // // Prepare message // var request = new HttpRequestMessage(HttpMethod.Post, _endpoint); // request.Headers.Add("Prediction-Key", _key); // request.Content = new ByteArrayContent(image) // { // Headers = {ContentType = new MediaTypeHeaderValue("application/octet-stream")} // }; // // Submit // var response = await Client.SendAsync(request); // response.EnsureSuccessStatusCode(); // return JsonConvert.DeserializeObject<CustomVisionResponse>( // await response.Content.ReadAsStringAsync()); //} } public class CustomVisionResponse { public List<Prediction> Predictions { get; set; } public Prediction TopPrediction { get { return Predictions.OrderByDescending(item => item.Probability).First(); } } } public class Prediction { public string Tag { get; set; } public double? Probability { get; set; } } }
46ba5f7cf1f8deb4371376e818522d6aa0221e82
C#
greenvox/FlowHelpers
/FlowHelpers/Models/DateTime/WeekRange.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FlowHelpers.Models { public class WeekRangeResponse { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string RangeLabel { get; set; } } public class WeekRange { public int WeekOfYear { get; set; } public int YearToSearch { get; set; } public static WeekRangeResponse ProcessRequest(WeekRange req) { //var currentDate = DateTime.Today; //var currentYear = currentDate.Year; var currentYear = req.YearToSearch; var weekOfYear = req.WeekOfYear; var firstOfYear = new DateTime(currentYear, 1, 1); Console.WriteLine("1st of Year: " + firstOfYear.ToLongDateString()); var firstDayOfYear = firstOfYear.DayOfWeek; if (firstDayOfYear.ToString() != "Monday") { do { firstOfYear = firstOfYear.AddDays(-1); firstDayOfYear = firstOfYear.DayOfWeek; } while (firstDayOfYear.ToString() != "Monday"); } //Find week; var daysToAdd = (weekOfYear - 1) * 7; var dateRangeStart = firstOfYear.AddDays(daysToAdd); var dateRangeEnd = dateRangeStart.AddDays(6); var rangeLabel = (dateRangeStart.ToShortDateString() + " - " + (dateRangeEnd.ToShortDateString())); WeekRangeResponse response = new WeekRangeResponse(); response.StartDate = dateRangeStart; response.EndDate = dateRangeEnd; response.RangeLabel = rangeLabel; return response; } } }
0ed451458dadd4e2cc339cb98ff72fbaefd137f4
C#
NightOwl888/J2N
/tests/J2N.Tests/Text/TestCharArrayCharSequence.cs
2.71875
3
using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace J2N.Text { public class TestCharArrayCharSequence : CharSequenceTestBase<CharArrayCharSequence> { public override void SetUp() { base.SetUp(); target = new CharArrayCharSequence(CharArray1); nullTarget = new CharArrayCharSequence(null); equalTarget = new CharArrayCharSequence(CharArray1); unequalTarget = new CharArrayCharSequence(CharArray2); emptyTarget = new CharArrayCharSequence(string.Empty.ToCharArray()); } [Test] public void TestValue() { Assert.IsNotNull(target.Value); Assert.AreEqual(CharArray1, target.Value); Assert.IsNull(nullTarget.Value); } [Test] public virtual void TestEqualityOperators() { Assert.IsTrue(target == equalTarget); Assert.IsTrue(equalTarget == target); Assert.IsFalse(target == unequalTarget); Assert.IsFalse(unequalTarget == target); Assert.IsTrue(target == CharArray1); Assert.IsTrue(CharArray1 == target); Assert.IsFalse(target == CharArray2); Assert.IsFalse(CharArray2 == target); Assert.IsTrue(nullTarget == (char[])null); Assert.IsTrue((char[])null == nullTarget); Assert.IsFalse(target != equalTarget); Assert.IsFalse(equalTarget != target); Assert.IsTrue(target != unequalTarget); Assert.IsTrue(unequalTarget != target); Assert.IsTrue(target != CharArray2); Assert.IsTrue(CharArray2 != target); Assert.IsFalse(target != CharArray1); Assert.IsFalse(CharArray1 != target); Assert.IsFalse(nullTarget != (char[])null); Assert.IsFalse((char[])null != nullTarget); } } }
cfa82221abe90d5841e0b3a9f25add9c5dc1791e
C#
nofuture-git/31g
/trunk/Code/NoFuture/Rand/Law/Procedure/Civil/US/Judgment/JudgmentAsMatterOfLaw.cs
2.84375
3
using System; using NoFuture.Rand.Law.Attributes; using NoFuture.Rand.Law.US; namespace NoFuture.Rand.Law.Procedure.Civil.US.Judgment { /// <summary> /// Capacity of a judge to withdraw a case from a jury when there is no meaningful question of law /// </summary> /// <remarks> /// <![CDATA[ "a method for protecting neutral principles of law from powerful forces /// outside the scope of law - compassion and prejudice" Rutherford v. Illinois Central R.R.(1960) ]]> /// </remarks> /// <remarks> /// Is not a verdict since its not rendered by a jury. /// </remarks> [Aka("directed verdict", "motion for judgment as a matter of law")] public class JudgmentAsMatterOfLaw : CivilProcedureBase, IJudgment { public Func<ILegalPerson[], ILegalPerson> GetSubjectPerson { get; set; } = lps => null; /// <summary> /// Where unlikely fades into the impossible /// </summary> public Predicate<ILegalConcept> IsCaseWeakBeyondReason { get; set; } = lc => false; public override bool IsValid(params ILegalPerson[] persons) { if (!IsCourtAssigned()) return false; var subjectPerson = GetSubjectPerson(persons); if (subjectPerson == null) { AddReasonEntry($"{nameof(GetSubjectPerson)} returned nothing"); return false; } var title = subjectPerson.GetLegalPersonTypeName(); if (!TryGetCauseOfAction(subjectPerson, out var subject)) return false; if (IsCaseWeakBeyondReason(subject)) { AddReasonEntry($"{title} {subjectPerson.Name}, {nameof(IsCaseWeakBeyondReason)} is true"); return true; } return false; } } }
94be8919665f5452fe0815cbe4111e6b10209713
C#
RayWangQvQ/Ray.EssayNotes.Blazor
/BlazorRepository/EmployeeRepository.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BlazorDomain; using Microsoft.EntityFrameworkCore; namespace BlazorRepository { public class EmployeeRepository : IEmployeeRepository { private readonly MyDbContext _myDbContext; public EmployeeRepository(MyDbContext myDbContext) { this._myDbContext = myDbContext; } public async Task<Employee> AddAsync(Employee employee) { await _myDbContext.AddAsync<Employee>(employee); var count = await _myDbContext.SaveChangesAsync(); if (count != 1) throw new Exception("新增失败"); return employee; } public async Task DeleteAsync(int id) { var e = await _myDbContext.Employees.FindAsync(id); _myDbContext.Employees.Remove(e); var count = await _myDbContext.SaveChangesAsync(); } public async Task<IList<Employee>> GetForDepartmentAsync(int departmentId) { return await _myDbContext.Employees .Where(x => x.DepartmentId == departmentId).ToListAsync(); } public async Task<Employee> GetOneAsync(int id) { return await _myDbContext.FindAsync<Employee>(id); } public async Task UpdateAsync(Employee employee) { _myDbContext.Attach(employee); _myDbContext.Employees.Update(employee); var count = await _myDbContext.SaveChangesAsync(); } } }
646453e90f4b8873ae51238464bcddb01e16903e
C#
Barkoff/WpfApp
/WpfApp/Model/Door.cs
3
3
using System.Windows; using GalaSoft.MvvmLight.Command; namespace WpfApp.Model { /// <summary> /// Дверь /// </summary> public class Door : Detail, IDoor { public RelayCommand OpenCommand { get; set; } public Door() { NativeName = "Дверь"; Weight = 40; OpenCommand = new RelayCommand(Open); IsOpened = false; } private string doorState; public string DoorState { get { return doorState; } set { doorState = value; RaisePropertyChanged(()=>DoorState); } } private bool _isOpened; public bool IsOpened { get { return _isOpened; } set { _isOpened = value; RaisePropertyChanged(()=>IsOpened); DoorState = IsOpened ? "открыта" : "закрыта"; } } public void Open() { IsOpened = !IsOpened; MessageBox.Show(string.Join(" ", Name, DoorState)); } } }
068f13090840f97af1301d43f8603da239f7e113
C#
cobalto/aspnet-core-social-network
/Libraries/Green.Services/Comments/CommentService.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using Green.Core.Data; using Green.Core.Domain.Comments; namespace Green.Services.Comments { public class CommentService { #region Fields private readonly IRepository<Comment> _commentRepository; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:Green.Services.Comments.CommentService"/> class. /// </summary> /// <param name="commentRepository">Comment repository.</param> public CommentService(IRepository<Comment> commentRepository) { this._commentRepository = commentRepository; } #endregion #region Methods /// <summary> /// Inserts the comment. /// </summary> /// <param name="comment">Comment.</param> public void InsertComment(Comment comment) { if (comment == null) throw new ArgumentNullException(nameof(comment)); _commentRepository.Insert(comment); } /// <summary> /// Gets all comments. /// </summary> /// <returns>The all comments.</returns> public IList<Comment> GetAllComments() { return _commentRepository.Table.ToList(); } /// <summary> /// Gets the comment by identifier. /// </summary> /// <returns>The comment by identifier.</returns> /// <param name="commentId">Comment identifier.</param> public Comment GetCommentById(int commentId) { if (commentId == 0) return null; return _commentRepository.GetById(commentId); } /// <summary> /// Gets the comment by GUID. /// </summary> /// <returns>The comment by GUID.</returns> /// <param name="commentGuid">Comment GUID.</param> public Comment GetCommentByGuid(Guid commentGuid) { if (commentGuid == Guid.Empty) return null; var query = from com in _commentRepository.Table where com.Key == commentGuid orderby com.Id select com; var comment = query.FirstOrDefault(); return comment; } /// <summary> /// Updates the comment. /// </summary> /// <param name="comment">Comment.</param> public void UpdateComment(Comment comment) { if (comment == null) throw new ArgumentNullException(nameof(comment)); _commentRepository.Update(comment); } #endregion } }
62fc700669756b1e187bd2da87ffe0058cf0a819
C#
josdan23/ProyectoBigonHnos
/ProyectoBigonHnos/data/ProvinciaDao/ProvinciaDaoListImpl.cs
2.53125
3
using ProyectoBigonHnos.data.ProvinciaDao; using ProyectoBigonHnos.dominio; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoBigonHnos.data.ProvinciaDao { class ProvinciaDaoListImpl : IProvinciaDAO { private static List<Provincia> todasLasProvincias = new List<Provincia>(); private static int idContador = 0; public void actualizar(Provincia t) { for (int i = 0; i < todasLasProvincias.Count; i++) { if (todasLasProvincias[i].IdProvincia == t.IdProvincia) { todasLasProvincias[i] = t; } } } public void eliminar(int id) { for (int i = 0; i < todasLasProvincias.Count; i++) { if (todasLasProvincias[i].IdProvincia == id) { todasLasProvincias.RemoveAt(i); } } } public Provincia leerPorId(int id) { for ( int i = 0; i < todasLasProvincias.Count; i++) { if ( todasLasProvincias[i].IdProvincia == id) { return todasLasProvincias.ElementAt(i); } } return null; } public List<Provincia> listarTodos() { return todasLasProvincias; } public void registrar(Provincia t) { t.IdProvincia = idContador; idContador++; todasLasProvincias.Add(t); } } }
fc004f22bd8fff9fb2a944c81306e6c8f3472c5e
C#
sureshbandi/socioboard-core
/SocioBoard/SocioboardAPI/Model/CompanyProfilesRepository.cs
2.578125
3
using Api.Socioboard.Helper; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Api.Socioboard.Model { public class CompanyProfilesRepository { public bool addAccount(Domain.Socioboard.Domain.CompanyProfiles compnayProfiles) { bool IsSuccess = false; //Creates a database connection and opens up a session using (NHibernate.ISession session = SessionFactory.GetNewSession()) { //After Session creation, start Transaction. using (NHibernate.ITransaction transaction = session.BeginTransaction()) { //proceed action, to save data. session.Save(compnayProfiles); transaction.Commit(); IsSuccess = true; }//End Transaction }//End session return IsSuccess; } public bool updateAccount(Domain.Socioboard.Domain.CompanyProfiles compnayProfiles) { bool IsUpdated = false; using (NHibernate.ISession session = SessionFactory.GetNewSession()) { //After Session creation, start Transaction. using (NHibernate.ITransaction transaction = session.BeginTransaction()) { try { // Proceed action to Update Data. // And Set the reuired paremeters to find the specific values. session.CreateQuery("Update companyprofiles set CompanyName =:CompanyName,FbProfileId =:FbProfileId,TwitterProfileId =:TwitterProfileId,LinkedinProfileId=:LinkedinProfileId,InstagramProfileId=:InstagramProfileId,YoutubeProfileId=:YoutubeProfileId,GPlusProfileId=:GPlusProfileId,TumblrProfileId=:TumblrProfileId,UserId=:UserId where Id = :Id ") .SetParameter("CompanyName", compnayProfiles.Companyname) .SetParameter("FbProfileId", compnayProfiles.Fbprofileid) .SetParameter("TwitterProfileId", compnayProfiles.Twitterprofileid) .SetParameter("LinkedinProfileId", compnayProfiles.Linkedinprofileid) .SetParameter("InstagramProfileId", compnayProfiles.Instagramprofileid) .SetParameter("YoutubeProfileId", compnayProfiles.Youtubeprofileid) .SetParameter("GPlusProfileId", compnayProfiles.Gplusprofileid) .SetParameter("TumblrProfileId", compnayProfiles.Tumblrprofileid) .SetParameter("UserId", compnayProfiles.Userid) .SetParameter("Id", compnayProfiles.Id) .ExecuteUpdate(); transaction.Commit(); IsUpdated = true; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); // return 0; } return IsUpdated; }//End Transaction }//End session } public Domain.Socioboard.Domain.CompanyProfiles getProfiles(string Name) { Domain.Socioboard.Domain.CompanyProfiles companyProfile = null; //Creates a database connection and opens up a session using (NHibernate.ISession session = SessionFactory.GetNewSession()) { //After Session creation, start Transaction. using (NHibernate.ITransaction transaction = session.BeginTransaction()) { NHibernate.IQuery query = session.CreateQuery("from companyprofiles where CompanyName = :CompanyName"); query.SetParameter("CompanyName", Name); List<Domain.Socioboard.Domain.CompanyProfiles> result = (List<Domain.Socioboard.Domain.CompanyProfiles>)query.Enumerable(); companyProfile = result[0]; }//End Transaction }//End session return companyProfile; } public List<string> getCompanyNames() { List<string> companyNames = new List<string>(); //Creates a database connection and opens up a session using (NHibernate.ISession session = SessionFactory.GetNewSession()) { //After Session creation, start Transaction. using (NHibernate.ITransaction transaction = session.BeginTransaction()) { //Proceed action, to Get all FacebookAccount. NHibernate.IQuery query = session.CreateQuery("from companyprofiles"); foreach (Domain.Socioboard.Domain.CompanyProfiles Profile in query.Enumerable()) { companyNames.Add(Profile.Companyname); } }//End Transaction }//End session return companyNames; } } }
2128968d4911c25ab3307b2c893f204489ca3308
C#
OmarMoataz/Speaker-Identification
/Recorder/Encoder.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Accord.DirectSound; using System.IO; using Accord.Audio; using Accord.Audio.Formats; namespace Recorder.Recorder { class Encoder : BaseRecorder { private WaveEncoder encoder; private MemoryStream _stream; public MemoryStream stream { get { return _stream; } set { _stream = value; } } private IAudioSource _source; public IAudioSource source { get { return _source; } set { _source = value; } } private float[] _current; public float[] current { get { return _current; } set { _current = value; } } private int _duration; public int duration { get { return _duration; } set { _duration = value; } } public override bool IsRunning() { return this.source.IsRunning; } public Encoder(EventHandler<NewFrameEventArgs> NewFrame, EventHandler<AudioSourceErrorEventArgs> AudioSourceError) { AudioDeviceCollection audioDevices = new AudioDeviceCollection(AudioDeviceCategory.Capture); AudioDeviceInfo INfo = null; foreach (var item in audioDevices) { INfo = item; } // Create capture device this.source = new AudioCaptureDevice(INfo.Guid) { // Listen on 22050 Hz DesiredFrameSize = FRAME_SIZE, SampleRate = SAMPLE_RATE, // We will be reading 16-bit PCM Format = SampleFormat.Format16Bit }; // Wire up some events source.NewFrame += NewFrame; source.AudioSourceError += AudioSourceError; // Create buffer for wavechart control this.current = new float[source.DesiredFrameSize]; // Create stream to store file this.stream = new MemoryStream(); this.encoder = new WaveEncoder(stream); } public override void Start() { this.duration = 0; this.source.Start(); } public override void Stop() { if (this.source != null) { // If we were recording this.source.SignalToStop(); this.source.WaitForStop(); Array.Clear(this.current, 0, current.Length); } } public void addNewFrame(Signal signal) { // Save current frame signal.CopyTo(current); // Save to memory this.encoder.Encode(signal); // Update counters this.duration += signal.Duration; this.samples += signal.Samples; this.frames += signal.Length; } public void Save(Stream fileStream) { if (this.stream != null) { this.stream.WriteTo(fileStream); fileStream.Close(); } } } }
98be418ad2af74ba2458dab340eb9f164ef41fd4
C#
tiagopsd/CarteiraDigital
/CarteiraDigital.Domain/Models/Validations/Result.cs
2.890625
3
using CarteiraDigital.Domain.Models.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace CarteiraDigital.Domain.Models { public class Result<T> : IResult<T> where T : class { public bool Success { get; private set; } public List<string> Messages { get; private set; } public T Model { get; private set; } public Result() { Messages = new List<string>(); } public Result<T> AddError(string message) { Success = false; Messages.Add(message); return this; } public Result<T> AddSuccess(T model, string message = "") { Model = model; Success = true; Messages.Add(message); return this; } public Result<T> AddMessage(string message) { Messages.Add(message); return this; } public static Result<T> BuildError(string message) => new Result<T> { Success = false, Messages = new List<string> { message } }; public static Result<T> BuildError(List<string> messages) => new Result<T> { Success = false, Messages = messages }; public static Result<T> BuildError(string message, Exception error) => new Result<T> { Success = false, Messages = new List<string> { $"Message: {message}", $"BaseException : {error.GetBaseException().Message}", $"StackTrace: {error.GetBaseException().StackTrace} " } }; public static Result<T> BuildSucess(T model, string message = "") => new Result<T> { Model = model, Success = true, Messages = new List<string> { message } }; } }
1718596529dc2089a1bdaeb079de5416255381c9
C#
dzadnip/Monthly-LeetCoding-Challenge
/Trie/Trie/Trie.cs
3.234375
3
using System; using System.Collections.Generic; using System.Text; namespace Trie { // Copied from discussion area public class Trie { private readonly TrieNode _root; public Trie() { _root = new TrieNode(); } public void Insert(string word) { _root.Insert(word, 0); } public bool Search(string word) { return _root.Search(word, 0); } public bool StartsWith(string word) { return _root.StartsWith(word, 0); } } }
5ec28c48e6410d80abe6d1febedbfd35e6d13450
C#
SquallB/Check_n_Cook
/Check_n_Cook/Model/AbstractModel.cs
3.078125
3
using Check_n_Cook.Events; using Check_n_Cook.Views; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// Contains all the common operations for models. Here contains the views, and operations to add, remove and refresh them. /// </summary> namespace Check_n_Cook.Model { public class AbstractModel { /// <summary> /// The views /// </summary> private List<View> views; /// <summary> /// Initializes a new instance of the <see cref="AbstractModel"/> class. /// </summary> public AbstractModel() { this.views = new List<View>(); } /// <summary> /// Adds the view. /// </summary> /// <param name="view">The view.</param> public void AddView(View view) { this.views.Add(view); } /// <summary> /// Removes the view. /// </summary> /// <param name="view">The view.</param> public void RemoveView(View view) { this.views.Remove(view); } /// <summary> /// Refreshes the views. /// </summary> /// <param name="e">The e.</param> public void RefreshViews(Event e) { foreach (View view in this.views) { view.Refresh(e); } } } }
75dc1a03d2f95a9687c245cff872f7b1cbb98203
C#
gjurgica/Forum
/Forum different version/Forum 2.0/Forum.DataAccess/Repositories/CategoryRepository.cs
2.96875
3
using Forum.DataAccess.Interfaces; using Forum.DomainClasses.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Forum.DataAccess.Repositories { public class CategoryRepository : BaseRepository, IRepository<Category> { public CategoryRepository(ForumDbContext context) : base(context) { } public int Delete(string Id) { Category category = _context.Categories.FirstOrDefault(c => c.Id == Id); if (category == null) { return -1; } _context.Remove(category); return _context.SaveChanges(); } public IEnumerable<Category> GetAll() { return _context.Categories.Include(c => c.Threads).ThenInclude(t => t.Posts); } public Category GetById(string Id) { return _context.Categories.FirstOrDefault(c => c.Id == Id); } public int Insert(Category entity) { _context.Categories.Add(entity); return _context.SaveChanges(); } public int Update(Category entity) { Category category = _context.Categories.FirstOrDefault(c => c.Id == entity.Id); category.Title = entity.Title; return _context.SaveChanges(); } //public int AddThreadToTheCategory(string categoryId, Thread thread) //{ // Category category = GetById(categoryId); // category.Threads.ToList().Add(thread); // return _context.SaveChanges(); //} } }
6c352fecfa9340263feb1d91f3b468631bd39f10
C#
danhQuQu/Programming-techniques
/Form4.cs
2.53125
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 LogIn { public partial class Class : Form { scheduleEntities1 SE = new scheduleEntities1(); private string[] ROOM = new string[100]; private string[] SPACE = new string[100]; private string[] NOTE = new string[100]; private string[] ID = new string[100]; private int lenRoom; int index = 0; public Class() { InitializeComponent(); } private void Form4_Load(object sender, EventArgs e) { showHeader(); var result = from c in SE.Rooms select new { phong = c.Phong, cap = c.Capacity, note = c.Note,id = c.ID }; var data = result.ToList(); for (int i = 0; i < data.Count; i++) { this.ROOM[i] = data[i].phong; this.SPACE[i] = data[i].cap; this.NOTE[i] = data[i].note; this.ID[i] = Convert.ToString(data[i].id); } for (int i = 0; i < data.Count; i++) { ListViewItem eVent = new ListViewItem(ID[i]); eVent.SubItems.Add(new ListViewItem.ListViewSubItem(eVent, ROOM[i])); eVent.SubItems.Add(new ListViewItem.ListViewSubItem(eVent, SPACE[i])); eVent.SubItems.Add(new ListViewItem.ListViewSubItem(eVent, NOTE[i])); this.lstRoom.Items.Add(eVent); } } private void showHeader() { this.lstRoom.Columns.Add("ID", 50, HorizontalAlignment.Left); this.lstRoom.Columns.Add("ROOM", 75, HorizontalAlignment.Left); this.lstRoom.Columns.Add("CAPACITY", 100, HorizontalAlignment.Left); this.lstRoom.Columns.Add("NOTE", 250, HorizontalAlignment.Left); } //---------------------------------Add Buttom---------------------------------------// private void btnAdd_Click(object sender, EventArgs e) { //ADD to DATABASE Room room = new Room() { Phong = this.txtRoom.Text, Capacity = this.txtCapacity.Text, Note = txtNote.Text }; SE.Rooms.Add(room); SE.SaveChanges(); int id = room.ID; ListViewItem eVent = new ListViewItem(Convert.ToString(id)); eVent.SubItems.Add(new ListViewItem.ListViewSubItem(eVent, this.txtRoom.Text)); eVent.SubItems.Add(new ListViewItem.ListViewSubItem(eVent, this.txtCapacity.Text)); eVent.SubItems.Add(new ListViewItem.ListViewSubItem(eVent, this.txtNote.Text)); this.lstRoom.Items.Add(eVent); Clear(); index++; } //--------------------------------------------------------------------------------// //---------------------------------Update Event-------------------------------------// private void listView1_Click(object sender, EventArgs e) { this.txtID.Text = this.lstRoom.SelectedItems[0].SubItems[0].Text; this.txtRoom.Text = this.lstRoom.SelectedItems[0].SubItems[1].Text; this.txtCapacity.Text = this.lstRoom.SelectedItems[0].SubItems[2].Text; this.txtNote.Text = this.lstRoom.SelectedItems[0].SubItems[3].Text; } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { } //------------------------------------------------------------------------------------// //---------------------------------Clear text----------------------------------------// private void Clear() { this.txtRoom.Text = ""; this.txtCapacity.Text = ""; this.txtNote.Text = ""; this.txtID.Text = ""; } private void btnDel_Click(object sender, EventArgs e) { int id = Convert.ToInt32(this.txtID.Text); Room room = SE.Rooms.Where(b => b.ID == id).FirstOrDefault(); SE.Rooms.Remove(room); SE.SaveChanges(); for (int i = 0; i < lstRoom.Items.Count; i++) { if (lstRoom.Items[i].Selected) { lstRoom.Items[i].Remove(); i--; } } Clear(); } private void btnUpdate_Click(object sender, EventArgs e) { Controller cl = new Controller(); this.lstRoom.SelectedItems[0].SubItems[1].Text = this.txtRoom.Text; this.lstRoom.SelectedItems[0].SubItems[2].Text = this.txtCapacity.Text; this.lstRoom.SelectedItems[0].SubItems[3].Text = this.txtNote.Text; string phong = this.txtRoom.Text; string cap = this.txtCapacity.Text; string note = this.txtNote.Text; string id = this.txtID.Text; cl.edit(id, phong, cap, note); Clear(); } private void label2_Click(object sender, EventArgs e) { } } }
2205dc147fc2cb1ceef2a98f6111136ce41acfa7
C#
t2wain/learn-algo
/AlgoLib/Knapsack/Sack.cs
3.25
3
using System; using System.Collections.Generic; using System.Text; namespace AlgoLib.Knapsack { public class Sack { public int Capacity { get; set; } public List<Item> AllItems { get; } = new List<Item>(); public List<Item> Items { get; } = new List<Item>(); public int TotalWeight { get; protected set; } public double TotalValue { get; protected set; } public int RemainCapacity { get { var r = this.Capacity - this.TotalWeight; return r > 0 ? r : 0; } } public void AddItem(Item i) { this.TotalWeight += i.Weight; this.TotalValue += i.Value; this.Items.Add(i); } public void AddItem(IEnumerable<Item> items) { foreach (var i in items) this.AddItem(i); } public void SetContent(Sack s) { this.Items.Clear(); this.Items.AddRange(s.Items); this.Capacity = s.Capacity; this.TotalValue = s.TotalValue; this.TotalWeight = s.TotalWeight; } public void Reset(int capacity) { this.Capacity = capacity; this.TotalValue = 0; this.TotalWeight = 0; this.Items.Clear(); } } }
4cf3d4d31ca8fc9e741a1156a332ee47420e8333
C#
davetapson/PrisonConsoleApp
/PrisonConsoleApp/Program.cs
3.203125
3
using System; namespace PrisonConsoleApp { class Program { static void Main(string[] args) { Batch batch = new(); // bad name. Could be PrisonManager PrisonEngine... something. Console.WriteLine(""); Console.WriteLine("Welcome to Prison. You can check in, but you can never leave."); Console.WriteLine(""); bool carryOn = true; string input; while (carryOn) { WriteInstructions(); input = Console.ReadLine(); switch (input) { case "a": case "Add P": batch.AddPrisoner(); break; case "b": case "Remove P": batch.RemovePrisoner(); break; case "c": case "Add S": batch.AddStaff(); break; case "d": case "Remove S": batch.RemoveStaff(); break; case "e": case "List P": batch.ListPrisoners(); break; case "f": case "List S": batch.ListStaff(); break; case "g": case "Number P": batch.CountPrisoners(); break; case "h": case "Number S": batch.CountStaff(); break; case "i": case "Calculate Wage Bill": batch.CalculateWageBill(); break; case "j": case "Prisoners who should be set free": batch.PrisonersWhoShouldBeLetFree(); break; case "k": case "Staff with next birthday": batch.StaffWithNextBirthday(); break; case "l": case "Prisoner List sorted by release date": batch.PrisonersByReleaseDate(); break; case "m": case "Count of staff by Job Type": batch.CountOfStaffByJobType(); break; case "x": carryOn = false; break; default: Console.WriteLine($"Instruction {input} is not recognised."); Console.WriteLine(""); break; }; } } private static void WriteInstructions() { // these can be extended to cover the above, but I'd not bother. Console.WriteLine(""); Console.WriteLine("_______________________________________"); Console.WriteLine("To add prisoner, enter 'Add P'."); Console.WriteLine("To remove prisoner, enter 'Remove P'."); Console.WriteLine("To add prisoner, enter 'Add S'."); Console.WriteLine("To remove prisoner, enter 'Remove S'."); Console.WriteLine(""); Console.WriteLine("To display prisoners, enter 'List P'."); Console.WriteLine("To display staff, enter 'List S'."); Console.WriteLine(""); Console.WriteLine("Enter 'x' to exit."); Console.WriteLine("_______________________________________"); Console.WriteLine(""); } } }
318b70473e69c71e955479e2c36b13d68000ea48
C#
Mohanee/Cab_Invoice_Generator_Problem
/CabInvoiceGenerator/InvoiceSummary.cs
3.546875
4
using System; using System.Collections.Generic; using System.Text; namespace CabInvoiceGenerator { class InvoiceSummary { int no_of_rides; double totalFare, averageFare_perRide; /// <summary> /// Constructor to set value of no_of_rides and totalFare variables /// </summary> /// <param name="no_of_rides">Total number of rides</param> /// <param name="totalFare">total fare for all rides</param> public InvoiceSummary(int no_of_rides, double totalFare) { this.no_of_rides = no_of_rides; this.totalFare = totalFare; } /// <summary> /// Calculating average fare from total rides and total fare /// </summary> public void CalculateAverageFare_perRide() { this.averageFare_perRide = (totalFare / no_of_rides); } /// <summary> /// Overriding ToString() method to return number of rides, total fare and average fare per ride all /// into a single string /// </summary> /// <returns>single string with all values separated by comma</returns> public override string ToString() => this.no_of_rides+","+this.totalFare+","+this.averageFare_perRide; } }
2d1eea9836fb9ada7822809da14074ca5e0ce64f
C#
Adrado/SisifoNotes
/SisifoNotes.Lib.DA.EFCore/SisifoNotesDbSet.cs
2.65625
3
using Microsoft.EntityFrameworkCore; using SisifoNotes.Lib.Core; using SisifoNotes.Lib.Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SisifoNotes.Lib.DA.EFCore { public abstract class SisifoNotesDbSet<T> : IDbSet<T> where T : Entity { internal SisifoNotesContext DbContext { get; set; } internal DbSet<T> DbSet { get; set; } public T Add(T entity) { DbSet.Add(entity); DbContext.SaveChanges(); return entity; } public bool Delete(Guid id) { var entityToRemove = DbSet.Find(id); if (entityToRemove == null) return false; DbSet.Remove(entityToRemove); DbContext.SaveChanges(); return true; } public IQueryable<T> GetAll() { return DbSet; } public T Update (T entity) { DbSet.Update(entity); DbContext.SaveChanges(); return entity; } } }
7e2c929ae0722cf16f712df8090f35c6e44022bd
C#
Darklight437/1st-year-game-prototype-2
/Assets/_Scripts/Behaviour Tree/SequenceBehaviour.cs
3.046875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; /* * class SequenceBehaviour * child class of Behaviour * * compound behaviour tree node that keeps executing * child nodes unitl one returns FAILURE * * author: Bradley Booth, Academy of Interactive Entertainment, 2017 */ public class SequenceBehaviour : Behaviour { //list of children to execute public List<Behaviour> children = new List<Behaviour>(); //position of node that returned pending, used to resume the node private int pendingI = 0; /* * Execute * overrides Behaviour's Update() * * calls upon children to run until one returns FAILURE in which case it also returns FAILURE * returns SUCCESS if no nodes return FAILURE * * @returns BehaviourReturn - depends on what the condition node is checking for */ public override BehaviourReturn Execute() { if (children.Count > 0) { //iterate through children or the latest child at the last iteration //get the size of the children list int childSize = children.Count; //iterate through all children, running the logic of the selector for (int i = pendingI; i < childSize; i++) { //store the child in a temp value Behaviour child = children[i]; BehaviourReturn val = child.Execute(); //pause the compound node and return PENDING if (val == BehaviourReturn.PENDING) { pendingI = i; return BehaviourReturn.PENDING; } else if (val == BehaviourReturn.FAILURE) { pendingI = 0; //a node returned FAILURE, stop and return FAILURE return BehaviourReturn.FAILURE; } } //no nodes returned FAILURE, stop and return SUCCESS pendingI = 0; return BehaviourReturn.SUCCESS; } else { //the compound node was improperly initialised return BehaviourReturn.NONE; } } }
07e93e5c10feac722729a7fdb3f2d72b9aca017e
C#
kpro1999/SlimIOCP
/SlimIOCP/SlimIOCP.Shared/MessageBufferPool.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SlimIOCP { internal class MessageBufferPool<T> where T : MessageBuffer { int clearBufferId = -1; readonly int poolAmount; readonly Queue<T> pool; readonly BufferManager bufferManager; readonly MessageBufferProducer<T> producer; internal MessageBufferPool(MessageBufferProducer<T> messageProducer) : this(messageProducer, 5, 1024, 1024, 1024) { } internal MessageBufferPool(MessageBufferProducer<T> messageProducer, int maxBuffers, int chunkSize, int chunksPerBlock, int maxPooled) { #if DEBUG if (messageProducer == null) { throw new ArgumentNullException("messageProducer"); } #endif poolAmount = maxPooled; pool = new Queue<T>(maxPooled); producer = messageProducer; bufferManager = new BufferManager(maxBuffers, chunkSize, chunksPerBlock); // Pre-allocate the amount of maxPooled objects we want to have T preAllocated; for (var i = 0; i < poolAmount; ++i) { if (tryAllocate(out preAllocated)) { if (!TryPush(preAllocated)) { //TODO: Error } } else { //TODO: Error } } } internal bool TryPop(out T message) { lock (pool) { if (pool.Count > 0) { message = pool.Dequeue(); return true; } } return tryAllocate(out message); } internal bool TryPush(T message) { #if DEBUG if (message == null) { throw new ArgumentNullException("message"); } if (!Object.ReferenceEquals(message.BufferManager, bufferManager)) { throw new ArgumentException("Message does not belong to this pool", "message"); } #endif if (clearBufferId == message.BufferId) { message.Destroy(); message.ClearBuffer(); producer.Return(message); } else { message.Reset(); lock (pool) { pool.Enqueue(message); } } return true; } bool tryAllocate(out T message) { int bufferId; int bufferOffset; int bufferSize; byte[] bufferHandle; if (bufferManager.TryAllocateBuffer(out bufferId, out bufferOffset, out bufferSize, out bufferHandle)) { message = producer.Get(); message.SetBuffer(bufferManager, bufferHandle, bufferId, bufferOffset, bufferSize); message.BufferAssigned(); return true; } message = null; return false; } } }
ae08b17f4764f6aed3c17255e240126aa129fc00
C#
haruncanatali/Not_Giris_Otomasyonu
/NotKayitSistemi/OgrenciListesi.cs
2.625
3
using NotKayitSistemi.Model; 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 NotKayitSistemi { public partial class OgrenciListesi : Form { AppDbContext context = new AppDbContext(); List<ListeDbo> liste = new List<ListeDbo>(); public OgrenciListesi() { InitializeComponent(); } private void OgrenciListesi_Load(object sender, EventArgs e) { foreach (var item in context.Tbl_Student.ToList()) { liste.Add(new ListeDbo { NameAndSurname = item.Name+" "+item.Surname, Tckn = item.Tckn }); } foreach (var item in liste) { listeLbx.Items.Add(item.NameAndSurname + "," + item.Tckn); } } private void secBtn_Click(object sender, EventArgs e) { string value = listeLbx.Items[listeLbx.SelectedIndex].ToString().Split(',').ToArray()[1].ToString(); var user = context.Tbl_Student.FirstOrDefault(c=>c.Tckn == value); if (user!=null) { EgitmenForm f1 = new EgitmenForm(); f1.tcGirisTxt.Text = user.Tckn; f1.sinav1GirisTxt.Text = user.Exam_1.ToString(); f1.sinav2GirisTxt.Text = user.Exam_2.ToString(); f1.sinav3GirisTxt.Text = user.Exam_3.ToString(); f1.Show(); this.Hide(); } else { MessageBox.Show("Lütfen seçim yapınız.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public class ListeDbo { public string NameAndSurname { get; set; } public string Tckn { get; set; } } }
ceebfd020164d34ac7d54708d218716fcd8f25b5
C#
vladmikhbond/BookListDemo
/BookLibrary/Book.cs
2.734375
3
using System; namespace BookLibrary { public class Book { public Book(int id, string title, string authors) { Id = id; Authors = authors; Title = title; } public int Id { set; get; } public string Title { set; get; } public string Authors { set; get; } } }
36742350beb021ddb10378ccfe7712b51ea24a4a
C#
strider3029/Hex-to-Decimal
/HexToDecimal/HexToDecimal.cs
3.9375
4
using System; using System.IO; namespace HexToDecimal { class HexToDecimal { static int Main(string[] args) { // Check the argument and file exists if (args.Length == 0 || !File.Exists(args[0])) { Console.Write("You failed to specify the file to read, or entered a non existant file path.\nPlease try again with the file name as the first argument."); return 0; } using (StreamReader reader = File.OpenText(args[0])) { while (!reader.EndOfStream) { string line = reader.ReadLine(); if (null == line) continue; if ("" == line) continue; PrintHexToDecimal(line); } } return 0; } static void PrintHexToDecimal(string hexString) { int convertedDecimal = Convert.ToInt32(hexString, 16); Console.WriteLine(convertedDecimal); } } }
e5220748b94c2d153b516189bce409824b3a127f
C#
ivan-azbukin/Dictator
/Dictator/Rocket.cs
3.734375
4
using System; using System.Collections.Generic; using System.Linq; namespace Dictator { public class Rocket { /// <summary> /// Коллекция всех боеприпасов /// </summary> private List<int> _ammo; /// <summary> /// Массив с максимальным номером боеприпаса на каждом из уровней /// </summary> private List<int> _borders; private readonly int _maxValue = 108; public Rocket() { _ammo = Enumerable.Range(1, _maxValue).ToList(); GetBorders(); } /// <summary> /// Вычисляем значение максимального элемента на каждом из уровней /// </summary> private void GetBorders() { _borders = new List<int>(); var acc = 2; _borders.Add(1); while (_borders.Last() < _maxValue) { _borders.Add(_borders[^1] + acc); acc++; } } /// <summary> /// Возвращает номер отсека, в котором находится боеприпас. /// Отсеки нумеруются с 1 /// </summary> /// <param name="ammoNumber">Номер боеприпаса</param> /// <returns></returns> public int GetAmmoLevel(int ammoNumber) { if (ammoNumber < 1) throw new ArgumentException("Ammo number must be greater or equal then 1"); if (ammoNumber > 108) throw new ArgumentException("Ammo number must be less or equal then 108"); return _borders.FindIndex(item => item >= ammoNumber) + 1; } } }
d1c27237d9f884419a11f64455ce21e180212e77
C#
andreimihailescu/ConsoleApp
/LINQ/BookShelf.cs
3.125
3
using System.Collections.Generic; namespace LINQ { public class BookShelf { private IEnumerable<Book> Books = new Book[] { new Book() { Title = "C# programming", Genre = "Educational", Price = 5 }, new Book() { Title = "Java programming", Genre = "Educational", Price = 4 }, new Book() { Title = "Titanic", Genre = "Romance", Price = 3 }, new Book() { Title = "Grown Ups", Genre = "Comedy", Price = 3 } }; public IEnumerable<Book> GetBooks() { return Books; } } }
e6d9c732667f6fae0e071b6ec1d7705c50fa0f93
C#
Al-Hurr/WeatherApp
/WeatherApp/Models/RequestClass.cs
2.796875
3
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace WeatherApp.Models { public static class RequestClass { public const string _api = "89c47b39-a986-4876-bfad-613d50650288"; static string _lat { get; set; } static string _lon { get; set; } static string _lang { get; set; } static string _extra { get; set; } static string _url = ""; public static WeatherInfo GetWeather(string lat, string lon, string lang, string extra) { _url = $"https://api.weather.yandex.ru/v2/forecast?lat={lat}&lon={lon}&lang={lang}&extra={extra}"; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_url); httpWebRequest.Method = "GET"; httpWebRequest.Headers["X-Yandex-API-Key"] = _api; HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); string response; using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { response = streamReader.ReadToEnd(); } JObject valuePairs = JObject.Parse(response); WeatherInfo weatherInfo = new WeatherInfo() { CityName = valuePairs["geo_object"]["locality"]["name"].ToString(), Now = DateTime.Parse(valuePairs["now_dt"].ToString()), Temp = valuePairs["fact"]["temp"].ToString(), FeelLike = valuePairs["fact"]["feels_like"].ToString(), Сondition = WeatherInfo.GetCondition(valuePairs["fact"]["condition"].ToString()), WindSpeed = valuePairs["fact"]["wind_speed"].ToString(), WindDir = WeatherInfo.GetWindDir(valuePairs["fact"]["wind_dir"].ToString()), PressureMm = valuePairs["fact"]["pressure_mm"].ToString(), Humidity = valuePairs["fact"]["humidity"].ToString(), Daytime = WeatherInfo.GetDayTime(valuePairs["fact"]["daytime"].ToString()), Season = WeatherInfo.GetSeason(valuePairs["fact"]["season"].ToString()), PrecType = WeatherInfo.GetPrecType(valuePairs["fact"]["prec_type"].ToString()), Cloudness = WeatherInfo.GetCloudness(valuePairs["fact"]["cloudness"].ToString()) }; return weatherInfo; } } }
45493b561383244784d0b4c8059356dc32b58f8e
C#
iNeverSleeeeep/NPOI-For-Unity
/NPOI.SS.Util/SSCellRange.cs
2.859375
3
using NPOI.SS.UserModel; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; namespace NPOI.SS.Util { /// For POI internal use only /// /// @author Josh Micich public class SSCellRange<K> : ICellRange<K>, IEnumerable<K>, IEnumerable where K : ICell { internal class ArrayIterator<D> : IEnumerator<D>, IDisposable, IEnumerator { private D[] _array; private int _index; public D Current { get { if (_index >= _array.Length) { throw new ArgumentNullException(_index.ToString(CultureInfo.CurrentCulture)); } return _array[_index++]; } } object IEnumerator.Current { get { return Current; } } public ArrayIterator(D[] array) { _array = array; _index = 0; } public bool MoveNext() { return _index < _array.Length; } public void Remove() { throw new NotSupportedException("Cannot remove cells from this CellRange."); } public void Reset() { } public void Dispose() { } } private int _height; private int _width; private K[] _flattenedArray; private int _firstRow; private int _firstColumn; public K TopLeftCell => _flattenedArray[0]; public K[] FlattenedCells => (K[])_flattenedArray.Clone(); public K[][] Cells { get { Type type = _flattenedArray.GetType(); K[][] result = (K[][])Array.CreateInstance(type, _height); type = type.GetElementType(); for (int num = _height - 1; num >= 0; num--) { K[] destinationArray = (K[])Array.CreateInstance(type, _width); int sourceIndex = _width * num; Array.Copy(_flattenedArray, sourceIndex, destinationArray, 0, _width); } return result; } } public int Height => _height; public int Width => _width; public int Size => _height * _width; public string ReferenceText { get { CellRangeAddress cellRangeAddress = new CellRangeAddress(_firstRow, _firstRow + _height - 1, _firstColumn, _firstColumn + _width - 1); return cellRangeAddress.FormatAsString(); } } private SSCellRange(int firstRow, int firstColumn, int height, int width, K[] flattenedArray) { _firstRow = firstRow; _firstColumn = firstColumn; _height = height; _width = width; _flattenedArray = flattenedArray; } public static SSCellRange<K> Create(int firstRow, int firstColumn, int height, int width, List<K> flattenedList, Type cellClass) { int count = flattenedList.Count; if (height * width != count) { throw new ArgumentException("Array size mismatch."); } K[] array = (K[])Array.CreateInstance(cellClass, count); array = flattenedList.ToArray(); return new SSCellRange<K>(firstRow, firstColumn, height, width, array); } public K GetCell(int relativeRowIndex, int relativeColumnIndex) { if (relativeRowIndex < 0 || relativeRowIndex >= _height) { throw new IndexOutOfRangeException("Specified row " + relativeRowIndex + " is outside the allowable range (0.." + (_height - 1) + ")."); } if (relativeColumnIndex < 0 || relativeColumnIndex >= _width) { throw new IndexOutOfRangeException("Specified colummn " + relativeColumnIndex + " is outside the allowable range (0.." + (_width - 1) + ")."); } int num = _width * relativeRowIndex + relativeColumnIndex; return _flattenedArray[num]; } public IEnumerator<K> GetEnumerator() { return new ArrayIterator<K>(_flattenedArray); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } }
14d578c45514a152738cf8fdaff7719b7abcb090
C#
rongguoxu/NCrawler
/src/NCrawler.HtmlProcessor/RegexSubstitution.cs
2.8125
3
using System; using System.Text.RegularExpressions; using NCrawler.HtmlProcessor.Interfaces; namespace NCrawler.HtmlProcessor { public class RegexSubstitution : ISubstitution { private readonly Lazy<Regex> _match; private readonly string _replacement; public RegexSubstitution(Regex match, string replacement) { _match = new Lazy<Regex>(() => match, true); _replacement = replacement; } public string Substitute(string original, CrawlStep crawlStep) { return _match.Value.Replace(original, _replacement); } } }
d950e84a6a235d5289becbdf6704fe263c7a2362
C#
GuzarevichJulia/MPP.Tracer
/TracerLibrary/ThreadInfo.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyTracer { public class ThreadInfo { public Stack<MethodDescriptor> methodStack = new Stack<MethodDescriptor>(); public List<MethodDescriptor> methodList= new List<MethodDescriptor>(); public int time; public void PushMethod(MethodDescriptor item) { if (methodStack.Count > 0) { MethodDescriptor previousMethod = methodStack.Peek(); methodStack.Push(item); previousMethod.insertedMethod.Add(methodStack.Peek()); } else { methodStack.Push(item); methodList.Add(methodStack.Peek()); } } public void PopMethod(DateTime endTime) { methodStack.Peek().elapsedTime = endTime.Subtract(methodStack.Peek().startTime).TotalMilliseconds; methodStack.Pop(); } public double GetThreadTime() { double result = 0; foreach (MethodDescriptor method in this.methodList) { result = result + method.elapsedTime; } return result; } } }
03d8444bb17b9337550f17b9e9196b1f70572687
C#
skotlowski/Learning
/C#/Course/Methods/Methods/Program.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Methods { class Program { static void Main(string[] args) { SayHi("Mike", 32); SayHi("John", 54); SayHi("Jim", 23); Console.ReadLine(); } static void SayHi(string name, int age) { Console.WriteLine("Hello " + name + " you are " +age); } } }
fc45ad1ca4cb194e723a2227870fcf08c80f9e0b
C#
LinaVera/Ejercicios2
/Ejercicios2/1.maximo.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicios2 { class maximo { private static void Main(string[] args) { Console.WriteLine("ingrese numero 1"); int.TryParse(Console.ReadLine(), out int n1); Console.WriteLine("ingrese numero 2"); int.TryParse(Console.ReadLine(), out int n2); int res = res = (n1 > n2) ? n1 : n2; Console.WriteLine("El maximo de los dos numeros es: {0}", res); } } }
8a92ea12749bfce8a9c106c66ff699555c6ff0ee
C#
Mfeliciano778/holbertonschool-csharp
/0x09-csharp-linear_algebra/33-inverse_2D/33-inverse_2D.cs
3.71875
4
using System; /// <summary> A class containing a public method called Inverse2D </summary> class MatrixMath { /// <summary> To find the inverse of a 2d matrix </summary> /// <param name="matrix">The first matrix</param> /// <returns>inversed matrix, else -1</returns> public static double[,] Inverse2D(double[,] matrix) { double[,] err = { { -1 } }; if (matrix == null || matrix.GetLength(0) != 2 || matrix.GetLength(1) != 2) return (err); double determinant = matrix[0, 0] * matrix[1, 1] - -1 * matrix[0, 1] * -1 * matrix[1, 0]; if (determinant == 0) return (err); double[,] result = new double[2, 2]; result[0, 0] = Math.Round(matrix[1, 1] / determinant, 2); result[0, 1] = Math.Round(-1 * matrix[0, 1] / determinant, 2); result[1, 0] = Math.Round(-1 * matrix[1, 0] / determinant, 2); result[1, 1] = Math.Round(matrix[0, 0] / determinant, 2); return (result); } }
8f77aa31bb063ae1dc0170f34138d644fbdddb63
C#
milkyway112/izdavanje-automobila
/Projekat/Rezervacija.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace Projekat { [Serializable] class Rezervacija { int idAutomobila; int idKupca; DateTime datumOd; DateTime datumDo; double cena; public Rezervacija() { idAutomobila = -1; idKupca = -1; datumOd = DateTime.ParseExact("01/01/0001", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); datumDo = DateTime.ParseExact("01/01/0001", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); cena = 0; } public Rezervacija(int idAutomobila, int idKupca, DateTime datumOd, DateTime datumDo, double cena) { this.idAutomobila = idAutomobila; this.idKupca = idKupca; this.datumOd = datumOd; this.datumDo = datumDo; this.cena = cena; } public int IdAutomobila { get { return idAutomobila; } set { idAutomobila = value; } } public int IdKupca { get { return idKupca; } set { idKupca = value; } } public DateTime DatumOd { get { return datumOd; } set { datumOd = value; } } public DateTime DatumDo { get { return datumDo; } set { datumDo = value; } } public double Cena { get { return cena; } set { cena = value; } } public override string ToString() { return "ID Kupca: " + idKupca + ", " + datumOd.ToString("dd/MM/yy") + " - " + datumDo.ToString("dd/MM/yy"); } public string ToStringZaKupca() { string automobil = ""; FileStream fs = File.OpenRead("automobili.pol"); BinaryFormatter bf = new BinaryFormatter(); List<Automobil> ispisAutomobila = bf.Deserialize(fs) as List<Automobil>; for (int i = 0; i < ispisAutomobila.Count; i++) { if (ispisAutomobila[i].Id == idAutomobila) { automobil += ispisAutomobila[i].ToStringZaKupca(); } } fs.Close(); return automobil + ": " + datumOd.ToString("dd/MM/yy") + " - " + datumDo.ToString("dd/MM/yy"); } } }
8be66aa925976cbf9ced3727f37eb9005800fc53
C#
craftingcheetah/Inspiration
/Color.cs
2.875
3
using System; public class Color { public string Name; public int Value; public void ChangeRandomValue(int maxValue) { Value = new Random().Next(0, maxValue); } }
e296e068296fcd7baf639c8c5ba77b1347a2f217
C#
rasouza1982/RepositoryPattern
/RepositoryPattern.Infrastructure/IPersistRepository.cs
2.5625
3
using System; using System.Collections.Generic; namespace RepositoryPattern.Infrastructure { public interface IPersistRepository<TEntity> where TEntity : class { void Add(TEntity entity); void Add(IEnumerable<TEntity> items); void Update(TEntity entity); void Delete(TEntity entity); void Delete(IEnumerable<TEntity> entities); } }
12a1ac8a8731cbd9a1e56e07a386ba24f0d7ba02
C#
caoth/BandwidthDelayAlgorithms
/SRAS/NetworkSimulator/NetworkSimulator/RoutingComponents/CommonAlgorithms/FordFulkerson.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetworkSimulator.NetworkComponents; namespace NetworkSimulator.RoutingComponents.CommonAlgorithms { class FordFulkerson { private Topology _Topology; private BreadthFirstSearch _BFS; private const double MaxValue = double.MaxValue; private Dictionary<Link, double> _backupResidualBandwidthCopy; public FordFulkerson(Topology topology) { _Topology = topology; Initialize(); } //private Dictionary<Link, double> _UsingBandwidthCopy; private void Initialize() { _BFS = new BreadthFirstSearch(_Topology); //_UsingBandwidthCopy = new Dictionary<Link, double>(); _backupResidualBandwidthCopy = new Dictionary<Link, double>(); } private void BackupTopology() { //_UsingBandwidthCopy.Clear(); _backupResidualBandwidthCopy.Clear(); foreach (var link in _Topology.Links) { //_UsingBandwidthCopy[link] = link.UsingBandwidth; _backupResidualBandwidthCopy[link] = link.ResidualBandwidth; } } private void RestoreTopology() { foreach (var link in _Topology.Links) { //link.UsingBandwidth = _UsingBandwidthCopy[link]; link.ResidualBandwidth = _backupResidualBandwidthCopy[link]; } } public double ComputeMaxFlow(Node source, Node destination) { BackupTopology(); var maxFlow = MaxFlow(source, destination); RestoreTopology(); return maxFlow; } private double MaxFlow(Node nodeSource, Node nodeTerminal) { var flow = 0d; var path = _BFS.FindPath(nodeSource, nodeTerminal); while (path.Count > 0) { var minCapacity = MaxValue; foreach (var link in path) { if (link.ResidualBandwidth < minCapacity) minCapacity = link.ResidualBandwidth; } if (minCapacity == MaxValue || minCapacity < 0) throw new Exception("minCapacity " + minCapacity); AugmentPath(path, minCapacity); flow += minCapacity; path = _BFS.FindPath(nodeSource, nodeTerminal); } return flow; } private void AugmentPath(IEnumerable<Link> path, double minCapacity) { foreach (var link in path) { link.UsingBandwidth += minCapacity; } } public List<Link> FindMinCutSet(Node source, Node destination) // caoth redo //public List<Link> FindMinCutSetOld(Node source, Node destination) { BackupTopology(); double flow = MaxFlow(source, destination); var sCut = new List<Node>(); var tCut = new List<Node>(); var minCutSet = new List<Link>(); // find sCut _BFS.FindPathMarkNode(source, source, sCut); // find tCut _Topology.Invert(); _BFS.FindPathMarkNode(destination, destination, tCut); _Topology.Invert(); // find mincut sets foreach (Link link in _Topology.Links) { if (link.ResidualBandwidth == 0 && _backupResidualBandwidthCopy[link] > 0) if (!sCut.Contains(link.Destination) && !tCut.Contains(link.Source)) if (_BFS.FindPath(link.Source, link.Destination).Count == 0) minCutSet.Add(link); } //foreach (var node in _Topology.Nodes) //{ // if (_BFS.FindPath(node, destination).Count == 0 && node != destination) // sCut.Add(node); // else // tCut.Add(node); //} //foreach (var sNode in sCut) //{ // foreach (var link in sNode.Links) // { // if (link.ResidualBandwidth <= 0 && tCut.Contains(link.Destination)) // minCutSet.Add(link); // } //} RestoreTopology(); return minCutSet; } public double SubFlow(Node source, Node destination, Link subLink) { double subflow; BackupTopology(); MaxFlow(source, destination); subflow = _Topology.GetLink(subLink.Source, subLink.Destination).UsingBandwidth; RestoreTopology(); return subflow; } } }
3ad939513cc42f88f1cda93f60129f2ad9f69fea
C#
Time2Ice/DiplomaSurvive
/Assets/Scripts/DiplomaSurviveDataGenerator/Implementations/ScoreContext.cs
2.578125
3
using DefaultNamespace; using DiplomaSurviveDataGenerator; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace Assets.Scripts.DiplomaSurviveDataGenerator.Implementations { public class ScoreContext : BaseScoreContext { private readonly IGameInfoHolder _gameData; private readonly IPlayerInfoHolder _playerData; public override event ValueChanged OnStudyScoreChanged; public override event ValueChanged OnPersonalLifeScoreChanged; public override event ValueChanged OnMaxPersonalLifeScoreChanged; public override event ValueChanged OnMaxStudyScoreChanged; public ScoreContext(IPlayerInfoHolder playerData, IGameInfoHolder gameData) { _gameData = gameData; _playerData = playerData; _playerData.PointsChanged += (x) => { OnStudyScoreChanged?.Invoke(); }; _playerData.CourseChanged += (x) => { OnMaxStudyScoreChanged?.Invoke(); }; _playerData.MaxPrivateLifeChanged += (x) => { OnMaxPersonalLifeScoreChanged?.Invoke(); }; _playerData.PersonalLifeChanged += (x, y) => { OnPersonalLifeScoreChanged?.Invoke(); }; } public override int StudyScore { get { return _playerData.Points; } set { _playerData.Points = value; } } public override int PersonalLifeScore { get { return _playerData.PrivateLife; } set { _playerData.PrivateLife = value; } } public override int MaxPersonalLifeScore { get { return _playerData.MaxPrivateLife; } set { _playerData.MaxPrivateLife = value; } } public override int MaxStudyScore { get { return _gameData.Courses[_playerData.CurrentCourse].points_to_next; } } } }
9e257a388db28c0115942b2cbc4a55894d4d4398
C#
ifsmetrics-lab/ifsmetrics
/IFSComparer/Measures/XVBSM.cs
2.546875
3
using System; using IFSSharedObjects.Models; using System.Text; using System.Collections.Generic; using System.Linq; namespace IFSComparer.Measures { /// <summary> /// This measure was proposed in: /// /// Loor, M., De Tré, G.: In a Quest for Suitable Similarity Measures to Compare Experience-Based Evaluations. /// In: Computational Intelligence: International Joint Conference, IJCCI 2015 Lisbon, Portugal, November 12-14, 2015, Revised Selected Papers /// pp. 291-314 (2017) /// /// DOI: 10.1007/978-3-319-48506-5_15 /// /// </summary> public class XVBSM: IFSMeasure { const String _CITEKEY = "Loor2017"; const String _CITE = "M.~Loor and G.~De~Tr{\\'e}, In a Quest for Suitable Similarity Measures to Compare Experience-Based Evaluations. In: Computational Intelligence: International Joint Conference, IJCCI 2015 Lisbon, Portugal, November 12-14, 2015, Revised Selected Papers pp. 291-314 (2017)"; Double _alpha; Double _wide; public Double Alpha { get { return _alpha;} set { _alpha = value; } } public Double Wide { get { return _wide;} set { _wide = value;} } Double _middleMarkWeight = 1; Double _upMarkWeight = .01; Double _downMarkWeight = .01; public Double MiddleMarkWeight { get{ return _middleMarkWeight; } set{ _middleMarkWeight = value;} } public Double UpMarkWeight { get{ return _upMarkWeight; } set{ _upMarkWeight = value;} } public Double DownMarkWeight { get{ return _downMarkWeight; } set{ _downMarkWeight = value;} } int _k = 1; public Int32 K { get{ return _k;} set{ _k = value; } } XVBSMResult _result = null; public enum Marker { MiddleMarker, UpMarker, DownMarker } public class XVBSMResult { private Double _level; public Double Level { get { return _level; } set { _level = value; } } private Dictionary<Int32, Marker> _cdpWellFitted; private Dictionary<Int32, Marker> _cdpWellUnfitted; public Dictionary<Int32, Marker> CDPWellFitted { get { return _cdpWellFitted; } } public Dictionary<Int32, Marker> CDPWellUnfitted { get { return _cdpWellUnfitted; } } public XVBSMResult() { _level = 0; _cdpWellFitted = new Dictionary<int, Marker>(); _cdpWellUnfitted = new Dictionary<int, Marker>(); } public void AddWellFittedMarker(Int32 key, Marker marker) { _cdpWellFitted.Add(key, marker); } public void AddWellUnfittedMarker(Int32 key, Marker marker) { _cdpWellUnfitted.Add(key, marker); } public override string ToString() { StringBuilder sb = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); String c = ""; int k = this._cdpWellFitted.Count; for(int i=0;i<k;i++) { switch (this._cdpWellFitted[i]) { case Marker.MiddleMarker: c = "o"; break; case Marker.UpMarker: c = "+"; break; case Marker.DownMarker: c = "-"; break; } sb.Append(c); } k = this._cdpWellUnfitted.Count; for (int i = 0; i < k; i++) { switch (this._cdpWellUnfitted[i]) { case Marker.MiddleMarker: c = "o"; break; case Marker.UpMarker: c = "+"; break; case Marker.DownMarker: c = "-"; break; } sb2.Append(c); } return String.Format("<{0}, '{1}', '{2}'>", _level, sb.ToString(), sb2.ToString()); } } public XVBSM() { _alpha = 0.5; _wide = 0.1; _k = 1; _middleMarkWeight = 1; _upMarkWeight = .6; _downMarkWeight = .4; base.CiteKey = _CITEKEY; base.Cite = _CITE; } public XVBSM(Double alpha, Double wide, int k, Double middleMarkWeight, Double upMarkWeight, Double downMarkWeight) { _alpha = alpha; _wide = wide; _k = k; _middleMarkWeight = middleMarkWeight; _upMarkWeight = upMarkWeight; _downMarkWeight = downMarkWeight; base.CiteKey = _CITEKEY; base.Cite = _CITE; } public override double GetSimilarity(IFS P, IFS Q) { double ret =0; _result = new XVBSMResult(); _result = GetSimilarityExtended(P, Q); double cdf = GetConnotationDifferentialFactor(_result); ret = _result.Level * cdf; return ret; } public XVBSMResult GetSimilarityExtended(IFS P, IFS Q) { double sum = 0; Dictionary<Int32, Double> spotDiffs = GetSpotDiffs(P, Q); int n = spotDiffs.Count; System.Diagnostics.Debug.Assert (n == P.Count); foreach (Double val in spotDiffs.Values) { sum += Math.Abs(val); } double level = 1 - sum / n; XVBSMResult extRet = new XVBSMResult(); extRet.Level = level; IOrderedEnumerable<KeyValuePair<Int32, IFSElement>> query = P.OrderBy<KeyValuePair<Int32, IFSElement>, IFSElement>(se => se.Value, new IFSElementMembershipComparer()); Double delta = GetHeuristicDelta(P ,_wide); int nMarkers = 0; foreach (KeyValuePair<Int32, IFSElement> pair in query) { Marker marker; if (Math.Abs(spotDiffs[pair.Key]) <= delta) marker = Marker.MiddleMarker; else if (spotDiffs[pair.Key] > delta) marker = Marker.UpMarker; else marker = Marker.DownMarker; extRet.AddWellUnfittedMarker(nMarkers, marker); nMarkers++; if (nMarkers >= _k) { break; } } query = P.OrderByDescending<KeyValuePair<Int32, IFSElement>, IFSElement>(se => se.Value, new IFSElementMembershipComparer()); nMarkers = 0; foreach (KeyValuePair<Int32, IFSElement> pair in query) { Marker marker; if (Math.Abs(spotDiffs[pair.Key]) <= delta) marker = Marker.MiddleMarker; else if (spotDiffs[pair.Key] > delta) marker = Marker.UpMarker; else marker = Marker.DownMarker; extRet.AddWellFittedMarker(nMarkers, marker); nMarkers++; if (nMarkers >= _k) { break; } } _result = extRet; return extRet; } private Dictionary<Int32, Double> GetSpotDiffs(IFS P, IFS Q) { Dictionary<Int32, Double> spotDiffs = new Dictionary<int, double> (); IFSElement q; //First, consider the IFSElements in P & Q and P - Q foreach (IFSElement p in P.Values) { if (Q.ContainsKey(p.ElementId)) // P & Q { q = Q[p.ElementId]; } else //P - Q { q = new IFSElement(); q.ElementId = p.ElementId; } spotDiffs.Add(p.ElementId, (p.Membership - q.Membership) + _alpha * (p.Hesitation - q.Hesitation)); } IFSElement p2; //Then, the IFSElements in Q - P foreach (IFSElement q2 in Q.Values) { if (!P.ContainsKey(q2.ElementId)) { p2 = new IFSElement(); p2.ElementId = q2.ElementId; spotDiffs.Add(q2.ElementId, (p2.Membership - q2.Membership) + _alpha * (p2.Hesitation - q2.Hesitation)); } } return spotDiffs; } double GetConnotationDifferentialFactor(XVBSMResult result) { double sumWellFitted = 0; int k = result.CDPWellFitted.Count; for (int i = 0; i < k; i++ ) { switch (result.CDPWellFitted[i]) { case Marker.UpMarker: sumWellFitted += _upMarkWeight; break; case Marker.MiddleMarker: sumWellFitted += _middleMarkWeight; break; case Marker.DownMarker: sumWellFitted += _downMarkWeight; break; } } double avgWellFitted = sumWellFitted / _k; double sumWellUnfitted = 0; k = result.CDPWellUnfitted.Count; for (int i = 0; i < k; i++) { switch (result.CDPWellUnfitted[i]) { case Marker.UpMarker: sumWellUnfitted += _upMarkWeight; break; case Marker.MiddleMarker: sumWellUnfitted += _middleMarkWeight; break; case Marker.DownMarker: sumWellUnfitted += _downMarkWeight; break; } } double avgWellUnfitted = sumWellUnfitted / _k; return Math.Max(avgWellFitted, avgWellUnfitted); } private double GetHeuristicDelta(IFS ifsRef, double wide) { double delta = 0; Double sumDistanceMuNu = 0; int n = ifsRef.Count; foreach (IFSElement el in ifsRef.Values) { sumDistanceMuNu += (el.Membership + el.Nonmembership); } delta = wide * sumDistanceMuNu / n; return delta; } } }
a2149deb1d9b2ce0d31c8b0b461795d905167145
C#
alexb5dh/NoCMD
/NoCMD/Program.cs
2.609375
3
using System; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using NoCMD.Exceptions; namespace NoCMD { internal static class Program { private static void RunWrapper(string commandLine) { Process.Start(new ProcessStartInfo { FileName = Process.GetCurrentProcess().MainModule.FileName, Arguments = "/wait " + commandLine, CreateNoWindow = true, UseShellExecute = false }); } [STAThread] private static void Main(string[] args) { try { var config = Config.ParseCommandLine(args); if (string.IsNullOrEmpty(config.Command)) return; // Todo: add help output if (config.WaitForExit) new NoCMDApplication(config).Run(); else RunWrapper(string.Join(" ", args.Select(arg => "\"" + arg + "\""))); } catch (Exception e) { MessageBox.Show(e.Message, $"NoCMD: Internal Error ({e.GetType().Name})"); } } } }
946e9051a3bcfc4686b26b9d2ab935cfa9859fcb
C#
ninjapretzel/Spring2020LabExamples
/Assets/Lab6/V2Scripts/QuickAndDirtyWeaponSwitch.cs
2.609375
3
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Lab6 { public class QuickAndDirtyWeaponSwitch : MonoBehaviour { public AWeapon[] weapons; PlayerControl player; void Update() { if (player == null) { player = GetComponent<PlayerControl>(); } if (Input.GetKeyDown(KeyCode.Alpha1)) { TrySwitch(0); } if (Input.GetKeyDown(KeyCode.Alpha2)) { TrySwitch(1); } if (Input.GetKeyDown(KeyCode.Alpha3)) { TrySwitch(2); } if (Input.GetKeyDown(KeyCode.Alpha4)) { TrySwitch(3); } if (Input.GetKeyDown(KeyCode.Alpha5)) { TrySwitch(4); } if (Input.GetKeyDown(KeyCode.Alpha6)) { TrySwitch(5); } if (Input.GetKeyDown(KeyCode.Alpha7)) { TrySwitch(6); } if (Input.GetKeyDown(KeyCode.Alpha8)) { TrySwitch(7); } if (Input.GetKeyDown(KeyCode.Alpha9)) { TrySwitch(8); } if (Input.GetKeyDown(KeyCode.Alpha0)) { TrySwitch(9); } } public void TrySwitch(int index) { if (index < weapons.Length) { player.GiveWeapon(weapons[index], true); } } } }
eb8998dac12b81847da6a9e17027a0c759dcffb4
C#
shendongnian/download4
/first_version_download2/411319-35958688-113059425-4.cs
2.65625
3
var propName = "CSName"; var keyValues = Management .GetInstances() .Cast<ManagementObject>() .Select(obj => new { name = propName, value = obj[propName] }) .Where(obj => obj.value != null); var result = String.Join( "", keyValues .Select(kv => String.Format("<br><font color = red>{0} : {1} </font>", kv.name, kv.value))); TxtBox.Text += result;
7002ccb9b8e315e8c58d920d1f601c02ec32b3c2
C#
itran/AIMS
/LegacyVS2005/AIMSClient/BLL/User.cs
2.546875
3
using System; using System.Collections.Generic; using System.Text; using AIMS.Common; using AIMS.DAL; using System.Data; namespace AIMS.BLL { public class User : BaseObject { #region "Private Declarations" private string _userName =""; private string _userFullName = ""; private string _userPassword = ""; private string _userEmailAddress = ""; private string _userPhone = ""; private string _userFax = ""; private string _userActiveYN = ""; private string _domainAuthYN = ""; #endregion #region "Public Declarations" public string UserName { get { return _userName; } set { _userName = value; } } public string UserPassword { get { return _userPassword; } set { _userPassword = value; } } public string UserFullName { get { return _userFullName; } set { _userFullName = value; } } public string UserEmailAddress { get { return _userEmailAddress; } set { _userEmailAddress = value; } } public string UserPhone { get { return _userPhone; } set { _userPhone = value; } } public string UserFax { get { return _userFax; } set { _userFax = value; } } public string UserActiveYN { get { return _userActiveYN; } set { _userActiveYN = value; } } public string DomainAuthYN { get { return _domainAuthYN; } set { _domainAuthYN = value; } } string _passwordWordSetupYN = ""; public string PasswordWordSetupYN { get { return _passwordWordSetupYN; } set { _passwordWordSetupYN = value; } } string _signaturePath = ""; public string SignaturePath { get { return _signaturePath; } set { _signaturePath = value; } } string _passwordWordHint = ""; public string PasswordWordHint { get { return _passwordWordHint; } set { _passwordWordHint = value; } } string _passwordHintAnswer = ""; public string PasswordWordHintAnswer { get { return _passwordHintAnswer; } set { _passwordHintAnswer = value; } } #endregion #region "Public Functions" public DataTable GetLoginDetails(string userName, string passWord) { DataTable tbl = new DataTable(); return tbl; } public User GetUserDetails(string UserName) { User oUser = new User(); DataSet ds = new DataSet(); UserDAL userDAL = new UserDAL(); ds = userDAL.GetUserDetails(UserName); if (!oUser.MapData(ds)) oUser = null; return oUser; } public override bool MapData(DataRow row) { UserName = GetString(row, "User_Name"); UserEmailAddress = GetString(row, "User_Email"); UserFax = GetString(row, "User_Fax"); UserPassword = GetString(row, "User_Password"); UserFullName = GetString(row, "User_Full_Name"); UserPhone = GetString(row, "User_Phone"); UserActiveYN = GetString(row, "User_Active_YN"); DomainAuthYN = GetString(row, "DOMAIN_AUTH_YN"); PasswordWordHint = GetString(row, "PASSWORD_HINT"); PasswordWordHintAnswer = GetString(row, "PASSWORD_HINT_ANSWER"); PasswordWordSetupYN = GetString(row, "PASSWORD_SETUP"); SignaturePath = GetString(row, "SIGNATURE_PATH"); return base.MapData(row); } public DataTable GetUserRestrictions(string UserName) { DataTable dtUserRestrictions = new DataTable(); UserDAL userDAL = new UserDAL(); dtUserRestrictions = userDAL.GetUserRestrictions(UserName); return dtUserRestrictions; } public DataTable GetUserMenuAccess(string UserName) { DataTable dtUserRestrictions = new DataTable(); UserDAL userDAL = new UserDAL(); dtUserRestrictions = userDAL.GetUserMenuAccess(UserName); return dtUserRestrictions; } public DataTable GetAllRestrictions(string UserName) { DataTable dtUserRestrictions = new DataTable(); UserDAL userDAL = new UserDAL(); dtUserRestrictions = userDAL.GetAllRestrictions(UserName); return dtUserRestrictions; } public bool SaveUserPassword(string userName, string Password, string PasswordHint, string PasswordHintAnswer) { User oUser = new User(); UserDAL UserDAL = new UserDAL(); bool bSaved = false; bSaved = UserDAL.SaveUserPassword(userName, Password, PasswordHint, PasswordHintAnswer); UserDAL = null; return bSaved; } #endregion } }
213ac36f7b81aef7babe5528db45441a977029a2
C#
dgg/nmoneys
/src/NMoneys.Tools/CompareIso/IsoCurrenciesCollection.cs
3.125
3
using System.Collections; using System.Collections.Generic; namespace NMoneys.Tools.CompareIso { // some countries share the same currency, so we normalize them internal class IsoCurrenciesCollection : IReadOnlyCollection<IsoCurrency> { private readonly Dictionary<short, IsoCurrency> _currencies; public IsoCurrenciesCollection() { _currencies = new Dictionary<short, IsoCurrency>(); } private void add(IsoCurrency scrapped) { if (scrapped != null && scrapped.HasValue) _currencies[scrapped.NumericCode.Value.GetValueOrDefault()] = scrapped; } public void AddRange(IsoCurrency[] scrapped) { for (int i = 0; i < scrapped.Length; i++) { add(scrapped[i]); } } public int Count => _currencies.Count; public IEnumerator<IsoCurrency> GetEnumerator() { return _currencies.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Contains(short numericCode) { return _currencies.ContainsKey(numericCode); } } }
4d9bb570f71c5a036af6a580a2b2f8e4fd0ef171
C#
josuestaun/FCTs_Josue
/CapaDatos/GestionDatos.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entidades; namespace CapaDatos { public class GestionDatos { BdFCTsEntities bdFCTsEntities = new BdFCTsEntities(); public GestionDatos() { } //Devolver lista de ciclos public List<Ciclo> DevolverCiclos(out string msj) { msj = ""; List<Ciclo> listaCiclos = new List<Ciclo>(); try { listaCiclos = bdFCTsEntities.Ciclos.ToList(); } catch (Exception e) { msj = e.Message; } return listaCiclos; } //Devolver lista de nombre de ciclos public List<String> DevolverCodigoCiclos(out string msj) { msj = ""; List<String> nombreCiclos = new List<string>(); try { nombreCiclos = bdFCTsEntities.Ciclos.Select(cic => cic.Id).ToList(); } catch (Exception e) { msj = e.Message; } return nombreCiclos; } //Devuelve ciclo por id public Ciclo DevolverCiclo(String id, out string msj) { msj = ""; Ciclo ciclo = new Ciclo(); try { ciclo = bdFCTsEntities.Ciclos.Find(id); } catch (Exception e) { msj = e.Message; } return ciclo; } //Devolver lista alumnos por id ciclo public List<Alumno> DevolverAlumnos(string id, out string msj) { msj = ""; List<Alumno> alumnosPorCiclo = new List<Alumno>(); try { alumnosPorCiclo = bdFCTsEntities.Ciclos.Find(id).Alumnos.OrderByDescending(al => al.Aprobado).ThenBy(al => al.Nombre).ToList(); } catch (Exception e) { msj = e.Message; } return alumnosPorCiclo; } //Devolver lista empresas por id ciclo public List<Empresa> DevolverEmpresas(string id, out string msj) { msj = ""; List<OfertasFCT> ofertasPorCiclo = new List<OfertasFCT>(); List<Empresa> empresasPorCiclo = new List<Empresa>(); try { ofertasPorCiclo = bdFCTsEntities.Ciclos.Find(id).OfertasFCTs.ToList(); empresasPorCiclo = ofertasPorCiclo.Select(of => of.Empresa).OrderBy(em => em.Nombre).ToList(); } catch (Exception e) { msj = e.Message; } return empresasPorCiclo; } //devuelve una lista de los nombres de los alumnos de un ciclo public List<String> DevolverNombreAlumnos(string id, out string msj) { msj = ""; List<String> nombreAlumnosPorCiclo = new List<String>(); try { nombreAlumnosPorCiclo = bdFCTsEntities.Ciclos.Find(id).Alumnos.OrderByDescending(al => al.Aprobado).ThenBy(al => al.Nombre).Select(al => al.Nombre).ToList(); } catch (Exception e) { msj = e.Message; } return nombreAlumnosPorCiclo; } public List<String> DevolerNombreAlumnosSinAsignar(string idCiclo, out string msj) { msj = ""; List<String> nombreAlumnosSinAsignar = new List<string>(); try { nombreAlumnosSinAsignar = bdFCTsEntities.Ciclos.Find(idCiclo).Alumnos.Where(al => al.FCT == null).Select(alum => alum.Nombre).ToList(); } catch (Exception e) { msj = e.Message; } return nombreAlumnosSinAsignar; } //deuvuelve una lista de los nombres de las empresas para un ciclo public List<String> DevolverNombreEmpresas(string id, out string msj) { msj = ""; List<OfertasFCT> ofertasPorCiclo = new List<OfertasFCT>(); List<String> nombreEmpresasPorCiclo = new List<String>(); try { ofertasPorCiclo = bdFCTsEntities.Ciclos.Find(id).OfertasFCTs.ToList(); nombreEmpresasPorCiclo = ofertasPorCiclo.Select(of => of.Empresa).OrderBy(em => em.Nombre).Select(em => em.Nombre).ToList(); } catch (Exception e) { msj = e.Message; } return nombreEmpresasPorCiclo; } //deuvuelve una lista de los nombres de los tutores para un ciclo public List<String> DevolverNombreTutores(string id, out string msj) { msj = ""; List<Alumno> alumnosPorCiclo = new List<Alumno>(); List<String> nombreTutores = new List<String>(); try { alumnosPorCiclo = bdFCTsEntities.Ciclos.Find(id).Alumnos.ToList(); //no funciona asi: //nombreTutores = alumnosPorCiclo.Select(fce => fce.FCT != null).Select(fc => fc.TutorInsti).ToList(); nombreTutores = bdFCTsEntities.Profes.Select(p => p.Nombre).ToList(); } catch (Exception e) { msj = e.Message; } return nombreTutores; } public List<Alumno> DevolverAlumnosAsignados(string id, out string msj) { msj = ""; List<Alumno> alumnosAsignados = new List<Alumno>(); try { alumnosAsignados = bdFCTsEntities.Ciclos.Find(id).Alumnos.Where(al => al.FCT != null).ToList(); } catch (Exception e) { msj = e.Message; } return alumnosAsignados; } //Comprobar que existe ciclo public String ExisteCiclo(String id) { String msj = ""; if (!bdFCTsEntities.Ciclos.Any(cic => cic.Id.ToUpper() == id.ToUpper())){ msj = "El ciclo " + id + " no existe."; } return msj; } //Comprobar si existe Profesor public String ExisteTutor(String nombre) { String msj = ""; if (!bdFCTsEntities.Profes.Any(prof => prof.Nombre.ToUpper() == nombre.ToUpper())){ msj = "El profesor " + nombre + " no existe."; } return msj; } public String ExisteAlumnoEnCiclo(String nombreAlumn, String idCiclo) { String msj = ""; //Compruebo si alumno existe en el ciclo Alumno alumno = bdFCTsEntities.Alumnos.SingleOrDefault(al => al.Nombre.ToUpper() == nombreAlumn.ToUpper()); if (alumno == null) { msj = "El alumno " + nombreAlumn + " no existe."; return msj; } else if (alumno.IdCiclo != idCiclo) { msj = "El alumno " + nombreAlumn + " no está en el ciclo " + idCiclo; } return msj; } //COmprobar si la empresa existe public String ExisteEmpresa(String nombreEmpresa) { String msj = ""; if (!bdFCTsEntities.Empresas.Any(emp => emp.Nombre.ToUpper() == nombreEmpresa.ToUpper())){ msj = "La empresa " + nombreEmpresa + " no existe."; } return msj; } //Comprobar si la empresa tiene ofertas public String EmpresaSolicita(String nombreEmpresa, String idCiclo) { String msj = ""; Empresa empresa = bdFCTsEntities.Empresas.SingleOrDefault(emp => emp.Nombre.ToUpper() == nombreEmpresa.ToUpper()); if (empresa == null) { msj = "La empresa no existe"; return msj; } OfertasFCT oferta = bdFCTsEntities.OfertasFCTs.SingleOrDefault(of => of.IdCiclo.ToUpper() == idCiclo.ToUpper() && of.IdEmpresa == empresa.Id); if (oferta == null) { msj = "La empresa " + nombreEmpresa + " no tiene ofertas para el ciclo " + idCiclo; } return msj; } //Devolver si alumno ha aprobado public String AlumnoAprobado(String nombreAlumno) { String msj = ""; Alumno alumno = bdFCTsEntities.Alumnos.SingleOrDefault(al => al.Nombre.ToUpper() == nombreAlumno.ToUpper()); if (alumno == null) { msj = "El alumno no existe"; return msj; } else if (!alumno.Aprobado) { msj = "El alumno " + nombreAlumno + " no ha aprobado el ciclo."; } return msj; } //Comprobar si un alumno ya esta asignado a una empresa public String AlumnoAsignado(String nombreAlumno) { String msj = ""; Alumno alumno = bdFCTsEntities.Alumnos.SingleOrDefault(al => al.Nombre.ToUpper() == nombreAlumno.ToUpper()); if (alumno == null) { msj = "El alumno no existe"; } else if (alumno.FCT != null) { String empresa = alumno.FCT.Empresa.Nombre; msj = "El alumno " + nombreAlumno + " ya tiene asignada la empresa " + empresa; } return msj; } //Comprobar si alumno no tiene asignada una empresa public String AlumnoNoAsignado(String nombreAlumno) { String msj = ""; Alumno alumno = bdFCTsEntities.Alumnos.SingleOrDefault(al => al.Nombre.ToUpper() == nombreAlumno.ToUpper()); if (alumno == null) { msj = "El alumno no existe"; } else if (alumno.FCT == null) { msj = "El alumno " + nombreAlumno + " no tiene asignada ninguna empresa"; } return msj; } //Comprobar si una empresa ya tiene todas sus ofertas asignadas public String EmpresaAsignada(String nombreEmpresa) { String msj = ""; Empresa empresa = bdFCTsEntities.Empresas.SingleOrDefault(emp => emp.Nombre.ToUpper() == nombreEmpresa.ToUpper()); if (empresa == null) { msj = "La empresa no existe"; return msj; } int numOfertas = empresa.OfertasFCTs.Count; int numFCTs = empresa.FCTs.Count; if (numFCTs >= numOfertas) { msj = "La empresa " + nombreEmpresa + " ya tiene asignados el/los " + numOfertas + " alumnos/as pedidos"; } return msj; } //Devolver objeto alumno public Alumno DevolverObjetoAlumno(String nombreAlumno) { Alumno alumno = bdFCTsEntities.Alumnos.Single(al => al.Nombre.ToUpper() == nombreAlumno.ToUpper()); return alumno; } //Devolver objeto empresa public Empresa DevolverObjetoEmpresa(String nombreEmpresa) { Empresa empresa = bdFCTsEntities.Empresas.Single(em => em.Nombre.ToUpper() == nombreEmpresa.ToUpper()); return empresa; } //Devolver objeto profesor public Profe DevolverObjetoProfesor(String nombreProfesor) { Profe profesor = bdFCTsEntities.Profes.Single(prof => prof.Nombre.ToUpper() == nombreProfesor.ToUpper()); return profesor; } //Metodo para añadir una nueva FCT de un alumno a una empresa public String InsertarFCT2() { String msj = ""; FCT fct = new FCT(999, 10, "Abilio", "Juan"); bdFCTsEntities.FCTs.Add(fct); bdFCTsEntities.SaveChanges(); return msj; } public String InsertarFCT(FCT fctParaAsignar) { String msj = ""; //creo la FCT FCT fct = new FCT(fctParaAsignar.NMatricula, fctParaAsignar.IdEmpresa, fctParaAsignar.TutorInsti, fctParaAsignar.TutorEmpresa); //Añadir FCT bdFCTsEntities.FCTs.Add(fct); try { //Error al guardar los cambios en la base de datos int nAfectados = bdFCTsEntities.SaveChanges(); } catch (Exception e) { msj = e.Message; } return msj; } public String RetirarFCT(int numMatricula) { String msj = ""; //En la Tabla FCT busco la FCT con el numMatricula FCT fct = bdFCTsEntities.FCTs.Find(numMatricula); if (fct == null) { msj = "No existe la fct"; return msj; } bdFCTsEntities.FCTs.Remove(fct); try { //guardo los cambios en la base de datos int nAfectados = bdFCTsEntities.SaveChanges(); if (nAfectados == 0) { msj = "No se ha podido borrar la fct"; return msj; } } catch (Exception e) { msj = e.Message; //Solucionar el borrado incorrecto en las colecciones //primero quitamos el estado deleted al registro bdFCTsEntities.Entry(fct).State = System.Data.Entity.EntityState.Unchanged; bdFCTsEntities.FCTs.Add(fct); //lo añadimos de nuevo } return msj; } } }
37735d632448450be122ffd14ee8da1e91d8e28e
C#
mattboschetti/xamarin-mobile-playground
/SampleAsyncTestingApp/SampleAsyncTestingApp/SampleAsyncTestingAppViewController.cs
2.75
3
using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; using System.Threading.Tasks; namespace SampleAsyncTestingApp { public partial class SampleAsyncTestingAppViewController : UIViewController { public SampleAsyncTestingAppViewController () : base ("SampleAsyncTestingAppViewController", null) { } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { // Return true for supported orientations return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); } async partial void calculatePrimeAsync (NSObject sender) { txtNthPrimeFound.Text = "Calculating..."; var i = int.Parse(txtNthPrimeToFind.Text); var x = await FindPrimeNumberAsync(i); txtNthPrimeFound.Text = x.ToString(); } partial void calculatePrimeSync (NSObject sender) { var i = int.Parse(txtNthPrimeToFind.Text); var x = FindPrimeNumber(i); txtNthPrimeFound.Text = x.ToString(); } public Task<long> FindPrimeNumberAsync(int n) { return Task.Run (() => { return FindPrimeNumber(n); }); } // Algorithm to find the nth prime number extracted from // http://stackoverflow.com/questions/13001578/i-need-a-slow-c-sharp-function public long FindPrimeNumber(int n) { int count = 0; long a = 2; while (count<n) { long b = 2; int prime = 1;// to check if found a prime while (b * b <= a) { if (a % b == 0) { prime = 0; break; } b++; } if (prime > 0) count++; a++; } return (--a); } } }
3fe012407d2b3028e2fa9a0d9ed739f1eabe3bee
C#
DenBread/metanit
/Den.Metanit/Den.Metanit/Program.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Den.Metanit { class Program { static void Main(string[] args) { int a = 5; Console.WriteLine($"Начальное значение переменной a = {a}"); IncrementRef(ref a); Console.WriteLine($"Переменная А после передачи ссылке равна = {a}"); Console.ReadLine(); } static void IncrementRef(ref int x) { x++; x = 5 + x; Console.WriteLine($"IncrementRef: {x}"); } } }
4fc9ac142a59b3db92ce536c67726c0b1a9863a4
C#
Knagis/CommonMarkSharp
/CommonMarkSharp/InlineParsers/CommonMarkInlineParser.cs
2.78125
3
using CommonMarkSharp.Inlines; using System; namespace CommonMarkSharp.InlineParsers { public class CommonMarkInlineParser : IInlineParser<Inline> { public CommonMarkInlineParser(Parsers parsers) { Parsers = parsers; OthersParser = new Lazy<IInlineParser<InlineString>>(() => new AllExceptParser(parsers.InlineParser.StartsWithChars)); } public Parsers Parsers { get; private set; } public Lazy<IInlineParser<InlineString>> OthersParser { get; private set; } public string StartsWithChars { get { return null; } } public bool CanParse(Subject subject) { return true; } public Inline Parse(ParserContext context, Subject subject) { var inline = Parsers.InlineParser.Parse(context, subject); if (inline == null) { inline = OthersParser.Value.Parse(context, subject); } if (inline == null) { inline = new InlineString(subject.Take()); } return inline; } } }
e9b5cb6f3a0fedf4418e232051e158bba5fcf2e8
C#
showtroylove/IGS
/DevExpress.HybridApp.Wpf/Common/DataModel/WebApi/WebApiRepository.cs
2.59375
3
using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Linq; using System.Linq.Expressions; using DevExpress.DevAV.Common.DataModel.EntityFramework; using DevExpress.DevAV.Common.Utils; using DevExpress.DevAV.DevAVDbDataModel; namespace DevExpress.DevAV.Common.DataModel.WebApi { /// <summary> /// A DbReadOnlyRepository is a IReadOnlyRepository interface implementation representing the collection of all entities in the unit of work, or that can be queried from the database, of a given type. /// DbReadOnlyRepository objects are created from a DbUnitOfWork using the GetReadOnlyRepository method. /// DbReadOnlyRepository provides only read-only operations against entities of a given type. /// </summary> /// <typeparam name="TEntity">Repository entity type.</typeparam> /// <typeparam name="TWebApiContext">DbContext type.</typeparam> public class WebApiReadOnlyRepository<TWebApiContext, TEntity> : DbRepositoryQuery<TEntity>, IReadOnlyRepository<TEntity> where TWebApiContext : WebApiContext<TEntity> where TEntity : class, new() { private readonly Func<TWebApiContext, Dictionary<TEntity, System.Data.Entity.EntityState>> _dbSetAccessor; private readonly WebApiUnitOfWork<TWebApiContext, TEntity> _unitOfWork; /// <summary> /// Initializes a new instance of DbReadOnlyRepository class. /// </summary> /// <param name="unitOfWork">Owner unit of work that provides context for repository entities.</param> /// <param name="dbSetAccessor">Function that returns DbSet entities from Entity Framework DbContext.</param> public WebApiReadOnlyRepository(WebApiUnitOfWork<TWebApiContext, TEntity> unitOfWork, Func<TWebApiContext, Dictionary<TEntity, System.Data.Entity.EntityState>> dbSetAccessor) : base(() => dbSetAccessor(unitOfWork.Context).Keys.ToList().AsQueryable()) { _dbSetAccessor = dbSetAccessor; _unitOfWork = unitOfWork; } protected Dictionary<TEntity, System.Data.Entity.EntityState> Entities => _dbSetAccessor(_unitOfWork.Context); protected TWebApiContext Context => _unitOfWork.Context; #region IReadOnlyRepository IUnitOfWork IReadOnlyRepository<TEntity>.UnitOfWork => _unitOfWork; #endregion } /// <summary> /// A DbRepository is a IRepository interface implementation representing the collection of all entities in the unit of work, or that can be queried from the database, of a given type. /// DbRepository objects are created from a DbUnitOfWork using the GetRepository method. /// DbRepository provides only write operations against entities of a given type in addition to the read-only operation provided DbReadOnlyRepository base class. /// </summary> /// <typeparam name="TEntity">Repository entity type.</typeparam> /// <typeparam name="TPrimaryKey">Entity primary key type.</typeparam> /// <typeparam name="TWebApiContext"></typeparam> public class WebApiRepository<TWebApiContext, TEntity, TPrimaryKey> : WebApiReadOnlyRepository<TWebApiContext, TEntity>, IRepository<TEntity, TPrimaryKey> where TWebApiContext : WebApiContext<TEntity> where TEntity : class, new() { private readonly Expression<Func<TEntity, TPrimaryKey>> getPrimaryKeyExpression; private readonly EntityTraits<TEntity, TPrimaryKey> entityTraits; /// <summary> /// Initializes a new instance of DbRepository class. /// </summary> /// <param name="unitOfWork">Owner unit of work that provides context for repository entities.</param> /// <param name="dbSetAccessor">Function that returns DbSet entities from Entity Framework DbContext.</param> /// <param name="getPrimaryKeyExpression">Lambda-expression that returns entity primary key.</param> public WebApiRepository(WebApiUnitOfWork<TWebApiContext, TEntity> unitOfWork, Func<TWebApiContext, Dictionary<TEntity, System.Data.Entity.EntityState>> dbSetAccessor, Expression<Func<TEntity, TPrimaryKey>> getPrimaryKeyExpression) : base(unitOfWork, dbSetAccessor) { this.getPrimaryKeyExpression = getPrimaryKeyExpression; entityTraits = ExpressionHelper.GetEntityTraits(this, getPrimaryKeyExpression); } protected virtual TEntity CreateCore() { var newEntity = new TEntity(); Entities.Add(newEntity, System.Data.Entity.EntityState.Added); return newEntity; } protected virtual void UpdateCore(TEntity entity) { Entities[entity] = System.Data.Entity.EntityState.Modified; } protected virtual EntityState GetStateCore(TEntity entity) { return GetEntityState(Context.Entities[entity]); } private static EntityState GetEntityState(System.Data.Entity.EntityState entityStates) { switch (entityStates) { case System.Data.Entity.EntityState.Added: return EntityState.Added; case System.Data.Entity.EntityState.Deleted: return EntityState.Deleted; case System.Data.Entity.EntityState.Detached: return EntityState.Detached; case System.Data.Entity.EntityState.Modified: return EntityState.Modified; case System.Data.Entity.EntityState.Unchanged: return EntityState.Unchanged; default: throw new NotImplementedException(); } } protected virtual TEntity FindCore(TPrimaryKey primaryKey) { return Context.Entities.Keys.FirstOrDefault(x => { var id = GetPrimaryKeyCore(x); return id.Equals(primaryKey); }); } protected virtual void RemoveCore(TEntity entity) { try { Context.Entities.Remove(entity); } catch (Exception ex) { throw DbExceptionsConverter.Convert(new DbUpdateException("An error occurred while deleting.", ex)); } } protected virtual TEntity ReloadCore(TEntity entity) { return FindCore(GetPrimaryKeyCore(entity)); } protected virtual TPrimaryKey GetPrimaryKeyCore(TEntity entity) { return entityTraits.GetPrimaryKey(entity); } protected virtual void SetPrimaryKeyCore(TEntity entity, TPrimaryKey primaryKey) { var setPrimaryKeyAction = entityTraits.SetPrimaryKey; setPrimaryKeyAction(entity, primaryKey); } #region IRepository TEntity IRepository<TEntity, TPrimaryKey>.Find(TPrimaryKey primaryKey) { return FindCore(primaryKey); } void IRepository<TEntity, TPrimaryKey>.Remove(TEntity entity) { RemoveCore(entity); } TEntity IRepository<TEntity, TPrimaryKey>.Create() { return CreateCore(); } void IRepository<TEntity, TPrimaryKey>.Update(TEntity entity) { UpdateCore(entity); } EntityState IRepository<TEntity, TPrimaryKey>.GetState(TEntity entity) { return GetStateCore(entity); } TEntity IRepository<TEntity, TPrimaryKey>.Reload(TEntity entity) { return ReloadCore(entity); } Expression<Func<TEntity, TPrimaryKey>> IRepository<TEntity, TPrimaryKey>.GetPrimaryKeyExpression => getPrimaryKeyExpression; void IRepository<TEntity, TPrimaryKey>.SetPrimaryKey(TEntity entity, TPrimaryKey primaryKey) => SetPrimaryKeyCore(entity, primaryKey); TPrimaryKey IRepository<TEntity, TPrimaryKey>.GetPrimaryKey(TEntity entity) => GetPrimaryKeyCore(entity); bool IRepository<TEntity, TPrimaryKey>.HasPrimaryKey(TEntity entity) => entityTraits.HasPrimaryKey(entity); #endregion } }
c3cff979741d40bed933da876008ac30c0a4edaa
C#
ripa-alexandr/worker
/Worker.Web/ViewModel/Employee/EmployeeViewModel.cs
2.609375
3
using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace Worker.Web.ViewModel.Employee { public class EmployeeViewModel { public int? Id { get; set; } [DisplayName("Имя")] [Required(ErrorMessage = "Поле '{0}' должно быть установлено")] [StringLength(50, ErrorMessage = "Длина строки должна быть до {1} символов")] public string Name { get; set; } [DisplayName("Должность")] [Required(ErrorMessage = "Поле '{0}' должно быть установлено")] [StringLength(50, ErrorMessage = "Длина строки должна быть до {1} символов")] public string Position { get; set; } [DisplayName("Статус")] [Required(ErrorMessage = "Поле '{0}' должно быть установлено")] public int Status { get; set; } [DisplayName("Заработная плата")] [Required(ErrorMessage = "Поле '{0}' должно быть установлено")] [RegularExpression(@"^\d+(,{1}\d{2}$|$)", ErrorMessage = "Поле '{0}' должно быть числом формата 0 или 0,00")] [Range(0, 1000000, ErrorMessage = "Поле '{0}' должно быть от {1} до {2}")] public decimal Salary { get; set; } public IEnumerable<SelectListItem> AllStatuses { get; set; } public EmployeeFilter Filter { get; set; } } }
e8ec157d7eeb6f7893e16e3b9f294ff99d25af9f
C#
stackthatcode/ProfitWise
/Push.Shopify/Model/Shop.cs
2.5625
3
using Newtonsoft.Json; namespace Push.Shopify.Model { public class Shop { public long Id { get; set; } public string Currency { get; set; } public string TimeZone { get; set; } public string TimeZoneIana { get; set; } public string Domain { get; set; } public string Email { get; set; } private Shop(string serializedJson) { dynamic parent = JsonConvert.DeserializeObject(serializedJson); var shop = parent.shop; this.Id = shop.id; this.Currency = shop.currency; this.TimeZone = shop.timezone; this.TimeZoneIana = shop.iana_timezone; this.Domain = shop.myshopify_domain; this.Email = shop.email; } public static Shop MakeFromJson(string json) { return new Shop(json); } public Shop() { } } }
e561e0b456b849c1dedc3625bb5c7a6e66e3b436
C#
SimeonStoykov/SoftUni
/C# basics/BGCoder/Telerik 28 December 2012/TelerikLogo/TelerikLogo.cs
3.515625
4
using System; class TelerikLogo { static void Main() { int n = int.Parse(Console.ReadLine()); int heightAndWidth = (n * 3) - 2; int leftLStar = (n / 2) + 1; int leftRStar = (n / 2) + 1; int rightLStar = heightAndWidth - (n / 2); int rightRStar = heightAndWidth - (n / 2); for (int rows = 1; rows <= (n / 2) + 1 + (n - 1 - ((n / 2) + 1)); rows++) { for (int cols = 1; cols <= heightAndWidth; cols++) { if (cols == leftLStar || cols == leftRStar || cols == rightLStar || cols == rightRStar) { Console.Write("*"); } else { Console.Write("."); } } leftLStar--; leftRStar++; rightLStar--; rightRStar++; Console.WriteLine(); } int leftStar = heightAndWidth / 2 + 1; int rightStar = heightAndWidth / 2 + 1; for (int rows = 1; rows <= (n*2)-1; rows++) { for (int cols = 1; cols <= heightAndWidth; cols++) { if (cols == leftStar || cols == rightStar) { Console.Write("*"); } else { Console.Write("."); } } if (rows < n) { leftStar--; rightStar++; } else { leftStar++; rightStar--; } Console.WriteLine(); } } }
2f1a0343fcedfd971d284635209f97585d8538e7
C#
Flydiverny/da148a_csharp
/ConsoleApplication1/ConsoleApplication1/Program.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.Write(new Program().GenerateHTMLRecurrence(7)); Console.ReadLine(); } public String GenerateHTMLRecurrence(int weeks) { var recurr = weeks * 7; var counter = 0; var sb = new StringBuilder(); var days = new[] { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" }; sb.AppendFormat("<div id=\"recurrOpt{0}\" class=\"schedSection\" data-bind=\"visible: ShowRecurrOpt{0}\">", recurr); for (var w = 1; w <= weeks; w++) { sb.AppendFormat("<div id=\"dayGroup_{0}_{1}\" class=\"day_group\">", recurr, w); foreach (var day in days) { sb.AppendFormat("<div data-bind=\"attr: {{ 'class': $data.cssClass}}\" class=\"day day_{0}_{1} input-group\">", recurr, w) .AppendFormat("<span class=\"input-group-addon input-sm {0}\"></span>", day) .AppendFormat("<span class=\"input-group-addon input-sm\">") .AppendFormat("<input type=\"checkbox\" data-bind=\"checked: ScheduleMask[{0}]\">", counter++) .Append("</span>") .Append("</div>"); } } return sb.ToString(); } /* <div data-bind="attr: { 'class': $data.cssClass }" class="day day_7_1"> <label class="tuesday checkbox-inline">tue</label> <input type="checkbox" data-bind="checked: ScheduleMask[1]"></div> <div data-bind="attr: { 'class': $data.cssClass }" class="day day_7_1"> <label class="wednesday checkbox-inline">wed</label> <input type="checkbox" data-bind="checked: ScheduleMask[2]"></div> <div data-bind="attr: { 'class': $data.cssClass }" class="day day_7_1"> <label class="thursday checkbox-inline">thur</label> <input type="checkbox" data-bind="checked: ScheduleMask[3]"></div> <div data-bind="attr: { 'class': $data.cssClass }" class="day day_7_1"> <label class="friday checkbox-inline">fri</label> <input type="checkbox" data-bind="checked: ScheduleMask[4]"></div> <div data-bind="attr: { 'class': $data.cssClass }" class="day day_7_1"> <label class="saturday checkbox-inline">sat</label> <input type="checkbox" data-bind="checked: ScheduleMask[5]"></div> <div data-bind="attr: { 'class': $data.cssClass }" class="day day_7_1"> <label class="sunday checkbox-inline">sun</label> <input type="checkbox" data-bind="checked: ScheduleMask[6]"></div> </div> */ } }