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
|
|---|---|---|---|---|---|---|
55a674de87d08faa17403dfebdcb8b980c4306ed
|
C#
|
chronoxor/NDepth
|
/Sources/Business/BusinessObjects/Domain/MonitoringEvent.cs
| 2.59375
| 3
|
using System;
using System.Runtime.Serialization;
using FluentValidation;
using NDepth.Business.BusinessObjects.Common;
namespace NDepth.Business.BusinessObjects.Domain
{
/// <summary>Monitoring event represents some event in past that occurs on some machine/module/component with some severity</summary>
[DataContract]
public class MonitoringEvent : IExtensibleDataObject
{
/// <summary>Identifier</summary>
[DataMember]
public virtual long Id { get; set; }
/// <summary>Timestamp</summary>
[DataMember]
public virtual DateTime Timestamp { get; set; }
/// <summary>Machine name</summary>
[DataMember]
public virtual string Machine { get; set; }
/// <summary>Module name</summary>
[DataMember]
public virtual string Module { get; set; }
/// <summary>Component name</summary>
[DataMember]
public virtual string Component { get; set; }
/// <summary>Severity code</summary>
[DataMember]
public virtual Severity Severity { get; set; }
/// <summary>Title of the monitoring event</summary>
[DataMember]
public virtual string Title { get; set; }
/// <summary>Description of the monitoring event</summary>
[DataMember]
public virtual string Description { get; set; }
#region Validator
/// <summary>Validator class</summary>
public class MonitoringEventValidator : AbstractValidator<MonitoringEvent>
{
internal MonitoringEventValidator()
{
RuleFor(entity => entity.Id).GreaterThan(0);
RuleFor(entity => entity.Machine).NotNull();
RuleFor(entity => entity.Module).NotNull();
RuleFor(entity => entity.Component).NotNull();
RuleFor(entity => entity.Title).NotNull();
RuleFor(entity => entity.Description).NotNull();
}
}
/// <summary>Validator instance</summary>
public static MonitoringEventValidator Validator = new MonitoringEventValidator();
#endregion
#region IExtensibleDataObject
[NonSerialized]
private ExtensionDataObject _theData;
public virtual ExtensionDataObject ExtensionData
{
get { return _theData; }
set { _theData = value; }
}
#endregion
}
}
|
a4b0b93413d82a921a798d4fc19f9d75ed255bee
|
C#
|
okanyalcinn/Paint_Misali
|
/Drawing_Tool/Tool_Pen.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Drawing_Tool
{
public partial class DrawingTool : Form
{
bool kalemButtonStart = false;
bool kalemCizStart = false;
private void _pnlKalem_Click(object sender, EventArgs e)
{
// PasifYap(); //Diğer butonları pasif yap
// kalemButtonStart = true;
// _pnlKalem.BorderStyle = BorderStyle.Fixed3D;
//#warning backcolor rengi ayarlayacaksın
// this.Cursor = Cursors.NoMove2D; //yukarı ok imleci
PanelClickEvents(_pnlKalem, ref kalemButtonStart, Cursors.NoMove2D);
}
void KalemMouseDown()
{
if (kalemButtonStart)
{
kalemCizStart = true;
}
}
int x_KalemCiz;
int Y_KalemCiz;
void KalemMouseMove(MouseEventArgs e)
{
Point _baslangicN = new Point(x_KalemCiz, Y_KalemCiz);
Point _bitisN = new Point(e.X, e.Y); // mouse yeni konumu
if (kalemCizStart && e.Button == MouseButtons.Left )
{
PenTool();
Graphics _gr = _picCizimAlani.CreateGraphics();
_gr.DrawLine(pencil, _baslangicN, _bitisN);
_gr.FillEllipse(new SolidBrush(_color), e.X - _LineSize / 2, e.Y - _LineSize / 2, _LineSize, _LineSize); //kalem,x,y,kalınlık,kalınlık
_gr.Dispose();
}
x_KalemCiz = e.X;
Y_KalemCiz = e.Y;
}
void KalemMouseUp()
{
ScreenShot(); //önceki yapılan çizimler silinmesin diye
}
}
}
|
29423465b9869166f60be1f7d4f17fe62e2198d2
|
C#
|
key-moon/cs-ctf-libraries
|
/CTFLibrary/Utils/Const.cs
| 2.9375
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
namespace CTFLibrary
{
public static class Const
{
public const string Digits = "0123456789";
public const string LowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
public const string UppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string PrintableLetters = "\t\n\r !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
public const string UnPrintableASCIILetters = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" + "\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff";
public const string HexLetters = Digits + "abcdefABCDEF";
public const string Base64Letters = UppercaseLetters + LowercaseLetters + Digits + "+/=";
}
}
|
3226b8a12cf951754afcd5ce0f2a06c15ce67f34
|
C#
|
ColinWade/rhinocommon
|
/examples/AutomationSample/SampleRhino/SampleRhinoCommand.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using Rhino;
using Rhino.Commands;
using Rhino.Geometry;
using Rhino.Input;
using Rhino.Input.Custom;
namespace SampleRhino
{
[
System.Runtime.InteropServices.Guid("efda8c97-1440-47f6-aa33-c024a7139d6a"),
CommandStyle(Style.Hidden)
]
public class SampleRhinoCommand : Command
{
public SampleRhinoCommand()
{
// Rhino only creates one instance of each command class defined in a
// plug-in, so it is safe to store a reference in a static property.
Instance = this;
}
/// <summary>
/// The only instance of this command.
/// </summary>
public static SampleRhinoCommand Instance
{
get;
private set;
}
/// <summary>
/// The command name as it appears on the Rhino command line.
/// </summary>
public override string EnglishName
{
get { return "SampleRhinoCommand"; }
}
/// <summary>
/// Rhino calls this function to run the command.
/// </summary>
protected override Result RunCommand(RhinoDoc doc, RunMode mode)
{
RhinoApp.WriteLine("{0} loaded.", SampleRhinoPlugIn.Instance.Name);
return Result.Success;
}
}
}
|
a682c274fcfc628bd347778527d026b5fe0b45bb
|
C#
|
navidnabavi/robina_speech
|
/RobinaSpeechServer/RobinaSpeechServer/RobinaSpeechServer/DataPublisher.cs
| 2.921875
| 3
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
namespace RobinaSpeechServer
{
public class DataPublisher
{
Socket socket; //udp socket
EndPoint endpoint;
System.Threading.Mutex mutex = new System.Threading.Mutex();
public DataPublisher(string host,string self,int port)
{
//socket.Bind(new IPEndPoint(IPAddress.Parse(self), port));
endpoint = new IPEndPoint(IPAddress.Parse(host), port);
//socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
init();
}
~DataPublisher()
{
if (socket != null)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
mutex.Close();
}
private void init()
{
do
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Conntecting to the {0}",endpoint);
socket.Connect(endpoint);
Console.WriteLine("Conntected to the host");
break;
}
catch (SocketException)
{
Console.WriteLine("address is invalid or network is not working");
System.Threading.Thread.Sleep(1000);
continue;
}
} while (true);
}
public void publish(Messages.Message d)
{
do
{
try
{
mutex.WaitOne();
StringWriter writer = new StringWriter();
Newtonsoft.Json.JsonSerializer serialization = new Newtonsoft.Json.JsonSerializer();
serialization.Serialize(writer, d);
//socket.SendTo(ASCIIEncoding.ASCII.GetBytes(writer.ToString()),endpoint);
socket.Send(ASCIIEncoding.ASCII.GetBytes(writer.ToString()));
mutex.ReleaseMutex();
}
catch (SocketException)
{
mutex.ReleaseMutex();
socket.Shutdown(SocketShutdown.Both);
socket.Close();
init();
continue;
}
} while (false);
}
}
}
|
bce0d7bff52d75325397bb1d749d4a87e789b910
|
C#
|
1141558/REST_API_CS
|
/DTO/MaterialDTO.cs
| 2.734375
| 3
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using nucleocs.Models;
namespace nucleocs.DTO
{
public class MaterialDTO{
public int MaterialId { get; set; }
public string Name { get; set; }
public List<int> FinishingId { get; set; }
public ICollection<Finishing> Finishings { get; set; }
public virtual ICollection<MaterialFinishingDTO> MaterialFinishingsDTO { get; set; }
public ICollection<FinishingDTO> FinishingsDTO { get; set; }
public MaterialDTO(){}
public MaterialDTO (int materialId, string name, ICollection<FinishingDTO> finishingsDTO){
this.MaterialId = materialId;
this.Name = name;
this.FinishingsDTO = new List<FinishingDTO>(finishingsDTO);
}
public MaterialDTO (int materialId, string name){
this.MaterialId = materialId;
this.Name = name;
}
public static MaterialDTO From(Material m) {
var finishings = new List<FinishingDTO>();
foreach(var mf in m.MaterialFinishings) {
finishings.Add(FinishingDTO.From(mf.Finishing));
}
return new MaterialDTO(m.MaterialId, m.Name, finishings);
}
}
}
|
cd022fe37e4bee5523121c27c37bc93e79fe984a
|
C#
|
Chroizen/Tugas7
|
/abstraction.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
// Compiler version 4.0, .NET Framework 4.5
namespace AbstractClass
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine("==== Hero DOTA ====");
Console.WriteLine();
Hero hero;
hero = new Strength();
hero.name();
hero.abilities();
hero.difficulty();
Console.WriteLine();
hero = new Agility();
hero.name();
hero.abilities();
hero.difficulty();
Console.WriteLine();
hero = new Intelligence();
hero.name();
hero.abilities();
hero.difficulty();
}
public abstract class Hero {
public abstract void name();
public abstract void abilities();
public abstract void difficulty();
}
public class Strength : Hero {
public override void name() {
Console.WriteLine("Name : Abaddon ");
}
public override void abilities() {
Console.WriteLine("Abilities : Mist Coil, Aphotic Shield, Curse of Avernus, Borrowed Time ");
}
public override void difficulty() {
Console.WriteLine("Difficulty : Normal ");
}
}
public class Agility : Hero {
public override void name() {
Console.WriteLine("Name : Ursa ");
}
public override void abilities() {
Console.WriteLine("Abilities : Earthshock, Overpower, Fury Swipes, Enrage ");
}
public override void difficulty() {
Console.WriteLine("Difficulty : Easy ");
}
}
public class Intelligence : Hero {
public override void name() {
Console.WriteLine("Name : Invoker ");
}
public override void abilities() {
Console.WriteLine("Abilities : Quas, Wex, Exort, Invoke ");
}
public override void difficulty() {
Console.WriteLine("Difficulty : Hard ");
}
}
}
}
|
00e964dd092329df490a767e8e2e06b2c9c7a29f
|
C#
|
beschoenen/school
|
/ALGA - Homework/week-1-recursion-beschoenen/1-Recursion-Test/FibonacciTest.cs
| 2.75
| 3
|
using ALGA;
using NUnit.Framework;
namespace ALGA_test
{
[Category("Fibonacci"), Timeout(1000)]
public class FibonacciTest
{
[Test]
public void FibonacciRecursiveNegative()
{
Assert.AreEqual(0, Fibonacci.fibonacci_recursive(-5));
}
[Test]
public void FibonacciRecursive()
{
Assert.AreEqual(0, Fibonacci.fibonacci_recursive(0));
Assert.AreEqual(1, Fibonacci.fibonacci_recursive(1));
Assert.AreEqual(1, Fibonacci.fibonacci_recursive(2));
Assert.AreEqual(2, Fibonacci.fibonacci_recursive(3));
Assert.AreEqual(3, Fibonacci.fibonacci_recursive(4));
Assert.AreEqual(5, Fibonacci.fibonacci_recursive(5));
Assert.AreEqual(8, Fibonacci.fibonacci_recursive(6));
Assert.AreEqual(13, Fibonacci.fibonacci_recursive(7));
Assert.AreEqual(21, Fibonacci.fibonacci_recursive(8));
Assert.AreEqual(34, Fibonacci.fibonacci_recursive(9));
Assert.AreEqual(55, Fibonacci.fibonacci_recursive(10));
}
[Test]
public void FibonacciIterativeNegative()
{
Assert.AreEqual(0, Fibonacci.fibonacci_iterative(-5));
}
[Test]
public void FibonacciIterative()
{
Assert.AreEqual(0, Fibonacci.fibonacci_iterative(0));
Assert.AreEqual(1, Fibonacci.fibonacci_iterative(1));
Assert.AreEqual(1, Fibonacci.fibonacci_iterative(2));
Assert.AreEqual(2, Fibonacci.fibonacci_iterative(3));
Assert.AreEqual(3, Fibonacci.fibonacci_iterative(4));
Assert.AreEqual(5, Fibonacci.fibonacci_iterative(5));
Assert.AreEqual(8, Fibonacci.fibonacci_iterative(6));
Assert.AreEqual(13, Fibonacci.fibonacci_iterative(7));
Assert.AreEqual(21, Fibonacci.fibonacci_iterative(8));
Assert.AreEqual(34, Fibonacci.fibonacci_iterative(9));
Assert.AreEqual(55, Fibonacci.fibonacci_iterative(10));
}
}
}
|
feee03518234d943750e4379014500541680f47e
|
C#
|
AndreiLisiutin/FRI3NDS.Angular4Template
|
/FRI3NDS.Angular4Template.Cloner/Program.cs
| 2.53125
| 3
|
using FRI3NDS.Angular4Template.Cloner.Cloner;
using FRI3NDS.Angular4Template.Cloner.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace FRI3NDS.Angular4Template.Cloner
{
class Program
{
static void Main(string[] args)
{
IConfigurationRoot configuration = LoadConfiguration();
IServiceProvider provider = ServiceConfiguration.CreateServiceProvider(configuration);
ICloner cloner = provider.GetService<ICloner>();
cloner.CloneSolution();
Console.ReadKey();
}
/// <summary>
/// Загрузить конфигурацию проекта.
/// </summary>
/// <returns>Конфигурация проекта.</returns>
private static IConfigurationRoot LoadConfiguration()
{
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true)
.AddEnvironmentVariables();
return builder.Build();
}
}
}
|
85a63b86f97598d327bb46d3c153777b95fe2cb7
|
C#
|
Devin-X/tada
|
/Questions/303-RangeSumQuery.cs
| 3.78125
| 4
|
using System;
namespace questions
{
// Question URL: https://leetcode.com/problems/range-sum-query-immutable/description/
//Given an integer array nums, find the sum of the elements
//between indices i and j(i ≤ j), inclusive.
//Example:
//Given nums = [-2, 0, 3, -5, 2, -1]
//sumRange(0, 2) -> 1
//sumRange(2, 5) -> -1
//sumRange(0, 5) -> -3
//Note:
//You may assume that the array does not change.
//There are many calls to sumRange function.
public class NumArray
{
// Concept Dynamic programming
int[] _nums;
int[] _sumNum;
public NumArray(int[] nums)
{
_nums = nums;
_sumNum = new int[nums.Length + 1];
_sumNum[0] = 0;
for (int i = 1; i < _sumNum.Length; i++)
{
_sumNum[i] = _sumNum[i - 1] + nums[i - 1];
}
}
public int sumRange(int i, int j)
{
if (i < 0 || j >= _nums.Length)
{
return 0;
}
return _sumNum[j + 1] - _sumNum[i];
}
}
}
|
62fe3b5ee5871de1c7879d030053fe64fd009974
|
C#
|
oleksiikrutykh/wp_base_tools
|
/Sources/PhoneApp14/BinarySerializing/CustomTypes/NullableSerializer.cs
| 3.125
| 3
|
namespace BinarySerializing.CustomTypes
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
internal class NullableSerializer : AbstractTypeSerializer
{
private LazyLoadSerializer valueSerializer;
public NullableSerializer(Type nullableValueType)
{
this.valueSerializer = new LazyLoadSerializer(nullableValueType);
}
public static AbstractTypeSerializer TryCreate(Type type, TypeInfo typeInfo)
{
AbstractTypeSerializer serializer = null;
if (typeInfo.IsGenericType)
{
var isNullable = typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>);
if (isNullable)
{
var valueType = typeInfo.GenericTypeArguments[0];
serializer = new NullableSerializer(valueType);
}
}
return serializer;
}
public override object Deserialzie(System.IO.BinaryReader reader)
{
object result = null;
var hasValue = reader.ReadBoolean();
if (hasValue)
{
result = this.valueSerializer.Serializer.Deserialzie(reader);
}
return result;
}
public override void Serialize(System.IO.BinaryWriter writer, object data)
{
var hasValue = data != null;
writer.Write(hasValue);
if (hasValue)
{
this.valueSerializer.Serializer.Serialize(writer, data);
}
}
}
}
|
6a9f00b2c8bfc588b93d42fa9fbd31c113dd20ae
|
C#
|
School-Works-On-Programming/comp123-s2016-lesson2
|
/COMP123-S2016-Lesson2/Program.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/**
*
* Author: Christopher Ritchil
* Date: May 17, 2016
* Date Modified: May 17, 2016
* Description: Advance Method Demo for Lesson 2
*
* Version: 0.0.4 - Added readUntilEnd - not completed
*
*/
namespace COMP123_S2016_Lesson2
{
/**
* Main driver class for Lesson 2
*
* @class Program
*/
public class Program
{
/**
*
* Main method for our drive class
*
* @constructor Main
* @param {string[]} args
*
*/
static void Main(string[] args)
{
int x = 50;
int y = 40;
int result = 0;
result = addXandY(x, y);
Console.WriteLine(result);
Console.WriteLine();
addYtoX(ref x, ref y);
Console.WriteLine(x);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(readUntilEnd());
}
/**
* Simple method to add two values
*
* @method addXandY
* @param {int} fNum
* @param {int} sNum
*
*/
public static int addXandY(int fNum, int sNum)
{
int result = 0;
result = fNum + sNum;
return result;
}
/**
* Simple method to demonstrate pass by ref keyword
*
* @method addYtoX
* @param {ref int} X
* @param {ref int} Y
*/
public static int addYtoX(ref int X, ref int Y)
{
X += Y;
return X;
}
public static string[] readUntilEnd()
{
string[] inputs = new string[50];
int inputCounter = 0;
do
{
Console.WriteLine("Enter a value - ('end' to stop)");
inputs[inputCounter] = Console.ReadLine();
if(inputs[inputCounter]=="end")
{
inputCounter = -1;
}else
{
inputCounter++;
}
} while (inputCounter != -1);
return inputs;
}
}
}
|
ab999a5677d93074ca5db921d586fdade3ef1186
|
C#
|
pablothedolphin/Scriptable-Console
|
/Scriptable Console/Assets/Scriptable Console/API/Scripts/DeveloperConsole.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace ScriptableFramework.DeveloperConsole
{
/// <summary>
///
/// </summary>
public class DeveloperConsole
{
/// <summary>
///
/// </summary>
protected readonly IEnumerable<IConsoleCommand> commands;
/// <summary>
///
/// </summary>
/// <param name="commands"></param>
public DeveloperConsole (IEnumerable<IConsoleCommand> commands)
{
this.commands = commands;
}
/// <summary>
///
/// </summary>
/// <param name="inputValue"></param>
/// <returns></returns>
public bool ProcessCommand (string inputValue)
{
string[] inputSplit = inputValue.Split (' ');
string commandInput = inputSplit[0];
string[] args = inputSplit.Skip (1).ToArray ();
return ProcessCommand (commandInput, args);
}
/// <summary>
///
/// </summary>
/// <param name="commandInput"></param>
/// <param name="args"></param>
/// <returns></returns>
public bool ProcessCommand (string commandInput, string[] args)
{
foreach (var command in commands)
{
if (!commandInput.Equals (command.CommandWord, StringComparison.OrdinalIgnoreCase))
{
continue;
}
return command.Process (args);
}
return false;
}
}
}
|
cd367f902a67903beffea761a3aa9999dadba0a2
|
C#
|
pedrolimajesus/template
|
/Shrike/Common/TAC/TAC/Interfaces/Scheduling.cs
| 2.515625
| 3
|
// //
// // Copyright 2012 David Gressett
// //
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// //
// // http://www.apache.org/licenses/LICENSE-2.0
// //
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Newtonsoft.Json;
using log4net;
namespace AppComponents
{
public class Recurrence
{
private DebugOnlyLogger _dblog;
private ILog _log;
public Recurrence()
{
DaysOfMonth = null;
DaysOfWeek = null;
MonthsLater = 0;
DaysLater = 0;
HoursLater = 0;
MinutesLater = 0;
AtFixedTime = DateTime.MinValue;
_log = ClassLogger.Create(GetType());
_dblog = DebugOnlyLogger.Create(_log);
}
public int[] DaysOfMonth { get; set; }
public int[] DaysOfWeek { get; set; }
public int MonthsLater { get; set; }
public int DaysLater { get; set; }
public int HoursLater { get; set; }
public int MinutesLater { get; set; }
public DateTime AtFixedTime { get; set; }
public static Recurrence OnDaysOfMonth(params int[] days)
{
Contract.Requires(days.All(d => d >= 1 && d <= 31));
return new Recurrence {DaysOfMonth = days};
}
public static Recurrence OnDaysOfWeek(params DayOfWeek[] days)
{
return new Recurrence {DaysOfWeek = days.Distinct().Cast<int>().ToArray()};
}
public static Recurrence InMonths(int monthsFromNow)
{
return new Recurrence {MonthsLater = monthsFromNow};
}
public static Recurrence InDays(int daysFromNow)
{
return new Recurrence {DaysLater = daysFromNow};
}
public static Recurrence InHours(int hoursFromNow)
{
return new Recurrence {HoursLater = hoursFromNow};
}
public Recurrence SetToFixedTime(int hour, int minute)
{
AtFixedTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, hour, minute, 0);
return this;
}
public DateTime GetNextRecurrence()
{
return GetNextRecurrence(DateTime.UtcNow);
}
public DateTime GetNextRecurrence(DateTime baseTime)
{
DateTime recurrence = baseTime;
if (DaysOfMonth != null)
{
var findDay = (from d in DaysOfMonth where d > recurrence.Day select d).FirstOrDefault();
if (findDay == 0)
{
recurrence = recurrence.AddMonths(1);
findDay = (from d in DaysOfMonth where d > recurrence.Day select d).FirstOrDefault();
}
if (findDay == 0)
{
var err = string.Format("Cannot find day of month recurrence for recurrence: {0}", ToString());
_log.Error(err);
throw new ArgumentOutOfRangeException(err);
}
if (findDay > DateTime.DaysInMonth(baseTime.Year, baseTime.Month))
findDay = DateTime.DaysInMonth(baseTime.Year, baseTime.Month);
recurrence = new DateTime(recurrence.Year, recurrence.Month, findDay, recurrence.Hour, recurrence.Minute,
recurrence.Second);
}
else if (DaysOfWeek != null)
{
if (!DaysOfWeek.All(d => d >= (int) DayOfWeek.Sunday && d <= (int) DayOfWeek.Saturday))
{
var err = string.Format("Cannot find day of week recurrence for recurrence {0}", ToString());
_log.Error(err);
throw new ArgumentOutOfRangeException(err);
}
while (!DaysOfWeek.Contains((int) recurrence.DayOfWeek))
recurrence = recurrence.AddDays(1.0);
}
else
{
if (MonthsLater > 0) recurrence = recurrence.AddMonths(MonthsLater);
if (DaysLater > 0) recurrence = recurrence.AddDays(DaysLater);
if (HoursLater > 0) recurrence = recurrence.AddHours(HoursLater);
if (MinutesLater > 0) recurrence = recurrence.AddMinutes(MinutesLater);
}
if (AtFixedTime != DateTime.MinValue)
{
recurrence = new DateTime(recurrence.Year, recurrence.Month, recurrence.Day, AtFixedTime.Hour,
AtFixedTime.Minute, AtFixedTime.Second);
if (recurrence < DateTime.UtcNow)
recurrence = recurrence.AddDays(1.0);
}
_dblog.InfoFormat("Recurrence {0} from base time {1} next {2}", ToString(), baseTime, recurrence);
return recurrence;
}
}
public class ScheduledItem
{
public const string MutexName = "scheduledjobs";
public ScheduledItem(string uniqueName, string message, Type type, string route, DateTime time,
Recurrence r = null)
{
UniqueName = uniqueName;
Message = message;
Route = route;
Type = type;
Time = time;
Recurrence = (r == null) ? string.Empty : JsonConvert.SerializeObject(r);
}
public ScheduledItem()
{
}
public string Id { get; set; }
public string Message { get; set; }
public string Route { get; set; }
public Type Type { get; set; }
public DateTime Time { get; set; }
public string Recurrence { get; set; }
public string UniqueName { get; set; }
}
public interface IJobScheduler
{
void ScheduleJob<T>(T jobInfo, DateTime schedule, Recurrence r = null, string jobRoute = null) where T : class;
void ScheduleJobOnlyOnce<T>(string uniqueName, T jobInfo, DateTime schedule, Recurrence r = null,
string jobRoute = null) where T : class;
IEnumerable<ScheduledItem> GetDue();
IEnumerable<ScheduledItem> GetAll();
void Reschedule(ScheduledItem item);
void Cancel(ScheduledItem item);
}
}
|
521263cdfad289ba90528bf79045eff2f418385c
|
C#
|
AiPEX-Lab-CMU/CityScene
|
/Assets/Supermarket_Hemang/Scripts/ShoppingList.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShoppingList : MonoBehaviour
{
public List<string> items;
// Start is called before the first frame update
void Start()
{
items = new List<string>();
}
public void generateShoppingList()
{
System.Random rand = new System.Random();
int index = rand.Next(4);
ProfileController pc = gameObject.GetComponentInParent<ProfileController>();
KeyValuePair<string, List<double>> prob = pc.getProfile(index);
double final_prob = rand.NextDouble();
Debug.Log(prob.Key + ":" + final_prob);
for (int i = 0; i < prob.Value.Count; i++)
{
int rand_var = rand.Next(2);
if ((prob.Value[i] * rand_var) >= (final_prob))
{
items.Add(pc.items[i]);
}
}
}
public void generateShoppingListBySoftmax()
{
System.Random rand = new System.Random();
int index = rand.Next(4);
ProfileController pc = gameObject.GetComponentInParent<ProfileController>();
KeyValuePair<string, List<double>> prob = pc.getProfile(index);
double final_prob = rand.NextDouble();
int maxItems = rand.Next(15);
while(maxItems==0)
{
maxItems = rand.Next(15);
}
int count = 0;
while(count<maxItems)
{
List<KeyValuePair<int, double>> map = createSoftmaxMap(prob.Value);
map.Sort((pair1, pair2) => pair1.Value.CompareTo(pair2.Value));
double remaining = final_prob;
for(int i=0; i<map.Count; i++)
{
int rv = rand.Next(2);
double probability = rv * map[i].Value;
if(!probability.Equals(0) && probability<=remaining)
{
count++;
items.Add(pc.items[map[i].Key]);
prob.Value[map[i].Key] = probability / 2;
remaining -= probability;
if (count == maxItems || remaining.Equals(0))
break;
}
}
}
Debug.Log("ItemCount : " + items.Count);
}
List<KeyValuePair<int,double>> createSoftmaxMap(List<double> probs)
{
List<KeyValuePair<int, double>> map = new List<KeyValuePair<int, double>>();
double total = 0;
foreach(double d in probs)
{
total += d;
}
for(int i=0; i<probs.Count; i++)
{
KeyValuePair<int, double> temp = new KeyValuePair<int, double>(i, (probs[i] / total));
map.Add(temp);
}
return map;
}
// Update is called once per frame
void Update()
{
}
}
|
76783bcb2605dd629edc11136807c27af94e42c6
|
C#
|
jmpEA31/GroundRouteFinder
|
/GroundRouteFinder/Output/RouteWriter.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GroundRouteFinder.Output
{
public abstract class RouteWriter : InvariantWriter
{
public static RouteWriter Create(int type, string path, string allSizes = "", int cargo = -1, int military = -1, string designator = "", string parkingCenter = "")
{
switch (type)
{
case 0:
return new KmlWriter(path);
case 1:
default:
return new TxtWriter(path, allSizes, cargo, military, designator, parkingCenter);
}
}
/// <summary>
/// Create a routewriter
/// </summary>
/// <param name="path"></param>
public RouteWriter(string path, Encoding encoding)
: base(path, encoding)
{
}
public abstract void Write(SteerPoint steerPoint);
}
}
|
5082a325e5dd67da417b8cde2cc13fecd7f7d2ee
|
C#
|
hloiseau/AirTech
|
/AirTech/Server/Controllers/TravelController.cs
| 2.734375
| 3
|
using AirTech.Server.DAO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
namespace AirTech.Server.Controllers
{
[ApiController]
[Route("[controller]")]
public class TravelController : Controller
{
private readonly ILogger _logger;
private readonly TravelDAO _dao;
public TravelController(TravelDAO context, ILogger<TravelController> logger)
{
this._logger = logger;
this._dao = context;
}
/// <summary>
/// Returns a list of all Travels
/// </summary>
/// <returns></returns>
[HttpGet(Name = "GetTravels")]
public async System.Threading.Tasks.Task<IEnumerable<Shared.Travel>> GetTravelsAsync()
{
try
{
return await _dao.GetTravels();
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
return null;
}
}
/// <summary>
/// Returns the Travel coresponding to the given Id
/// </summary>
/// <param name="id">whanted travel Id</param>
/// <returns></returns>
[HttpGet("{id}", Name = "GetTravelById")]
public Shared.Travel GetTravelById(int id)
{
try
{
return _dao.GetTravelsById(id);
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
return null;
}
}
}
}
|
e23cc0292b505f6125b61ac34f195bac7b43db9f
|
C#
|
zestt132hp/PatternsOfDesign
|
/PatternsOfDesign/Behavior patterns/Strategy/Context.cs
| 2.859375
| 3
|
using PatternsOfDesign.Behavior_patterns.Strategy.Strategies;
namespace PatternsOfDesign.Behavior_patterns.Strategy
{
class Context
{
private IStrategy _strategy;
public Context(IStrategy strategy)
{
_strategy = strategy;
}
public void ChangeStrategy(IStrategy strategy)
{
_strategy = strategy;
}
public int ExecuteStrategy(int a, int b)
{
return _strategy.Execute(a, b);
}
}
}
|
94f7214cd9d2fec42eb1bb321e89db4eb908c0c7
|
C#
|
joaonc/jdn45common
|
/Jdn45Common/Jdn45Common/FileAssociation/FileAssociationUtil.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Jdn45Common;
namespace Jdn45Common.FileAssociation
{
public static class FileAssociationUtil<T>
{
/// <summary>
/// The function that associates a name (directory or file) with its association.
/// This can be anything: a DB call, read file and get contents, etc.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
/// <returns></returns>
public delegate T Associator(string name);
/// <summary>
/// The function that writes to a string the associated object.
/// </summary>
/// <param name="association"></param>
/// <returns></returns>
public delegate string AssociationWriter(T association);
private static void SetParent(FileAssociationNode<T> node, FileAssociationNode<T> parent)
{
node.Parent = parent;
foreach (FileAssociationNode<T> subNode in node.Nodes)
{
SetParent(subNode, node);
}
}
public static FileAssociationRootNode<T> LoadFileAssociationNode(string fileName)
{
FileAssociationRootNode<T> fileAssociationRootNode =
(FileAssociationRootNode<T>)Util.DeserializeFromXmlFile(fileName, typeof(FileAssociationRootNode<T>));
SetParent(fileAssociationRootNode, null);
return fileAssociationRootNode;
}
public static void SaveFileAssociation(FileAssociationRootNode<T> fileAssociationRootNode, string fileName)
{
Util.SerializeToXmlFile(fileAssociationRootNode, fileName);
}
}
}
|
354e6a3c693ff44be3b895b6bcb3809762f61971
|
C#
|
shendongnian/download4
|
/first_version_download2/229926-18053262-44831508-2.cs
| 2.6875
| 3
|
public class Column
{
private Source _Source = new Source();
private Destination _Destination = new Destination();
public Source Source { get { return _Source; } }
public Destination Destination { get { return _Destination; } }
}
public class Source
{
public string Name { get; set; }
public string Type { get; set; }
}
public class Destination
{
public string Name { get; set; }
public string Type { get; set; }
}
|
d020057c6b8837dc88ce5d658aaa95e6d7e30b4e
|
C#
|
rorymacleod/AdventOfCode2019
|
/Tests/Day02Tests.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;
namespace AdventOfCode2019.Tests
{
public class Day02Tests
{
[Theory]
[InlineData(14, 2)]
[InlineData(1969, 966)]
[InlineData(100756, 50346)]
public void Returns_fuel_for_known_masses_including_fuel_masses(int mass, int expected)
{
// Act
var app = new Day02();
app.AddMass(mass);
app.Fuel.Should().Be(expected);
}
[Fact]
public void Returns_fuel_for_combined_masses_with_fuel()
{
// Act
var app = new Day02();
app.AddMass(14);
app.AddMass(1969);
app.AddMass(100756);
app.Fuel.Should().Be(2 + 966 + 50346);
}
}
}
|
01b7bf1dbcdd98534b26cd15519521a896b9fbd8
|
C#
|
dalenewman/Transformalize
|
/src/Transformalize/Extensions/StringExtensions.cs
| 3.09375
| 3
|
#region license
// Transformalize
// Configurable Extract, Transform, and Load
// Copyright 2013-2019 Dale Newman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Collections.Generic;
using System.Linq;
namespace Transformalize.Extensions {
public static class StringExtensions {
public static string Left(this string s, int length) {
return s.Length > length ? s.Substring(0, length) : s;
}
public static string Right(this string s, int length) {
return s.Length > length ? s.Substring(s.Length - length, length) : s;
}
public static bool IsNumeric(this string value) {
return double.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out double retNum);
}
public static bool In(this string value, params string[] args) {
if (args == null || args.Length == 0)
return false;
return args.Any(s => s == value);
}
/// <summary>
/// Credit to Marc Cliftlon
/// http://www.marcclifton.com/
/// http://www.codeproject.com/Members/Marc-Clifton
/// </summary>
public static string[] DelimiterSplit(this string src, char delimeter, char quote = '\"') {
var result = new List<string>();
var index = 0;
var start = 0;
var inQuote = false;
while (index < src.Length) {
if ((!inQuote) && (src[index] == delimeter)) {
result.Add(src.Substring(start, index - start).Trim());
start = index + 1; // Ignore the delimiter.
}
if (src[index] == quote) {
inQuote = !inQuote;
}
++index;
}
// The last part.
if (!inQuote) {
result.Add(src.Substring(start, index - start).Trim());
}
return result.ToArray();
}
public static IEnumerable<string> SplitLine(this string line, char delimiter, bool quoted) {
return quoted ? line.DelimiterSplit(delimiter) : line.Split(delimiter);
}
}
}
|
e85ae257a9b5b583395fb03deb6965fe261344a2
|
C#
|
OlyaNikolaeva/ProjectBot
|
/EmotienBot/EmotienBot/Program.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types.ReplyMarkups;
namespace EmotienBot
{
class Program
{
static ITelegramBotClient botClient;
public static Dictionary<int, UserInfo> UserInfos;
public static UserService<Human> Service;
public static FileService<Photo> PhotoService;
public static EmotionService<Emotion> EmotionService;
public static void Main()
{
botClient = new TelegramBotClient("637745165:AAF0CMMeHQIuOHk_4w44n17uM2q6mEj5Vt8");
var me = botClient.GetMeAsync().Result;
Console.WriteLine(
$"Hello, World! I am user {me.Id} and my name is {me.FirstName}."
);
Service = new UserService<Human>();
PhotoService = new FileService<Photo>();
UserInfos = new Dictionary<int, UserInfo>();
botClient.OnMessage += Bot_OnMessage;
botClient.StartReceiving();
Thread.Sleep(int.MaxValue);
}
public static async void Bot_OnMessage(object sender, MessageEventArgs e)
{
var dateCurrent = DateTime.Today;
var listPeople = Service.GetAll();
var senderId = e.Message.From.Id;
UserInfos.TryGetValue(senderId, out var userInfo);
if (userInfo == null)
{
userInfo = new UserInfo
{
Emotion = new Emotion(),
Human = new Human(),
Step = 0,
Photo = new Photo()
};
UserInfos.Add(senderId, userInfo);
userInfo.Human.SenderId = senderId;
userInfo.Human.Date = dateCurrent;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Привет, меня зовут Гриша-Голубь и я являюсь ботом, который распознает твои эмоции по фотографии, которую ты мне отправищь)"
);
//var listPeople = Service.GetAll();
foreach (var i in listPeople)
{
if (userInfo.Human.SenderId == i.SenderId)
{
userInfo.Step = 4;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Вы уже записаны в базе.Рады вас снова видеть) "
);
return;
}
else
{
userInfo.Step = 0;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Рады с вами познакомится) Позвольте записать вас в базу"
);
return;
}
}
}
if (userInfo.Step == 0)
{
userInfo.Step++;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Начнем?"
);
return;
}
if (userInfo.Step == 1)
{
if (e.Message.Text == "да" || e.Message.Text == "Да" || e.Message.Text == "Yes")
{
userInfo.Step++;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Отлично, как тебя зовут?"
);
return;
}
if (e.Message.Text == "нет" || e.Message.Text == "Нет" || e.Message.Text == "No")
{
userInfo.Step++;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Так, кто бы ты ни был, ты ОФИГЕЛ!!! Я тут значит работаю, твои эмоции пытаюсь просканировать, а ты со мной разговаривать значит не хочешь??? У тя просто ннет выбора) Как тебя зовут незнакомец?"
);
return;
}
else
{
userInfo.Step++;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Я не бэлмэс тебяя, но сочту твой ответ за Да) Как тебя зовут, незнакомец?"
);
return;
}
}
if (userInfo.Step == 2)
{
var name = e.Message.Text;
userInfo.Human.Name = name;
userInfo.Step++;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Отлично, а какая у вас фамилия, ну или ник???"
);
return;
}
if (userInfo.Step == 3)
{
var lastName = e.Message.Text;
userInfo.Human.LastName = lastName;
Service.Save(userInfo.Human);
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Отлично, у меня есть необходимые данные, чтобы внести вас в базу"
);
userInfo.Step++;
}
if (userInfo.Step == 4)
{
userInfo.Step++;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Пришлите мне вашу фотку"
);
return;
}
if (userInfo.Step == 5)
{
if (e.Message.Photo != null)
{
var photos = e.Message.Photo;
var photo = photos[photos.Length - 1];
var fileId = photo.FileId;
var photoIdentifier = Guid.NewGuid();
using (var fileStream = System.IO.File.OpenWrite($"files\\{photoIdentifier}.jpg"))
{
var fileInfo = await botClient.GetInfoAndDownloadFileAsync(
fileId: fileId,
destination: fileStream
);
}
userInfo.Photo.Path = $"files\\{photoIdentifier}.jpg";
userInfo.Photo.DateCreate = dateCurrent;
userInfo.Photo.UserId = 1;
PhotoService.Save(userInfo.Photo);
}
userInfo.Step++;
}
if (userInfo.Step == 6)
{
if (userInfo.Photo.Path == null)
{
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Че блин????"
);
userInfo.Step = 4;
}
else
{
var emotionGuy = new StartEmotionsAPI();
var currentEmotion = await emotionGuy.Start(userInfo.Photo.Path);
var maxEm = new MaxEmotionKek();
string g = maxEm.Max(currentEmotion);
var ty = new EmotionToString();
var type = ty.ToStringEm(g);
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: type
);
userInfo.Step++;
}
}
if (userInfo.Step == 7)
{
userInfo.Step++;
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Что ты хочешь сделать дальше?",
replyMarkup: new ReplyKeyboardMarkup
{
Keyboard = new[]
{
new []
{
new KeyboardButton("Хочу получить фото обратно"),
new KeyboardButton("Устал"),
},
new []
{
new KeyboardButton("Хочу отправить фото снова"),
new KeyboardButton("Хочу кофе")
},
}
}
);
return;
}
if (userInfo.Step == 8)
{
if (e.Message.Text == "Хочу получить фото обратно")
{
await botClient.SendPhotoAsync(
chatId: e.Message.Chat,
File.OpenRead(userInfo.Photo.Path),
replyMarkup: new ReplyKeyboardRemove()
);
}
if (e.Message.Text == "Устал")
{
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Иди поспи",
replyMarkup: new ReplyKeyboardRemove()
);
}
if (e.Message.Text == "Хочу отправить фото сново")
{
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Ок, я готов",
replyMarkup: new ReplyKeyboardRemove()
);
userInfo.Step = 4;
}
if (e.Message.Text == "Хочу кофе")
{
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: "Советую сходить в Coffe Bean,говорят там скидки)",
replyMarkup: new ReplyKeyboardRemove()
);
}
userInfo.Step++;
}
if (userInfo.Step == 9)
{
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: $"Теперь я устал, если хочешь еще поболтать, напиши мне попозже"
);
userInfo.Step = 4;
}
}
}
}
|
9ddb91cfe508df5c2d1dc32186d2f2580e4d7e9e
|
C#
|
cmcquillan/SmtpPilot
|
/src/SmtpPilot.Server/Delegates.cs
| 2.796875
| 3
|
namespace SmtpPilot.Server
{
/// <summary>
/// Delegate that plugs into <see cref="SMTPServer"/> that fires when a new client connects to the server.
/// </summary>
/// <param name="sender">The <see cref="SMTPServer"/> instance that receives the client connection.</param>
/// <param name="eventArgs">A <see cref="MailClientConnectedEventArgs"/> object.</param>
public delegate void MailClientConnectedEventHandler(object sender, MailClientConnectedEventArgs eventArgs);
/// <summary>
/// Delegate that plugs into <see cref="SMTPServer"/> that fires when a client disconnects from the server.
/// </summary>
/// <param name="sender">The <see cref="SMTPServer"/> instance from which the client disconnected.</param>
/// <param name="eventArgs">A <see cref="MailClientDisconnectedEventArgs"/> object.</param>
public delegate void MailClientDisconnectedEventHandler(object sender, MailClientDisconnectedEventArgs eventArgs);
/// <summary>
/// Delegate that plugs into the <see cref="SMTPServer"/> and is handed to the <see cref="SmtpPilot.Server.States.ISmtpStateContext"/> instance that fires when an email is completed and processed.
/// </summary>
/// <param name="sender">The <see cref="SmtpPilot.Server.States.ISmtpStateContext"/> object that fired the event.</param>
/// <param name="eventArgs">A <see cref="EmailProcessedEventArgs"/> object.</param>
public delegate void EmailProcessedEventHandler(object sender, EmailProcessedEventArgs eventArgs);
/// <summary>
/// Delegate that plugs into the <see cref="SMTPServer"/> and is fired when the server is started. This is fired as soon as the worker thread is initialized and running.
/// </summary>
/// <remarks>Server start time is rather minimal, so most applications will not need explicit access to this information.
/// Use this if you application needs precise timing knowledge of when the server is ready and listening.</remarks>
/// <param name="sender">A reference to <see cref="SMTPServer"/> firing the event.</param>
/// <param name="eventArgs">A <see cref="ServerEventArgs"/> object.</param>
public delegate void ServerStartedEventHandler(object sender, ServerEventArgs eventArgs);
/// <summary>
/// Delegate that plugs into the <see cref="SMTPServer"/> and is fired when the server is stopped.
/// This is fired as soon as the worker thread has completed its final loop, right before releasing it back to the thread pool.
/// </summary>
/// <param name="sender">A reference to <see cref="SMTPServer"/> firing the event.</param>
/// <param name="eventArgs">A <see cref="ServerEventArgs"/> object.</param>
public delegate void ServerStoppedEventHandler(object sender, ServerEventArgs eventArgs);
}
|
18e173773e94a0c97ffa787735f29a1ecfb159db
|
C#
|
tilmanbeyyer/WU_Aufbereitung
|
/Verarbeiter/Verarbeiter/Schueler.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Text;
namespace Verarbeiter
{
class Schueler
{
private string nachname;
private string vorname;
private string klasse;
private Fehlzeit[] fehlzeit;
public Schueler(string nachname, string vorname, string klasse, Fehlzeit[] fehlzeit)
{
this.nachname = nachname;
this.vorname = vorname;
this.klasse = klasse;
this.fehlzeit = new Fehlzeit[5];
}
#region Getter/Setter
public string Nachname { get => nachname; set => nachname = value; }
public string Vorname { get => vorname; set => vorname = value; }
public string Klasse { get => klasse; set => klasse = value; }
internal Fehlzeit[] Fehlzeit { get => fehlzeit; set => fehlzeit = value; }
#endregion
}
}
|
ab6eee2bf874d7be5af75403090fa81ec22f5f7b
|
C#
|
lpestl/SimpleTasks
|
/Task051/albert_davletov/Program.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task51_AnswerFromTheAuthor
{
class Program
{
public class WorkTime
{
public int FirstTime { get; set; } // время упаковки заказа Алисой
public int SecondTime { get; set; } // время доставки заказа Бобом
}
public static bool ComparePairs(WorkTime a, WorkTime b)
{
int minOfMin = Math.Min(Math.Min(a.FirstTime, a.SecondTime), Math.Min(b.FirstTime, b.SecondTime));
if (minOfMin == a.FirstTime || minOfMin == b.SecondTime)
{
return false;
}
return true;
}
public static List<WorkTime> Sort(List<WorkTime> vector)
{
int i, j;
for (i = 0; i < vector.Count; i++)
{
for (j = i + 1; j < vector.Count; j++)
{
if (ComparePairs(vector[i], vector[j]))
{
var tmp = vector[i];
vector[i] = vector[j];
vector[j] = tmp;
}
}
}
return vector;
}
public static int GetMinDeliveryTime(List<WorkTime> vector)
{
var newVector = Sort(vector);
int sum = 0, a = 0;
for (int i = 0; i < newVector.Count; i++)
{
a += vector[i].FirstTime;
sum = Math.Max(a, sum) + vector[i].SecondTime;
}
return sum;
}
public static void Main()
{
Console.WriteLine("UniLecs");
var vector = new List<WorkTime>()
{
new WorkTime() { FirstTime = 4, SecondTime = 5 },
new WorkTime() { FirstTime = 4, SecondTime = 1 },
new WorkTime() { FirstTime = 30, SecondTime = 4 },
new WorkTime() { FirstTime = 6, SecondTime = 30 },
new WorkTime() { FirstTime = 2, SecondTime = 3 }
};
Console.WriteLine(GetMinDeliveryTime(vector));
}
}
}
|
b6f4af6500635cb5e0ef5b67fe5e1c890f9a1b1a
|
C#
|
deyan-yosifov/Deyan-Projects
|
/CSharp/FMI/GeometryBasics/Models/LineSegmentsIntersectionModel.cs
| 2.75
| 3
|
using GeometryBasics.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeometryBasics.Models
{
public class LineSegmentsIntersectionModel : ExampleModelBase
{
private const string name = "Алгоритъм за пресичане на множество отсечки.";
private const string description = @"Алгоритъмът следва следните стъпки:
1. Сортира крайщата на отсечките по височина.
2. Започвайки да ""мете"" с хоризонтална права отдолу-нагоре се добавят нови точки от крайщата на отсечките.
3. Добавените точки се пазят сортирани по хоризонтално съседство така, че на всяка стъпка да се търсят пресичанията само на съседни отсечки от новодобавените точки.
4. Намерените пресечници също се добавят към сортирания вертикален списък от точки.
5. При достигане на междинна точка от дадена отсечка се премахва от списъка на съседите точката от същата отсечка, която имат по-малка вертикална координата.
6. Алгоритъмът приключва при достигане на най-високата точка от ""метенето"".";
public LineSegmentsIntersectionModel()
: base(name, description, Activator.CreateInstance<LineSegmentsIntersection>)
{
}
}
}
|
43d98958f5f40696c3a01bfc4201fbd8b086944a
|
C#
|
esiole/MyGL
|
/MyGL/Shaders/Sources/PhongShaderSource.cs
| 3.078125
| 3
|
namespace MyGL
{
/// <summary>
/// Универсальный шейдер. Рассчитывает освещение по Фонгу. Работает с нормалями и материалами.
/// Поддерживает множество точечных источников света и прожекторов.
/// </summary>
public sealed class PhongShaderSource : IShaderSource
{
private const string vertexShaderSource = @"
#version 330 core
layout (location = 0) in vec3 aPosition;
layout (location = 1) in vec3 aNormal;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
varying vec3 FragPos;
varying vec3 Normal;
void main()
{
gl_Position = projection * view * model * vec4(aPosition, 1.0);
Normal = aNormal * mat3(transpose(inverse(model)));
FragPos = vec3(model * vec4(aPosition, 1.0));
}
";
private readonly string fragmentShaderSource = "";
/// <summary>
/// Получить исходный код вершинного шейдера.
/// </summary>
public string VertexShaderSource => vertexShaderSource;
/// <summary>
/// Получить исходный код фрагментного шейдера.
/// </summary>
public string FragmentShaderSource => fragmentShaderSource;
/// <summary>
/// Создание исходного кода шейдера Фонга.
/// </summary>
/// <param name="countPointLight">Количество точечных источников света.</param>
/// <param name="countSpotLight">Количество прожекторов.</param>
public PhongShaderSource(int countPointLight, int countSpotLight)
{
fragmentShaderSource = $@"
#version 330 core
struct Material
{{
vec3 ambient;
vec3 diffuse;
vec3 specular;
float shininess;
}};
struct DirLight
{{
vec3 ambient;
vec3 diffuse;
vec3 specular;
vec3 direction;
}};
struct PointLight
{{
vec3 ambient;
vec3 diffuse;
vec3 specular;
vec3 position;
float constant;
float linear;
float quadratic;
}};
struct SpotLight
{{
vec3 ambient;
vec3 diffuse;
vec3 specular;
vec3 direction;
vec3 position;
float cutOff;
float outerCutOff;
float constant;
float linear;
float quadratic;
}};
varying vec3 Normal;
varying vec3 FragPos;
uniform DirLight dirLight;
uniform PointLight pointLights[{countPointLight}];
uniform SpotLight spotLights[{countSpotLight}];
uniform Material material;
uniform vec3 viewPos;
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)
{{
vec3 lightDir = normalize(-light.direction);
float diff = max(dot(normal, lightDir), 0.0);
vec3 reflectDir = reflect(-lightDir, normal);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 ambient = light.ambient * material.ambient;
vec3 diffuse = light.diffuse * (diff * material.diffuse);
vec3 specular = light.specular * (spec * material.specular);
return (ambient + diffuse + specular);
}}
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{{
vec3 lightDir = normalize(light.position - fragPos);
float diff = max(dot(normal, lightDir), 0.0);
vec3 reflectDir = reflect(-lightDir, normal);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
float distance = length(light.position - fragPos);
float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
vec3 ambient = light.ambient * material.ambient;
vec3 diffuse = light.diffuse * (diff * material.diffuse);
vec3 specular = light.specular * (spec * material.specular);
ambient *= attenuation;
diffuse *= attenuation;
specular *= attenuation;
return (ambient + diffuse + specular);
}}
vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{{
vec3 lightDir = normalize(light.position - FragPos);
float diff = max(dot(normal, lightDir), 0.0);
vec3 reflectDir = reflect(-lightDir, normal);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
float distance = length(light.position - FragPos);
float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
float theta = dot(lightDir, normalize(-light.direction));
float epsilon = light.cutOff - light.outerCutOff;
float intensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);
vec3 ambient = light.ambient * material.ambient;
vec3 diffuse = light.diffuse * (diff * material.diffuse);
vec3 specular = light.specular * (spec * material.specular);
ambient *= attenuation;
diffuse *= attenuation * intensity;
specular *= attenuation * intensity;
return (ambient + diffuse + specular);
}}
void main()
{{
vec3 norm = normalize(Normal);
vec3 viewDir = normalize(viewPos - FragPos);
vec3 result = CalcDirLight(dirLight, norm, viewDir);
for(int i = 0; i < {countPointLight}; i++)
result += CalcPointLight(pointLights[i], norm, FragPos, viewDir);
for(int i = 0; i < {countSpotLight}; i++)
result += CalcSpotLight(spotLights[i], norm, FragPos, viewDir);
gl_FragColor = vec4(result, 1.0f);
}}
";
if (countPointLight == 0)
{
fragmentShaderSource = fragmentShaderSource.Replace("uniform PointLight pointLights[0];", "");
fragmentShaderSource = fragmentShaderSource.Replace("for(int i = 0; i < 0; i++)", "");
fragmentShaderSource = fragmentShaderSource.Replace("result += CalcPointLight(pointLights[i], norm, FragPos, viewDir);", "");
}
if (countSpotLight == 0)
{
fragmentShaderSource = fragmentShaderSource.Replace("uniform SpotLight spotLights[0];", "");
fragmentShaderSource = fragmentShaderSource.Replace("for(int i = 0; i < 0; i++)", "");
fragmentShaderSource = fragmentShaderSource.Replace("result += CalcSpotLight(spotLights[i], norm, FragPos, viewDir);", "");
}
}
}
}
|
184eac8880f618bac0fb5ab4242d516a739e06ab
|
C#
|
FabianoPretoJr/Etapa-Tecnica-GFT
|
/exerciciosGFT/exercicio1GFT/exercicio1GFT/Program.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace exercicio1GFT
{
class Program
{
static void Main(string[] args)
{
ValoresImpares vi = new ValoresImpares();
Console.WriteLine("Digite o valor inicial: ");
vi.Inicial = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Digite o valor final: ");
vi.Final = Convert.ToInt32(Console.ReadLine());
vi.Imprimiralores();
Console.ReadKey();
}
}
}
|
35e0675dfcb59f1d5fbf36ea20e8fac99ce22a0e
|
C#
|
IOneB/exam483
|
/chapter2. Types/Skill1_Create.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace exam483.chapter2._Types
{
class Skill1_Create
{
/* Структуры - нет конструктора по умолчанию, нельзя в структуре инициализировать переменные.
* Структуры хранятся в стэке (кроме замыкания), массив структур - непрерывный блок памяти
* Стек - это область памяти, которая выделяется и удаляется (просто отбрасывается) при входе и выходе из блоков
*/
public void Do()
{
}
}
}
|
f2dc3372eb36766e4bc8de4945b9b1520a6cfded
|
C#
|
shendongnian/download4
|
/code2/282292-5800257-12495434-2.cs
| 2.515625
| 3
|
private void searchBox_TextChanged(object sender, EventArgs e)
{
if (gridUsers.Rows.Count > 0)
{
foreach (UltraGridRow row in gridUsers.Rows)
{
if (Regex.IsMatch(row.Cells[1].Value.ToString(), searchBox.Text, RegexOptions.IgnoreCase))
{
gridUsers.Rows[indexCounter].Hidden = false;
}
else
{
gridUsers.Rows[indexCounter].Hidden = true;
}
}
}
}
|
32e66f01cb994f317caf75307ec501bfddfef77d
|
C#
|
rmit-s3585659-nicole-renner/Emerge_Educational_Game
|
/Assets/Scripts/ShopScript.cs
| 2.625
| 3
|
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ShopScript : MonoBehaviour {
public GameObject ShopPanel;
public Text cheeseCountText;
public GameObject productButton;
private Dictionary<string, Item> products;
private Dictionary<Item, GameObject> buttons;
void Awake()
{
products = new Dictionary<string, Item>();
buttons = new Dictionary<Item, GameObject>();
products["Slower Falls"] = new Item(30,1,0);
products["Stronger Feet"] = new Item(19,0,-1);
}
// Use this for initialization
void Start()
{
cheeseCountText.text = "Cheese Count: " + SaveLoad.savedCollectibles.ToString();
foreach (string product in products.Keys)
{
GameObject button = (GameObject)Instantiate(productButton, ShopPanel.transform);
button.GetComponentInChildren<Text>().text = product + "\n" + products[product].cost;
button.GetComponent<Button>().onClick.AddListener(() => Buy(products[product]));
Item i = products[product];
buttons[i] = button;
if (SaveLoad.savedCollectibles < i.cost)
{
Debug.Log("Too expensive");
button.GetComponent<Button>().interactable = false;
}
}
}
public void ReturnToMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
void Buy(Item obj)
{
SaveLoad.savedCollectibles = SaveLoad.savedCollectibles - obj.cost;
SaveLoad.Save();
buttons[obj].GetComponent<Button>().interactable = false;
}
}
public class Item {
public int cost;
int platformFallDelay;
int gravity;
public Item(int c, int fall, int grav)
{
cost = c;
platformFallDelay = fall;
gravity = grav;
}
}
|
26622e9500dfd65005779c1401970f30e0bfae6b
|
C#
|
jli103828/CollectJoe
|
/CollectJoe/ScoreList.cs
| 2.5625
| 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;
using System.IO;
namespace CollectJoe
{
public partial class frmScoreList : Form
{
private string _highScoreFilePath;
public frmScoreList(string scorePath)
{
InitializeComponent();
_highScoreFilePath = scorePath;
}
public void RefreshScore() {
if (_highScoreFilePath == "" || _highScoreFilePath == null || !File.Exists(_highScoreFilePath)){
txtScore.Text = "Rangliste nicht verfügbar.";
}
else{
txtScore.Text = File.ReadAllText(_highScoreFilePath);
}
}
private void BtnClose_Click(object sender, EventArgs e)
{
Hide();
}
private void FrmScoreList_Closing(object sender, FormClosingEventArgs e)
{
Hide();
e.Cancel = true;
}
}
}
|
2bdfa0d12724cbe560a194954c21f7bb07b82c7e
|
C#
|
triducnguyen/SeedSearch
|
/Seed Dispersal/Assets/Scripts/Data/StudentProfile.cs
| 2.734375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
namespace SeedSearch
{
public class StudentProfile : MonoBehaviour
{
public StudentData student;
public GameObject content;
public TMP_Text studentName;
public TMP_Text firstPrompt;
public TMP_Text secondPrompt;
public TMP_Text thirdPrompt;
public GameObject answer;
private bool initalized = false;
[SerializeField]private List<GameObject> durationObjects;
private void InitializeDuration()
{
if (student.Times != null)
{
if (student.Times.Count > 0)
{
int count = 1;
for (int i = 2; i < student.Times.Count; i++)
{
GameObject newAnswer = Instantiate(answer);
newAnswer.transform.SetParent(content.transform);
newAnswer.GetComponent<TMP_Text>().text = "Duration for question " + count + " : " + student.Times[i];
durationObjects.Add(newAnswer);
count++;
}
}
}
initalized = true;
}
public void NewProfile()
{
foreach(GameObject obj in durationObjects)
{
Destroy(obj);
}
durationObjects.Clear();
initalized = false;
}
// Update is called once per frame
void FixedUpdate()
{
studentName.text = student.FirstName + " " + student.LastName;
firstPrompt.text = "Student First Note: " + student.FirstPrompt;
secondPrompt.text = "Student Second Note: " + student.SecondPrompt;
thirdPrompt.text = "Student Third Note: " + student.ThirdPrompt;
//answer.text = "Attemps: " + student.Answers.Count;
if(!initalized)
InitializeDuration();
}
}
}
|
683709b20195f419a66a2697f795d726a0439e64
|
C#
|
kurisankaku/programming_prc
|
/csharp-practice/Test.cs
| 3.40625
| 3
|
using System;
class Base1 {
public Base1() {
Console.WriteLine("Base1()");
}
public Base1(int x) {
Console.WriteLine("Base1(int x)");
}
public Base1(int x, int y) {
Console.WriteLine("Base1(int x, int y)");
}
}
class Test1 : Base1 {
public Test1(int x) {
Console.WriteLine("Test1(int x)");
}
}
public static class ExtensionClass1 {
public static string AddHoge(this string str) {
return str + "Hoge1";
}
}
class Sample {
static void Main() {
Test1 test = new Test1(1);
Console.WriteLine("Fuga".AddHoge());
}
}
|
9071fca95292451da5cf8b03e7218957802ad33b
|
C#
|
JERRYZFC/edasample
|
/src/services/EdaSample.Services.Inventory/Controllers/ProductsController.cs
| 2.671875
| 3
|
using EdaSample.Common.DataAccess;
using EdaSample.Services.Inventory.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EdaSample.Services.Inventory.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly IDataAccessObject dataAccessObject;
private readonly ILogger logger;
public ProductsController(IDataAccessObject dataAccessObject, ILogger<ProductsController> logger)
{
this.dataAccessObject = dataAccessObject;
this.logger = logger;
}
[HttpGet]
public async Task<IEnumerable<Product>> GetProducts() => await this.dataAccessObject.GetAllAsync<Product>();
[HttpPost]
public async Task<IActionResult> CreateAsync(Product product)
{
if (string.IsNullOrEmpty(product.Name))
{
return BadRequest("Product name was not specified.");
}
var productsWithSameName = await this.dataAccessObject.FindBySpecificationAsync<Product>(p => string.Equals(p.Name, product.Name));
if (productsWithSameName?.Count() > 0)
{
return Conflict($"The product '{product.Name}' already exists.");
}
var id = Guid.NewGuid();
product.Id = id;
await this.dataAccessObject.AddAsync(product);
logger.LogInformation("产品信息注册成功。");
return Created(Url.Action("GetByKeyAsync", new { id }), id);
}
[HttpGet("{id}")]
public async Task<Product> GetByKeyAsync(Guid id)
{
return await this.dataAccessObject.GetByIdAsync<Product>(id);
}
}
}
|
a0838d0259569c410c29cd3d1d166a2fc42d5f99
|
C#
|
Jendisch/HumaneSociety
|
/Humane_Society/Humane_Society/HumaneSociety.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Humane_Society
{
class HumaneSociety
{
Employee employee;
Adopt adopt;
public void InitiateMenu()
{
UserInterface.WelcomeGreetingToMenu();
EnterEmployeeMenuOrAdopterMenu();
}
private void EnterEmployeeMenuOrAdopterMenu()
{
string choice = UserInterface.AskIfEmployeeOrPotentialAdopter().ToLower();
switch (choice)
{
case "employee":
GoToEmployeeMenu();
Console.Clear();
break;
case "adopter":
adopt = new Adopt();
adopt.DecideWhatToDoAsAnAdopter();
Console.Clear();
break;
case "exit":
break;
default:
UserInterface.DisplayNotAValidResponse();
EnterEmployeeMenuOrAdopterMenu();
break;
}
}
private void GoToEmployeeMenu()
{
string choice = UserInterface.TypeEmployeePassword().ToLower();
switch (choice)
{
case "answer":
employee = new Employee();
employee.DecideWhatToDoAsAnEmployee();
break;
case "back":
EnterEmployeeMenuOrAdopterMenu();
break;
default:
UserInterface.DisplayNotAValidResponse();
GoToEmployeeMenu();
break;
}
}
}
}
|
bc3e95f64ea49b8f877a07e81a46404f938f20a4
|
C#
|
DracoPQL/MoviitAssessment
|
/2 - Services/MinisServices/SandwichsService.svc.cs
| 2.609375
| 3
|
using Moviit.Domain.Business.Sandwichs.Contracts;
using Moviit.Domain.DTO.POCO;
using Moviit.Services.BaseServices.CORS;
using Moviit.Services.BaseServices.Faulting;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading.Tasks;
namespace Moviit.Services.MinisServices
{
/// <summary>
/// Implementation of the sandwich service.
/// </summary>
[ServiceBehavior(Namespace = "urn:Moviit.Services.MinisServices")]
[ErrorHandlerBehavior()]
[CORSBehavior()]
public class SandwichsService : ISandwichsService
{
#region Variables
private ISandwichManagement _sandwichManagement;
#endregion
#region Constructors
/// <summary>
/// Shared constructor. It will be called once on the service initialization.
/// </summary>
static SandwichsService()
{
}
/// <summary>
/// Default constructor
/// </summary>
public SandwichsService()
{
}
/// <summary>
/// Constructor with injected dependencies
/// </summary>
/// <param name="sandwichManagement">ISandwichManagement implementation to use</param>
public SandwichsService(ISandwichManagement sandwichManagement)
{
_sandwichManagement = sandwichManagement;
}
#endregion
#region Sandwich Management
/// <summary>
/// Creates a new sandwich
/// </summary>
/// <param name="request">Sandwich to create</param>
/// <returns>Id of the new created sandwich</returns>
public async Task<int> SandwichCreate(Sandwich request)
{
int result = await _sandwichManagement.SandwichCreate(request);
return result;
}
/// <summary>
/// Returns a sandwich given his id
/// </summary>
/// <param name="sandwichId">Id of the sandwich to return</param>
/// <returns>The specified sandwich</returns>
public async Task<Sandwich> SandwichRead(int sandwichId)
{
Sandwich result = await _sandwichManagement.SandwichRead(sandwichId);
return result;
}
/// <summary>
/// Updates a sandwich
/// </summary>
/// <param name="request">Sandwich to update</param>
/// <returns>Task for async operations</returns>
public async Task SandwichUpdate(Sandwich request)
{
await _sandwichManagement.SandwichUpdate(request);
}
/// <summary>
/// Deletes a sandwich
/// </summary>
/// <param name="sandwichId">Id of the sandwich to delete</param>
/// <returns>Task for async operations</returns>
public async Task SandwichDelete(int sandwichId)
{
await _sandwichManagement.SandwichDelete(sandwichId);
}
/// <summary>
/// Lists the sandwichs
/// </summary>
/// <returns>All the sandwichs</returns>
public async Task<IEnumerable<Sandwich>> SandwichList()
{
IEnumerable<Sandwich> result = await _sandwichManagement.SandwichList();
return result;
}
#endregion
#region Ingredient Management
/// <summary>
/// Creates a new ingredient
/// </summary>
/// <param name="request">Ingredient to create</param>
/// <returns>Id of the new created ingredient</returns>
public async Task<int> IngredientCreate(Ingredient request)
{
int result = await _sandwichManagement.IngredientCreate(request);
return result;
}
/// <summary>
/// Returns an ingredient given his id
/// </summary>
/// <param name="ingredientId">Id of the ingredient to return</param>
/// <returns>The specified ingredient</returns>
public async Task<Ingredient> IngredientRead(int ingredientId)
{
Ingredient result = await _sandwichManagement.IngredientRead(ingredientId);
return result;
}
/// <summary>
/// Updates an ingredient
/// </summary>
/// <param name="request">Ingredient to update</param>
/// <returns>Task for async operations</returns>
public async Task IngredientUpdate(Ingredient request)
{
await _sandwichManagement.IngredientUpdate(request);
}
/// <summary>
/// Deletes an ingredient
/// </summary>
/// <param name="ingredientId">Id of the ingredient to delete</param>
/// <returns>Task for async operations</returns>
public async Task IngredientDelete(int ingredientId)
{
await _sandwichManagement.IngredientDelete(ingredientId);
}
/// <summary>
/// Lists the ingredients
/// </summary>
/// <returns>All the ingredients</returns>
public async Task<IEnumerable<Ingredient>> IngredientList()
{
IEnumerable<Ingredient> result = await _sandwichManagement.IngredientList();
return result;
}
#endregion
#region Reports
/// <summary>
/// Get the sandwichs sold on the last seven days with their quantities.
/// </summary>
/// <returns>The report data</returns>
public async Task<IEnumerable<TheOnlyReportDTO>> TheOnlyReport()
{
IEnumerable<TheOnlyReportDTO> result = await _sandwichManagement.TheOnlyReport();
return result;
}
#endregion
}
}
|
8cb2f0d02729e0b7cbc1086af4058bd206f78fa4
|
C#
|
jarjaris/sharpclean
|
/metatypes.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sharpclean
{
//the .pgm file's basic data
struct data
{
public string filetype;
public int width, height, maxgreyval;
public int totalpixels;
};
//used for the menu's when the user selects to print certain data
enum info
{
ALL, FILETYPE, DIMENSIONS, TOTALPIXELS, MAXGREYVAL
};
//a basic pixel class
struct pixel
{
public bool selected; //used for selection
public bool found;
public byte value; //grey value
public int id; //ID [0->totalpixels]
};
//edge and filler use this for navigation around the pixel map
enum direction
{
none, up, down, left, right
};
//same deal, a little more abstract
class pathDirection
{
public direction dir = direction.none;
public int id = -1;
public pathDirection(direction d, int i) { dir = d; id = i; }
};
//each pixel has eight neighbors
class octan
{
public int tl = -1, t = -1, tr = -1,
l = -1, r = -1,
bl = -1, b = -1, br = -1;
public octan()
{
tl = -1; t = -1; tr = -1;
l = -1; r = -1;
bl = -1; b = -1; br = -1;
}
};
//same deal, different use
class neighbor
{
public readonly int tl = 0;
public readonly int t = 1;
public readonly int tr = 2;
public readonly int l = 3;
public readonly int r = 4;
public readonly int bl = 5;
public readonly int b = 6;
public readonly int br = 7;
};
//confidence class
public class conf
{
public double obj = 0.0, dust = 0.0,
o_size = 0.0, d_size = 0.0,
o_edge = 0.0, d_edge = 0.0,
o_val = 0.0, d_val = 0.0;
public bool isObj;
};
//for building the tree
class tup
{
public int s, e;
public tup(int st, int en) { s = st; e = en; }
public void change(int st, int en) { s = st; e = en; }
};
}
|
d895058516752d1832b3ce3dbf2bb00e9e89f80b
|
C#
|
hanlonJ/ConditionalStatements
|
/ConditionalStatements/Program.cs
| 4.03125
| 4
|
/*
Author: Jared Hanlon
Date: 1/21/2019
Comments: This C# Console application code demonstrates the use of
conditional statements after getting input from users
*/
using System;
namespace ConditionalStatements
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What grade do you expect to receive in ISM 4300?");
/* use the try catch block to validate user input
if the user provides bad input, the catch block
will display a message and recommend proper input
*/
try
{
string input = Console.ReadLine();
int grade = int.Parse(input);
// if / if else / else statement
if ((grade > 97) && (grade < 101))
{
Console.WriteLine("Your grade for ISM 4300 is an A+");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 91) && (grade < 98))
{
Console.WriteLine("Your grade for ISM 4300 is an A");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 89) && (grade < 92))
{
Console.WriteLine("Your grade for ISM 4300 is an A-");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 87) && (grade < 90))
{
Console.WriteLine("Your grade for ISM 4300 is a B+");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 81) && (grade < 88))
{
Console.WriteLine("Your grade for ISM 4300 is a B");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 79) && (grade < 82))
{
Console.WriteLine("Your grade for ISM 4300 is a B-");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 77) && (grade < 80))
{
Console.WriteLine("Your grade for ISM 4300 is a C+");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 71) && (grade < 78))
{
Console.WriteLine("Your grade for ISM 4300 is a C");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 69) && (grade < 72))
{
Console.WriteLine("Your grade for ISM 4300 is a C-");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 67) && (grade < 70))
{
Console.WriteLine("Your grade for ISM 4300 is a D+");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 61) && (grade < 68))
{
Console.WriteLine("Your grade for ISM 4300 is a D");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if ((grade > 59) && (grade < 62))
{
Console.WriteLine("Your grade for ISM 4300 is a D-");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
else if (grade < 60)
{
Console.WriteLine("Your grade for ISM 4300 is an F ");
Console.WriteLine("Press any key to exit the program ...");
Console.ReadKey(true);
}
} // end of try
catch
{
Console.WriteLine("Please use an integer data type between 0 and 100 for your expected grade next time");
Console.WriteLine("Press any key to exit the program and try again...");
Console.ReadKey(true);
} // end of catch
} // end of main
} // end of class
} // end of namespace
|
2e17b92d6a9caacc51bc6c40b267560424ac9563
|
C#
|
ThrashAbaddon/ADO.NET-Models
|
/ConsoleDB/Program.cs
| 3
| 3
|
using System;
using System.Data.SqlClient;
namespace ConsoleDB
{
class RazliciteKonekcije
{
static void Main(string[] args)
{
// Connect using .NET data provider for SQL Server and integrated security
string sqlConnectString1 =
@"Data Source=KUSARI-PC\SQLEXPRESS;Initial Catalog=TSQL2012;Integrated Security=True;";
using (SqlConnection connection = new SqlConnection(sqlConnectString1))
{
connection.Open();
// Return some information about the server.
Console.WriteLine("---.NET data provider for SQL Server " +
"with Windows Authentication mode---");
Console.WriteLine("ConnectionString = {0}\n", sqlConnectString1);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}
|
6b39db442fb0f9360a47604a6191f1d481f9b1b6
|
C#
|
klubenov/SoftUni
|
/ProgrammingFundamentals/E06ArraysExercisesG2/P01LargestCommonEnd/P01LargestCommonEnd.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace P01LargestCommonEnd
{
class P01LargestCommonEnd
{
static void Main(string[] args)
{
string[] firstSequence = Console.ReadLine().Split(' ').ToArray();
string[] secondSequence = Console.ReadLine().Split(' ').ToArray();
int cycleLength = Math.Min(firstSequence.Length, secondSequence.Length);
int sameStartCount = 0;
int sameEndCount = 0;
int arrayDifference = Math.Abs(firstSequence.Length - secondSequence.Length);
string[] longerSequence = new string[Math.Max(firstSequence.Length, secondSequence.Length)];
string[] shorterSequence = new string[Math.Min(firstSequence.Length, secondSequence.Length)];
if (firstSequence.Length >= secondSequence.Length)
{
Array.Copy(firstSequence, longerSequence, firstSequence.Length);
Array.Copy(secondSequence, shorterSequence, secondSequence.Length);
}
else
{
Array.Copy(firstSequence, shorterSequence, firstSequence.Length);
Array.Copy(secondSequence, longerSequence, secondSequence.Length);
}
for (int i = 0; i < cycleLength-1; i++)
{
if (firstSequence[i] == secondSequence[i])
sameStartCount++;
}
for (int i = cycleLength-1; i >= 0; i--)
{
if (longerSequence[i + arrayDifference] == shorterSequence[i])
sameEndCount++;
}
Console.WriteLine(Math.Max(sameEndCount,sameStartCount));
}
}
}
|
d06594720c93a23cf2a5e4406f86b1496ee20ddd
|
C#
|
andreclaroribeiro/PadroesProjeto
|
/PadroesProjeto.Source/Singleton/Dispositivo.cs
| 3.28125
| 3
|
using System;
namespace PadroesProjeto.Source.Singleton
{
public class Dispositivo
{
public string Marca { get; set; }
public string Modelo { get; set; }
private static Dispositivo instance = new Dispositivo();
public void Ligar()
{
Console.WriteLine("Equipamento ligado.");
}
public void Desligar()
{
Console.WriteLine("Equipamento desligado.");
}
public static Dispositivo GetInstance()
{
return instance ?? (instance = new Dispositivo());
}
public override string ToString()
{
return $"Marca e Modelo {Marca} - {Modelo}";
}
private Dispositivo() { }
}
}
|
84d86be5f24b200471f770735d6c93a8c32ee623
|
C#
|
captaindarkness/OOSE-Dungeon-Crawler-Project
|
/Assets/Scripts/EnemyAI.cs
| 2.796875
| 3
|
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
Transform target;
public Transform myTransform;
public float moveSpeed = 0.5f;
public float rotationSpeed = 3.0f;
bool Detect;
public float radiusAI = 10;
// Use this for initialization
void Start () {
//Set target to find a GameObject with the Tag Player which is set in unity
target = GameObject.FindWithTag ("Player").transform;
myTransform = transform;
}
// Update is called once per frame
void Update () {
//If Detect is true the Enemy object will rotate its front towards the Player and move towards the Player object by trying to match its position
if (Detect) {
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
//Keeps running the detectArea function
detectArea ();
}
void detectArea(){
//Distance is used to define a circle around the Enemy
float distance = Vector3.Distance (target.transform.position, transform.position);
//If the Player is within 5 units of the Enemy it will turn detect on, if above 5 units it will turn off
if (distance < radiusAI) {
Detect = true;
}
else if(distance > radiusAI) {
Detect = false;
}
}
}
|
c3b667f986f8c351c364215d80f9682c70632d09
|
C#
|
erinloy/ReactiveForms5
|
/ReactiveForms5/Form1.cs
| 2.796875
| 3
|
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Reactive.Linq;
namespace ReactiveForms5
{
public partial class Form1 : Form
{
Random rnd = new Random();
public Form1()
{
InitializeComponent();
Observable.FromEventPattern(e => this.Click += e, e => this.Click -= e).ObserveOn(this)
.Subscribe(e=>
{
this.BackColor = Color.FromArgb(255, rnd.Next(255), rnd.Next(255), rnd.Next(255));
});
}
}
}
|
d5c23cb5e6ef41b079603edc8a41077ff5e330bd
|
C#
|
ivanloy/UWPolyFlama
|
/Monopoly - Cliente - Pero bien/PantallasMonopoly/Models/Converters/DadoConverter.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace PantallasMonopoly.Models
{
class DadoConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
int dado = (int)value;
switch (dado)
{
case 1: return new Uri("ms-appx://ExamenDI/CustomAssets/Dado/uno.jpg");
case 2: return new Uri("ms-appx://ExamenDI/CustomAssets/Dado/dos.jpg");
case 3: return new Uri("ms-appx://ExamenDI/CustomAssets/Dado/tres.jpg");
case 4: return new Uri("ms-appx://ExamenDI/CustomAssets/Dado/cuatro.jpg");
case 5: return new Uri("ms-appx://ExamenDI/CustomAssets/Dado/cinco.jpg");
case 6: return new Uri("ms-appx://ExamenDI/CustomAssets/Dado/seis.jpg");
default: return new Uri("ms-appx://ExamenDI/CustomAssets/Dado/uno.jpg");
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException(); //Jaja para que quieres eso salu2
}
}
}
|
d3d812d06100ed786679ce8068e8271663c4d663
|
C#
|
gustavopalomino/BODYTECH
|
/BODYTECH/Domain.Test/EjercicioTest.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domain.Entities;
using Domain.Business;
using NUnit.Framework;
namespace Domain.Test
{
[TestFixture]
public class EjercicioTest
{
Ejercicio ejercicio;
[SetUp]
public void Initialize()
{
ejercicio = new Ejercicio();
}
//Persona
[Test]
public void Ejercicio_Nombre_Incorrecto()
{
Ejercicio entity = new Ejercicio()
{
Nombre = "Pp",
};
//Actuar
string resultado = entity.ValidarEjercicio();
//Afirmar
Assert.AreEqual("El nombre del ejercicio debe tener minimo 3 y maximo 40 caracteres", resultado);
}
[Test]
public void Ejercicio_Registro_Correcto()
{
Ejercicio entity = new Ejercicio()
{
Nombre = "Avanzadas",
};
//Actuar
string resultado = entity.ValidarEjercicio();
//Afirmar
Assert.AreEqual("Ejercicio registrado exitosamente!", resultado);
}
}
}
|
1f72f43b36cd3a5cb49c66277421dff589fde2f9
|
C#
|
Zarkana/redfin-c-sharp
|
/PageObjects/BasePage.cs
| 2.625
| 3
|
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace RedFin.PageObjects
{
class BasePage
{
public IWebDriver baseWebDriver { get; set; }
public IWebElement wElement { get; set; }
public BasePage(IWebDriver driver)
{
baseWebDriver = driver;
}
public IWebElement getWebElement(IWebDriver driver, By by, int timeout = 30)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(by));
return driver.FindElement(by);
}
public IList<IWebElement> getWebElements(IWebDriver driver, By by, int timeout = 30)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(by));
return driver.FindElements(by);
}
}
}
|
286dec45fdc7300c3022ea1a2a96f22be1b6eee7
|
C#
|
Lenny32/Microsoft.AspNetCore.Authentication.LinkedInAccount
|
/LinkedInAccountHelper.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNetCore.Authentication.LinkedInAccount
{
/// <summary>
/// Contains static methods that allow to extract user's information from a <see cref="JObject"/>
/// instance retrieved from LinkedIn after a successful authentication process.
/// </summary>
public static class LinkedInAccountHelper
{
/// <summary>
/// Gets the LinkedIn Account user ID.
/// </summary>
public static string GetId(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("id");
}
/// <summary>
/// Gets the user's name.
/// </summary>
public static string GetDisplayName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("formattedName");
}
/// <summary>
/// Gets the user's given name.
/// </summary>
public static string GetGivenName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("lastName");
}
/// <summary>
/// Gets the user's surname.
/// </summary>
public static string GetSurname(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("firstName");
}
/// <summary>
/// Gets the user's email address.
/// </summary>
public static string GetEmail(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("emailAddress");
}
}
}
|
ebf74bd6136e24953906a7e34f885ec697026bff
|
C#
|
barisgunduzer/MimariProje-SeriPortMonitoru
|
/mimari_seriport_haberlesme/Form1.cs
| 2.75
| 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 mimari_seriport_haberlesme
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void COMPortlariListele()
{
string[] myPort;
myPort = System.IO.Ports.SerialPort.GetPortNames();
comboBox1.Items.AddRange(myPort);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
COMPortlariListele();
}
delegate void GelenVerileriGuncelleCallback(string veri);
private void GelenVerileriGuncelle(string veri)
{
if (this.textBox1.InvokeRequired)
{
GelenVerileriGuncelleCallback d = new GelenVerileriGuncelleCallback(GelenVerileriGuncelle);
this.Invoke(d, new object[] { veri });
}
else
{
this.textBox1.AppendText(veri);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex < 0)
{
MessageBox.Show("COM port bulunamadi");
return;
}
if (comboBox2.SelectedIndex < 0)
{
MessageBox.Show("Bağlantı hızı seçiniz");
return;
}
try
{
if (serialPort1.IsOpen == false)
{
serialPort1.PortName = comboBox1.SelectedItem.ToString();
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
button1.Text = "BAĞLANTI KES";
timer1.Enabled = true;
}
else
{
timer1.Enabled = false;
serialPort1.Close();
button1.Text = "BAĞLANTI AÇ";
}
}
catch
{
MessageBox.Show("Bağlantı açılamadı!");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.BytesToRead > 0)
{
GelenVerileriGuncelle(serialPort1.ReadExisting());
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
|
a8601fd3d3d9382d4b134c61af790e2b51734db3
|
C#
|
dfitraa/primbon-csharp
|
/Program.cs
| 2.796875
| 3
|
using System;
namespace Primbon
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Neptu Hari Lahir\t\tNeptu Nama Hari Pasaran Jawa");
Console.WriteLine("=======================================================");
Console.WriteLine("Minggu \t= 5\t\t\tWage\t= 4");
Console.WriteLine("Senin \t= 4\t\t\tKliwon\t= 8");
Console.WriteLine("Selasa \t= 3\t\t\tLegi\t= 5");
Console.WriteLine("Rabu \t= 7\t\t\tPahing\t= 9");
Console.WriteLine("Kamis \t= 8\t\t\tPon\t= 7");
Console.WriteLine("Jumat \t= 6");
Console.WriteLine("Sabtu \t= 9");
Console.Write("\n\nMasukkan Jumlah Neptu Pria: ");
int input1 = Convert.ToInt16(Console.ReadLine());
Console.Write("Masukkan Jumlah Neptu Wanita: ");
int input2 = Convert.ToInt16(Console.ReadLine());
int result = input1 + input2;
int[] pegat = {1,9,17,25,33};
int[] ratu = {2,10,18,26,34};
int[] jodoh = {3,11,19,27,35};
int[] topo = {4,12,20,28,36};
int[] tinari = {5,13,21,29};
int[] padu = {6,14,22,30};
int[] sujanan = {7,15,23,31};
int[] pesthi = {8,16,24,32};
Console.Write("\n\n");
for (int i = 0; i < pegat.Length; i++)
if (result == pegat[i])
{
Console.Write("Hasil Weton PEGAT");
}
for (int i = 0; i < ratu.Length; i++)
if (result == ratu[i])
{
Console.Write("Hasil Weton RATU");
}
for (int i = 0; i < jodoh.Length; i++)
if (result == jodoh[i])
{
Console.Write("Hasil Weton JODOH");
}
for (int i = 0; i < topo.Length; i++)
if (result == topo[i])
{
Console.Write("Hasil Weton TOPO");
}
for (int i = 0; i < tinari.Length; i++)
if (result == tinari[i])
{
Console.Write("Hasil Weton TINARI");
}
for (int i = 0; i < padu.Length; i++)
if (result == padu[i])
{
Console.Write("Hasil Weton PADU");
}
for (int i = 0; i < sujanan.Length; i++)
if (result == sujanan[i])
{
Console.Write("Hasil Weton SUJANAN");
}
for (int i = 0; i < pesthi.Length; i++)
if (result == pesthi[i])
{
Console.Write("Hasil Weton PESTHI");
}
}
}
}
|
e7bde4f8943bbda59e0093cb80261bd68799d3fa
|
C#
|
johnddiaz/flight-scheduling
|
/UnitTestProject1/CustomerBaseTest.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cs270_uwp
{
class CustomerBaseTest
{
String s = "asdf";
String e = "asdf";
string s1 = "asdf";
String e1 = "asdf";
public void Tester() {
if (s.Equals(e)) {
System.Diagnostics.Debug.WriteLine("equal");
}
}
}
}
|
124faf5893b4d69e419b3c47e93e30bbcfef05b6
|
C#
|
tokkenno/aoe3-launcher
|
/AOEIII_Launcher/Cultures/Culture.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AOEIII_Launcher.Culture
{
public abstract class Culture
{
protected String _STRING_NOT_FOUND_MESSAGE = String.Empty;
protected Dictionary<String, String> langValues = new Dictionary<String, String>();
protected G11N.Countries country = G11N.Countries.UNDEFINED;
protected G11N.Languages language = G11N.Languages.UNDEFINED;
public String getTranslateString(String id)
{
if (this.langValues.ContainsKey(id))
{
return this.langValues[id];
}
else
{
return this._STRING_NOT_FOUND_MESSAGE;
}
}
public G11N.Languages Language
{
get { return this.language; }
}
public G11N.Countries Country
{
get { return this.country; }
}
}
}
|
200e3a2eafd52b2588ce5e8b80e2a71a8e17ed67
|
C#
|
SuperMeip/SpiritWorld-Unity
|
/Assets/Scripts/Coordinate.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A tile position in a level
/// </summary>
public struct Coordinate {
/// <summary>
/// 0, 0 coordinate constant
/// </summary>
public static Coordinate Zero = (0, 0);
/// <summary>
/// east west
/// </summary>
public short x;
/// <summary>
/// north south
/// </summary>
public short z;
/// <summary>
/// up down in 2D
/// </summary>
public short y => z;
/// <summary>
/// Get this as a unity vector 2
/// </summary>
public Vector3 Vec3 {
get => new Vector3(x, 0, z);
}
/// <summary>
/// Get this as a unity vector 2
/// </summary>
public Vector2 Vec2 {
get => new Vector2(x, z);
}
/// <summary>
/// get this as a cube coord
/// </summary>
public Vector3 Cube {
get => new Vector3(x, -x - z, z);
}
/// <summary>
/// If this coordinate is valid and was properly initialized
/// </summary>
public bool isInitialized {
get;
private set;
}
/// <summary>
/// Create a 3d coordinate
/// </summary>
/// <param name="x"></param>
/// <param name="z"></param>
public Coordinate(short x, short z) {
this.x = x;
this.z = z;
isInitialized = true;
}
/// <summary>
/// preform the acton on all coordinates between this one and the end coordinate
/// </summary>
/// <param name="end">The final point to run on, exclusive</param>
/// <param name="action">the function to run on each point</param>
/// <param name="step">the value by which the coordinate values are incrimented</param>
public void until(Coordinate end, Action<Coordinate> action, short step = 1) {
Coordinate current = (x, z);
for (current.x = x; current.x < end.x; current.x += step) {
for (current.z = z; current.z < end.z; current.z += step) {
action(current);
}
}
}
/// <summary>
/// preform the acton on all coordinates between this one and the end coordinate
/// </summary>
/// <param name="end">The final point to run on, exclusive</param>
/// <param name="action">the function to run on each point</param>
/// <param name="step">the value by which the coordinate values are incrimented</param>
public void until(Coordinate end, Func<Coordinate, bool> action, short step = 1) {
Coordinate current = (x, z);
for (current.x = x; current.x < end.x; current.x += step) {
for (current.z = z; current.z < end.z; current.z += step) {
if (!action(current)) return;
}
}
}
/// <summary>
/// Checks if this coordinate is within a set, dictated by boundaries. (inclusive, and exclusive)
/// </summary>
public bool isWithin((Coordinate minInclusive, Coordinate maxExclusive) bounds) {
return isWithin(bounds.minInclusive, bounds.maxExclusive);
}
/// <summary>
/// Checks if this coordinate is within a set, dictated by boundaries. (inclusive, and exclusive)
/// </summary>
/// <param name="start">The starting location to check if the point is within, inclusive</param>
/// <param name="bounds">The outer boundary to check for point inclusion. Exclusive</param>
/// <returns></returns>
public bool isWithin(Coordinate start, Coordinate bounds) {
return isWithin(bounds) && isAtLeastOrBeyond(start);
}
/// <summary>
/// Checks if this coordinate is within a set, dictated by boundaries. (inclusive, and exclusive)
/// </summary>
/// <param name="bounds">The inner [0](inclusive) and outer [1](exclusive) boundary to check for point inclusion</param>
/// <returns></returns>
public bool isWithin(Coordinate[] bounds) {
if (bounds != null && bounds.Length == 2) {
return isWithin(bounds[1]) && isAtLeastOrBeyond(bounds[0]);
} else throw new ArgumentOutOfRangeException("Coordinate.isWithin must take an array of size 2.");
}
/// <summary>
/// Checks if this coordinate is greater than (or equal to) a lower bounds coordinate (Inclusive)
/// </summary>
public bool isAtLeastOrBeyond(Coordinate bounds) {
return x >= bounds.x
&& z >= bounds.z;
}
/// <summary>
/// Checks if this coordinate is within a bounds coodinate (exclusive)
/// </summary>
public bool isWithin(Coordinate bounds) {
return x < bounds.x
&& z < bounds.z;
}
/// implicit opperators
///===================================
/// <summary>
/// Create a coordinate from a touple.
/// </summary>
/// <param name="coordinates">(X, Z)</param>
public static implicit operator Coordinate((int, int) coordinates) {
return new Coordinate((short)coordinates.Item1, (short)coordinates.Item2);
}
/// <summary>
/// Create a coordinate from a touple.
/// </summary>
/// <param name="coordinates">(X, Z)</param>
public static implicit operator Coordinate(Vector3 coordinate) {
return new Coordinate((short)coordinate.x, (short)coordinate.z);
}
/// <summary>
/// Create a vector 3 from a coordinate
/// </summary>
/// <param name="coordinates">(X, Z)</param>
public static implicit operator Vector3(Coordinate coordinate) {
return new Vector3(coordinate.x, 0, coordinate.z);
}
/// <summary>
/// Create a coordinate from a touple.
/// </summary>
/// <param name="coordinates">(X, Z)</param>
public static implicit operator Coordinate((short, short) coordinates) {
return new Coordinate(coordinates.Item1, coordinates.Item2);
}
///OVERRIDES
///===================================
public static Coordinate operator +(Coordinate a, Coordinate b) {
return (
a.x + b.x,
a.z + b.z
);
}
public static Coordinate operator -(Coordinate a, Coordinate b) {
return (
a.x - b.x,
a.z - b.z
);
}
public static Coordinate operator -(Coordinate a, int b) {
return (
a.x - b,
a.z - b
);
}
public static Coordinate operator +(Coordinate a, int b) {
return (
a.x + b,
a.z + b
);
}
public static Vector2 operator +(Coordinate a, Vector2 b) {
return new Vector2(
a.x + b.x,
a.z + b.y
);
}
public static Coordinate operator *(Coordinate a, Coordinate b) {
return (
a.x * b.x,
a.z * b.z
);
}
public static Vector3 operator *(Vector3 a, Coordinate b) {
return new Vector3(
a.x * b.x,
a.y,
a.z * b.z
);
}
public static Coordinate operator *(Coordinate a, int b) {
return (
a.x * b,
a.z * b
);
}
public static Vector3 operator %(Coordinate a, Vector3 b) {
return new Vector3(
a.x % b.x,
b.y,
a.z % b.z
);
}
public static Vector3 operator +(Coordinate a, Vector3 b) {
return new Vector3(
a.x + b.x,
b.y,
a.z + b.z
);
}
public static Vector3 operator *(Coordinate a, Vector3 b) {
return new Vector3(
(float)a.x * b.x,
b.y,
(float)a.z * b.z
);
}
public static Vector3 operator +(Vector3 a, Coordinate b) {
return new Vector3(
a.x + b.x,
a.y,
a.z + b.z
);
}
public static bool operator >(Coordinate a, Coordinate b) {
return a.x > b.x || a.y > b.y;
}
public static bool operator <(Coordinate a, Coordinate b) {
return a.x < b.x && a.y < b.y;
}
/// <summary>
/// Is limited to (short.MAX, short.MAX)
/// </summary>
/// <returns></returns>
public override int GetHashCode() {
return (z << 16) | x;
}
/// <summary>
/// Coord to string
/// </summary>
/// <returns></returns>
public override string ToString() {
return "{" + x + ", " + z + "}";
}
/// <summary>
/// deconstruct
/// </summary>
/// <param name="x"></param>
/// <param name="z"></param>
internal void Deconstruct(out int x, out int z) {
x = this.x;
z = this.z;
}
}
#region Directions
/// <summary>
/// Direction constants
/// </summary>
public static class Directions {
/// <summary>
/// A valid direction
/// </summary>
public class Direction : IEquatable<Direction> {
/// <summary>
/// The id of the direction
/// </summary>
public int Value {
get;
private set;
}
/// <summary>
/// The name of this direction
/// </summary>
public string Name {
get;
private set;
}
/// <summary>
/// The x y z offset of this direction from the origin
/// </summary>
public Coordinate Offset {
get => Offsets[Value];
}
/// <summary>
/// Get the oposite of this direction
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public Direction Reverse {
get {
if (Equals(North)) {
return South;
}
if (Equals(South)) {
return North;
}
if (Equals(East)) {
return West;
}
return East;
}
}
internal Direction(int value, string name) {
Value = value;
Name = name;
}
/// <summary>
/// To string
/// </summary>
/// <returns></returns>
public override string ToString() {
return Name;
}
public override int GetHashCode() {
return Value;
}
/// <summary>
/// Equatable
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Direction other) {
return other.Value == Value;
}
/// <summary>
/// Override equals
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj) {
return (obj != null)
&& !GetType().Equals(obj.GetType())
&& ((Direction)obj).Value == Value;
}
}
/// <summary>
/// Z+
/// </summary>
public static Direction North = new Direction(0, "North");
/// <summary>
/// X+
/// </summary>
public static Direction East = new Direction(1, "East");
/// <summary>
/// Z-
/// </summary>
public static Direction South = new Direction(2, "South");
/// <summary>
/// X-
/// </summary>
public static Direction West = new Direction(3, "West");
/// <summary>
/// All the directions in order
/// </summary>
public static Direction[] All = new Direction[4] {
North,
East,
South,
West
};
/// <summary>
/// The cardinal directions. Non Y related
/// </summary>
public static Direction[] Cardinal = new Direction[4] {
North,
East,
South,
West
};
/// <summary>
/// The coordinate directional offsets
/// </summary>
public static Coordinate[] Offsets = new Coordinate[4] {
(0,1),
(1,0),
(0,-1),
(-1, 0)
};
}
#endregion
#region Float Utilities
public static class RangeUtilities {
/// <summary>
/// Scale a float value to a new set of maxes and mins.
/// </summary>
/// <param name="value"></param>
/// <param name="newMax"></param>
/// <param name="newMin"></param>
/// <param name="oldMax"></param>
/// <param name="oldMin"></param>
/// <returns></returns>
public static float scale(this float value, float newMax, float newMin, float oldMax = 1.0f, float oldMin = -1.0f) {
float scaled = newMin + (value - oldMin) / (oldMax - oldMin) * (newMax - newMin);
return scaled;
}
/// <summary>
/// fast clamp a float to between 0 and 1
/// </summary>
/// <param name="value"></param>
/// <param name="minValue"></param>
/// <param name="maxValue"></param>
/// <returns></returns>
public static float clampToFloat(float value, int minValue, int maxValue) {
return (
(value - minValue)
/ (maxValue - minValue)
);
}
/// <summary>
/// fast clamp float to short
/// </summary>
/// <param name="value"></param>
/// <param name="minFloat"></param>
/// <param name="maxFloat"></param>
/// <returns></returns>
public static short clampToShort(float value, float minFloat = 0.0f, float maxFloat = 1.0f) {
return (short)((short.MaxValue - short.MinValue)
* ((value - minFloat) / (maxFloat - minFloat))
+ short.MinValue);
}
/// <summary>
/// Clamp a value between two numbers
/// </summary>
/// <param name="value"></param>
/// <param name="startingMin"></param>
/// <param name="startingMax"></param>
/// <param name="targetMin"></param>
/// <param name="targetMax"></param>
/// <returns></returns>
public static double clamp(double value, double startingMin, double startingMax, double targetMin, double targetMax) {
return (targetMax - targetMin)
* ((value - startingMin) / (startingMax - startingMin))
+ targetMin;
}
/// <summary>
/// Clamp the values between these numbers in a non scaling way.
/// </summary>
/// <param name="number"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static float box(this float number, float min, float max) {
if (number < min)
return min;
else if (number > max)
return max;
else
return number;
}
/// <summary>
/// Box a float between 0 and 1
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static float box01(this float number) {
return box(number, 0, 1);
}
}
#endregion
#region Array Utilities
public static class ArrayUtilities {
public static void Populate<T>(this T[,] arr, T value) {
for (int i = 0; i < arr.Length; i++) {
for (int j = 0; j < arr.Length; j++) {
arr[i, j] = value;
}
}
}
public static void Deconstruct<TKey, TValue>(
this KeyValuePair<TKey, TValue> kvp,
out TKey key,
out TValue value) {
key = kvp.Key;
value = kvp.Value;
}
public static void Populate<T>(this T[] arr, T value) {
for (int i = 0; i < arr.Length; i++) {
arr[i] = value;
}
}
}
#endregion
#region Sort Utilities
public static class SortExtentions {
private static System.Random rng = new System.Random();
public static IList<T> Shuffle<T>(this IList<T> list) {
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
}
#endregion
#region Bit Utilities
public static class BitIntExtentions {
public static int TurnBitOn(this int value, int bitToTurnOn) {
return (value | bitToTurnOn);
}
public static int TurnBitOff(this int value, int bitToTurnOff) {
return (value & ~bitToTurnOff);
}
public static int FlipBit(this int value, int bitToFlip) {
return (value ^ bitToFlip);
}
}
#endregion
|
ecddf4bb99190763634d538c69ed80172c56acaf
|
C#
|
jasonbashov/Telerik-Academy
|
/C# Part 2/01.Arrays/18.RemoveMinElements/Program.cs
| 3.484375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//* Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the
//remaining array is sorted in increasing order. Print the remaining sorted array. Example:
// {6, 1, 4, 3, 0, 3, 6, 4, 5} -> {1, 3, 3, 4, 5}
//resheniqto e bazirano na predhodnite 2 zadachi, no s leki promeni v implementaciqta
class Program
{
static bool IsSorted(List<int> list)
{
bool isSorted = true;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > list[i + 1])
{
isSorted = false;
}
}
return isSorted;
}
static void Main()
{
//int[] array = { 6, 1, 4, 3, 0, 3, 6, 4, 5,1,6,99,2,7,8 };
Console.WriteLine("Enter the array's length N:");
int n = int.Parse(Console.ReadLine());
int[] array = new int[n];
Console.WriteLine("Fill the array:");
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter index {0} value:", i);
array[i] = int.Parse(Console.ReadLine());
}
List<int> tempList = new List<int>();
List<int> neededList = new List<int>();
//string subset = "";
bool isSubsetSorted = false;
int numberOfElements = array.Length;
int maxSubsets = (int)Math.Pow(2, numberOfElements) - 1; //opredelqme maximalniq broi na podmnojestvata
for (int i = 1; i <= maxSubsets; i++)
{
tempList.Clear();
//long checkingSum = 0;
//int countElements = 0;
for (int j = 0; j < numberOfElements; j++)
{
int mask = 1 << j;
int nAndMask = i & mask;
int bit = nAndMask >> j;
if (bit == 1)//ako 1viq bit na 4isloto e edinica, zna4i moje da u4astva v dadenoto podmnojestvo
{
//checkingSum = checkingSum + array[j];
//subset = subset + " " + array[j];
//countElements++;
tempList.Add(array[j]);
}
}
isSubsetSorted = IsSorted(tempList);
if (isSubsetSorted && (neededList.Count < tempList.Count))//ako temp list-a e sortiran i temp lista e po-dylyg ot neededList -> temp list e nashiq list
{
neededList.Clear();
foreach (int number in tempList)
{
neededList.Add(number);
}
//Console.WriteLine("Yes ->" + subset);
//isSubsetSorted = true;
}
}
foreach (int number in neededList)
{
Console.Write(number + " ");
}
Console.WriteLine();
}
}
|
c0ef8ef890752764476e3ace87b44af8bbb4fd9e
|
C#
|
J101R/Leaplog-accounting
|
/LeapLog/IncomeStatement.xaml.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Office.Interop.Excel;
namespace LeapLog
{
/// <summary>
/// Interaction logic for IncomeStatement.xaml
/// </summary>
public partial class IncomeStatement : UserControl
{
public static string destinationText = Journal.passingText;
public IncomeStatement()
{
InitializeComponent();
DateTime now = DateTime.Now;
string format = "MMMM dd, yyyy";
Database.is_date.from_date = now;
Database.is_date.to_date = now;
From.Text = now.ToString(format);
To.Text = now.ToString(format);
}
// method that refreshes the income-statement grid so that it is updated with current entries
public void Refresh()
{
// Clear all grids and textbox
entryGridE.Items.Clear();
entryGridR.Items.Clear();
entryGridTE.Items.Clear();
entryGridTR.Items.Clear();
textBox1.Clear();
double Total_revenue = 0;
double Total_expenses = 0;
//add t-accounts to respective grids
DateTime from = Database.is_date.from_date;
DateTime to = Database.is_date.to_date;
for (int i = 0; i < Database.TEntries.Count; i++)
{
Entry_tacc _tacc = Database.TEntries[i];
DateTime td = _tacc.Date;
if (td.Day >= from.Day && td.Month >= from.Month && td.Year >= from.Year &&
td.Day <= to.Day && td.Month <= to.Month && td.Year <= to.Year)
{
string type = _tacc.Type;
string name = _tacc.Account;
Entry_tacc t = _tacc.Clone();
t.Balance = Math.Abs(_tacc.Balance);
//and if account is a revenue account
if (type == "Revenue")
{
entryGridR.Items.Add(t);
Total_revenue += t.Balance;
}
//or if account is an expense account
if (type == "Expense")
{
entryGridE.Items.Add(t);
Total_expenses += t.Balance;
}
}
}
// Add the totals
entryGridTR.Items.Add(new Total() { total = Total_revenue });
entryGridTE.Items.Add(new Total() { total = Total_expenses });
double ni = (Total_revenue - Total_expenses);
textBox1.Text = ni.ToString();
Database.net_income = ni;
//get the three variables, add them into a new income-data class object
Database.IncomeData.total_revenue = Total_revenue;
Database.IncomeData.total_expenses = Total_expenses;
Database.IncomeData.net_income = ni;
}
private void from_SelectionChanged(object sender, RoutedEventArgs e)
{
DateTime.TryParse(From.Text, out Database.is_date.from_date);
Refresh();
}
private void to_SelectionChanged(object sender, RoutedEventArgs e)
{
DateTime.TryParse(To.Text, out Database.is_date.to_date);
Refresh();
}
//method for when help feature button is clicked
private void incomeHelpButton_Click(object sender, RoutedEventArgs e)
{
if (incomeHelpWindow.Visibility == Visibility.Collapsed)
{
incomeHelpWindow.Visibility = Visibility.Visible;
}
else
{
incomeHelpWindow.Visibility = Visibility.Collapsed;
}
}
}
}
|
aa8c5e083a505bcb5c7a2f2f539b2e33cb4964af
|
C#
|
MongolChat/MChatSDK
|
/MChatSDK/MChatWorkerConfiguration.cs
| 2.65625
| 3
|
using System;
namespace MChatSDK
{
public class MChatWorkerConfigurationException : Exception {
public MChatWorkerConfigurationException()
: base("MChat Worker not configured, Please configure worker")
{
}
}
public class MChatWorkerConfiguration
{
public enum MChatWorkerType
{
MChatWorkerKey,
MChatWorkerBasic
}
internal String apiKey;
internal MChatWorkerType workerType;
internal String authorization;
internal int bnsTimeout;
Boolean configured = false;
private static MChatWorkerConfiguration instance = null;
public static MChatWorkerConfiguration Instance
{
get
{
if (instance == null)
{
instance = new MChatWorkerConfiguration();
}
return instance;
}
}
public void Configure(String apiKey, MChatWorkerType workerType, String authorization)
{
this.apiKey = apiKey;
this.workerType = workerType;
this.authorization = authorization;
this.configured = true;
}
public void setBNSTimeout(int timeout)
{
this.bnsTimeout = timeout;
}
public String showInfo
{
get
{
String info = "";
info += "ApiKey - " + this.apiKey + "\n";
info += "WorkerType - " + this.workerType + "\n";
info += "WorkerCredentials - " + this.authorization + "\n";
return info;
}
}
internal void CheckIsConfigured() {
if (!this.configured)
{
throw new MChatWorkerConfigurationException();
}
}
}
}
|
0caa3680c09a97814966c20789bd1d2e671350cd
|
C#
|
njtrentacoste/WordWrap
|
/WordWrap/WordWrapper.cs
| 3.59375
| 4
|
using System.Text;
using System.Text.RegularExpressions;
namespace WordWrap
{
public class WordWrapper
{
public string Wrap(string text, int length)
{
var wrapped = new StringBuilder();
var regex = new Regex("\b");
var words = regex.Replace(text, " ").Split(' ');
var lineLength = 0;
foreach (var word in words)
{
var wordLength = word.Length;
if (wordLength <= length && (wordLength + lineLength) <= length)
{
wrapped.Append(word + " ");
lineLength += (wordLength + 1);
}
else if (wordLength <= length)
{
wrapped.AppendLine();
wrapped.Append(word + " ");
lineLength = (wordLength + 1);
}
else
{
wrapped.AppendLine();
var tempWord = word;
do
{
var firstPart = tempWord.Length >= length ? tempWord.Substring(0, length - 1) : tempWord;
if (firstPart.Length < (length - 1))
{
wrapped.Append(firstPart + " ");
lineLength += firstPart.Length;
}
else
{
wrapped.Append(firstPart + "-");
wrapped.AppendLine();
lineLength = 0;
}
tempWord = tempWord.Replace(firstPart, "");
wordLength -= firstPart.Length;
}
while (wordLength > 0);
}
}
return wrapped.ToString();
}
}
}
|
10ec51ffb964b9e74b2f0bcc7b1d7f59b6aa136e
|
C#
|
Minoxsys/CPMS
|
/PAS/PAS/Controllers/ClinicianController.cs
| 2.609375
| 3
|
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using CPMS.Domain;
using PAS.Models;
namespace PAS.Controllers
{
public class ClinicianController : Controller
{
[HttpGet]
public ActionResult Add()
{
var addClinicianViewModel = new AddClinicianViewModel
{
Hospitals = GetHospitals(),
Specialties = GetSpecialties(),
AllClinicians = GetAllClinicians()
};
return View(addClinicianViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(AddClinicianInputModel clinicianInputModel)
{
if (ModelState.IsValid)
{
using (var unitOfwork = new UnitOfWork())
{
var hospital = GetHospitalById(clinicianInputModel.SelectedHospital, unitOfwork);
var specialty = GetSpecialtyByCode(clinicianInputModel.SelectedSpecialty, unitOfwork);
var clinician = new Clinician
{
Name = clinicianInputModel.Name,
Hospital = hospital,
Specialty = specialty
};
unitOfwork.Clinicians.Add(clinician);
unitOfwork.SaveChanges();
}
return RedirectToAction("Add");
}
clinicianInputModel.Hospitals = GetHospitals();
clinicianInputModel.Specialties = GetSpecialties();
clinicianInputModel.AllClinicians = GetAllClinicians();
return View(clinicianInputModel);
}
[HttpGet]
public JsonResult GetSpecialtiesBy(int? hospitalId = null)
{
var specialties = new List<LiteSpecialtyViewModel> { new LiteSpecialtyViewModel {Code = "0", Name = "Select Specialty"} };
specialties.AddRange(GetSpecialties(hospitalId));
return new JsonResult {Data = specialties, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
private IEnumerable<LiteHospitalViewModel> GetHospitals()
{
using (var unitOfWork = new UnitOfWork())
{
return unitOfWork.Hospitals.ToArray().Select(hospital => new LiteHospitalViewModel
{
Id = hospital.Id,
Name = hospital.Name
});
}
}
private IEnumerable<LiteSpecialtyViewModel> GetSpecialties(int? hospitalId = null)
{
using (var unitOfWork = new UnitOfWork())
{
return hospitalId == null
? unitOfWork.Specialties.ToArray().Select(GetLiteSpecialty)
: GetHospitalById((int) hospitalId, unitOfWork).Specialties.ToArray().Select(GetLiteSpecialty);
}
}
private LiteSpecialtyViewModel GetLiteSpecialty(Specialty specialty)
{
return new LiteSpecialtyViewModel
{
Code = specialty.Code,
Name = specialty.Name
};
}
private IEnumerable<ClinicianViewModel> GetAllClinicians()
{
using (var unitOfWork = new UnitOfWork())
{
return unitOfWork.Clinicians
.Include(p => p.Hospital)
.Include(p => p.Specialty)
.ToArray().Select(clinician => new ClinicianViewModel
{
Hospital = clinician.Hospital.Name,
Specialty = clinician.Specialty.Name,
Name = clinician.Name
});
}
}
private Specialty GetSpecialtyByCode(string code, UnitOfWork unitOfwork)
{
return unitOfwork.Specialties.FirstOrDefault(specialty => specialty.Code == code);
}
private Hospital GetHospitalById(int hospitalId, UnitOfWork unitOfwork)
{
return unitOfwork.Hospitals
.Include(p => p.Specialties)
.FirstOrDefault(hospital => hospital.Id == hospitalId);
}
}
}
|
a21e6d1e9d47bb98905998c3d280cd3bf8f5d1a7
|
C#
|
prabhaarunram/NewRepos
|
/Controllers/OrderController.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Shopping.Models;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Shopping.Controllers
{
[Route("api/Order")]
[ApiController]
public class OrderController : Controller
{
// GET: api/<OrderController>
[HttpGet("Orders")]
public IEnumerable<Order> Get()
{
CoreDbContext objCore = new CoreDbContext();
return objCore.Order.AsEnumerable();
}
// GET api/<OrderController>/5
[HttpGet("{id}")]
public Order Get(int id)
{
CoreDbContext objCore = new CoreDbContext();
return objCore.Order.Where(x => x.OrderId == id).FirstOrDefault();
}
// POST api/<OrderController>
[HttpPost]
public void Post([FromBody] Order objOrder)
{
CoreDbContext objCore = new CoreDbContext();
objCore.Order.Attach(objOrder);
objCore.Entry(objOrder).State = (Microsoft.EntityFrameworkCore.EntityState)DataRowState.Added;
objCore.SaveChanges();
objCore.Dispose();
}
// PUT api/<OrderController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] Order objOrder)
{
CoreDbContext objCore = new CoreDbContext();
Order objUpdateOrder = new Order();
objUpdateOrder = objCore.Order.Where(x => x.OrderId == id).FirstOrDefault();
objUpdateOrder.Quantity = objOrder.Quantity;
objCore.Order.Update(objUpdateOrder);
objCore.SaveChanges();
objCore.Dispose();
}
// DELETE api/<OrderController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
CoreDbContext objCore = new CoreDbContext();
Order objOrder = new Order();
objOrder = objCore.Order.Where(x => x.OrderId == id).FirstOrDefault();
objCore.Order.Remove(objOrder);
objCore.SaveChanges();
objCore.Dispose();
}
}
}
|
e7e237ac371258fe076481304375eb07a1fd82fd
|
C#
|
mosa/MOSA-Project
|
/Source/Mosa.Compiler.Framework/Analysis/LiveVariableAnalysis/LiveRanges.cs
| 2.671875
| 3
|
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using System;
using System.Collections.Generic;
using System.Text;
namespace Mosa.Compiler.Framework.Analysis.LiveVariableAnalysis;
public sealed class LiveRanges
{
public List<Range> Ranges { get; } = new List<Range>(1);
public int Count => Ranges.Count;
public Range LastRange => Ranges[Count - 1];
public Range FirstRange
{
get => Ranges[0];
set => Ranges[0] = value;
}
public void Add(int start, int end)
{
Add(new Range(start, end));
}
public void Add(Range range)
{
if (Count == 0)
{
Ranges.Add(range);
return;
}
if (range.End < FirstRange.Start)
{
Ranges.Insert(0, range);
return;
}
if (range.Start > LastRange.End)
{
Ranges.Add(range);
return;
}
for (var i = 0; i < Count; i++)
{
var liveRange = Ranges[i];
if (liveRange.Start == range.Start && liveRange.End == range.End)
return;
if (liveRange.IsAdjacent(range) || liveRange.Intersects(range))
{
liveRange = new Range(Math.Min(range.Start, liveRange.Start), Math.Max(range.End, liveRange.End));
Ranges[i] = liveRange;
for (var z = i + 1; z < Count; z++)
{
var nextLiveRange = Ranges[z];
if (liveRange.IsAdjacent(nextLiveRange) || liveRange.Intersects(nextLiveRange))
{
var newliveRange = new Range(Math.Min(liveRange.Start, nextLiveRange.Start), Math.Max(liveRange.End, nextLiveRange.End));
Ranges[i] = liveRange;
Ranges.RemoveAt(z);
continue;
}
return;
}
return;
}
}
}
public override string ToString()
{
if (Ranges.Count == 0)
return string.Empty;
var sb = new StringBuilder();
foreach (var range in Ranges)
{
sb.Append("[").Append(range.Start).Append(",").Append(range.End).Append("],");
}
if (sb[sb.Length - 1] == ',')
sb.Length--;
return sb.ToString();
}
}
|
087fe0f36ae22420a82543ea91d966fabec773bc
|
C#
|
sy545633799/NetworkCore
|
/photonServer/ExitGamesLibs/Net.Sockets/BatchMessage.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExitGames.Net.Sockets
{
/// <summary>
/// batch message.
/// </summary>
internal sealed class BatchMessage
{
/// <summary>
/// The header size.
/// </summary>
private int HeaderSize = 8;
/// <summary>
/// The messages.
/// </summary>
private readonly List<ArraySegment<byte>> message = new List<ArraySegment<byte>>();
/// <summary>
/// The size.
/// </summary>
private int size;
/// <summary>
/// Initializes a new instance of the <see cref="T:ExitGames.Net.Sockets.BatchMessage"/> class.
/// </summary>
public BatchMessage()
{ }
/// <summary>
/// Reads a <see cref="T:ExitGames.Net.Sockets.BatchMessage"/> from a byte array.
/// </summary>
/// <param name="data">The data.</param>
/// <returns>A <see cref="T:ExitGames.Net.Sockets.BatchMessage"/>.</returns>
/// <exception cref="T:System.ArgumentException">
/// Length of byte array is less than header size.
/// </exception>
public static BatchMessage FromBinary(byte[] data)
{
if (data.Length < 8)
{
throw new ArgumentException("Invalid data length.", "data");
}
int num = BitConverter.ToInt32(data, 0);
int num2 = BitConverter.ToInt32(data, 4);
if (num != data.Length)
{
throw new ArgumentException(string.Format("Data length {0} does not match message size {1}", data.Length, num), "data");
}
BatchMessage HeaderSize = new BatchMessage
{
HeaderSize = num
};
int num3 = 0;
int offset = 8;
while (num3 < num2)
{
int count = BitConverter.ToInt32(data, offset);
offset += 4;
ArraySegment<byte> item = new ArraySegment<byte>(data, offset, count);
HeaderSize.message.Add(item);
offset += count;
num3++;
}
return HeaderSize;
}
/// <summary>
/// Adds a message.
/// </summary>
/// <param name="data">The data.</param>
public void AddMessage(ArraySegment<byte> data)
{
this.HeaderSize += 4;
this.HeaderSize += data.Count;
this.message.Add(data);
}
/// <summary>
/// Clears all messages.
/// </summary>
public void Clear()
{
this.HeaderSize = 8;
this.message.Clear();
}
/// <summary>
/// Converts messages to a list of <see cref="T:System.ArraySegment`1"/> of byte.
/// </summary>
/// <returns> A list of <see cref="T:System.ArraySegment`1"/> of byte.</returns>
public List<ArraySegment<byte>> ToBinary()
{
List<ArraySegment<byte>> list = new List<ArraySegment<byte>>();
byte[] array = BitConverter.GetBytes(this.HeaderSize);
list.Add(new ArraySegment<byte>(array));
array = BitConverter.GetBytes(this.MessageCount);
list.Add(new ArraySegment<byte>(array));
foreach (ArraySegment<byte> segment in this.message)
{
array = BitConverter.GetBytes(segment.Count);
list.Add(new ArraySegment<byte>(array));
list.Add(segment);
}
return list;
}
/// <summary>
/// Gets MessageCount.
/// </summary>
public int MessageCount
{
get
{
return message.Count;
}
}
/// <summary>
/// Gets Size.
/// </summary>
public int Size
{
get
{
return size;
}
}
/// <summary>
/// The array segement indexer.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>An <see cref="T:System.ArraySegment`1"/>.</returns>
public ArraySegment<byte> this[int index]
{
get
{
return message[index];
}
}
}
}
|
d98980f7a3acc130f43a92137b1e7f6a50d1d07b
|
C#
|
Normo/evoAlg4CSharp
|
/src/main/main/Evolution.cs
| 2.828125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Gtk;
using System.Text;
using System.ComponentModel;
namespace main
{
public class Evolution
{
public delegate List<Genome> RecombineMethod (Genome genomeA, Genome genomeB);
public delegate void FitnessMethod (Genome genome);
public delegate void MutateMethod (List<Genome> genomes);
public delegate void OnProgressEvent(double percentage);
public event OnProgressEvent OnProgress;
public RecombineMethod Recombine;
public FitnessMethod CalcFitness;
public MutateMethod Mutate;
public int countGene; // Anzahl der Gene
public int maxGenerations; // Maximale Anzahl zu erzeugender Generationen
public int countIndividuals; // Anzahl an Individuen einer Population
public int countChilds; // Anzahl zu erzeugender Kinder
public double recombinationProbability; // Rekombinationswahrscheinlichkeit
public bool InvertOnMutate; // Mutation: true = invertieren, false = tauschen
public double minAllelValue; // Minimaler Wert der Allele
public double maxAllelValue; // Maximaler Wert der Allele
public Helper.Enums.SelPropType SelPropType; // Selektionswahrscheinlichkeit: Fitness- oder Rangbasiert
public Helper.Enums.SelType SelType; // Selektionsverfahren: Roulette, Single-, MultiTournament
public Helper.Enums.Encryption Encryption; // Genomkodierung
public int TournamentMemberCount; // Anzahl Teilnehmer der Turnierselektion
public double bestFitness; // Bester Fitnesswert
public double averageFitness; // Durchschnittliche Fitness der aktuellen Generation
public int bestFitnessGeneration; // Generationzahl, in der bestFitness aufgetreten ist
public int stableGenerations; // Anzahl an Generationen, in denen sich die beste Fitness nicht geaendert hat
public List<double> bestSolutions; // Liste mit den besten Fitnesswerten aus mehreren Durchläufen
public List<int> bestSolutionsGeneration; // Liste mit den Generationzahlen, in denen die beste Fitness das erste Mal aufgetreten ist
public List<Genome> bestList;
private StringBuilder sb;
/// <summary>
/// Konstruktor
/// </summary>
/// <param name='problem'>Anzuwendendes Problem</param>
public Evolution(Problem problem)
{
countGene = problem.countGene;
maxGenerations = problem.maxGenerations;
countIndividuals = problem.countIndividuals;
countChilds = problem.countChilds;
recombinationProbability = problem.recombinationProbability;
InvertOnMutate = problem.InvertOnMutate;
minAllelValue = problem.minAllelValue;
maxAllelValue = problem.maxAllelValue;
SelPropType = problem.SelPropType;
SelType = problem.SelType;
Encryption = problem.Encryption;
TournamentMemberCount = problem.TournamentMemberCount;
sb = problem.Output;
bestFitness = double.MaxValue;
averageFitness = double.MaxValue;
bestFitnessGeneration = 0;
bestSolutions = new List<double>();
bestSolutionsGeneration = new List<int>();
bestList = new List<Genome>(maxGenerations-1);
CalcFitness = problem.CalcFitnessDefault;
switch (Encryption)
{
case Helper.Enums.Encryption.None :
{
Recombine = problem.RecombineDefault;
Mutate = problem.MutateDefault;
break;
}
case Helper.Enums.Encryption.Binary :
{
Recombine = problem.RecombineBinary;
Mutate = problem.MutateBinary;
break;
}
case Helper.Enums.Encryption.Real :
{
Recombine = problem.RecombineReal;
Mutate = problem.MutateReal;
break;
}
}
}
/// <summary>
/// Der eigentliche evolutionäre Algorithmus - entspricht doc/EvoAlgTSP.pdf.
/// </summary>
public void Compute()
{
int countGeneration = 0;
int c; // child-counter
bestFitness = double.MaxValue;
averageFitness = double.MaxValue;
bestFitnessGeneration = 0;
Genome bestGenome;
sb.AppendLine("Compute:");
// 1. Initialisiere Population P(0) mit zufälligen Genomen
Population p = new Population(countIndividuals, countGene, minAllelValue, maxAllelValue, Encryption);
// 2. Berechne die Fitnesswerte von P(0)
foreach (Genome genome in p.curGeneration) {
CalcFitness(genome);
}
// Ermittel beste Lösung von P(0)
bestGenome = Helper.Fitness.GetBestGenome(p.curGeneration);
while(countGeneration < maxGenerations && stableGenerations < 1000)
{
//Event für Fortschritt feuern
if (OnProgress != null)
{
double percentage = ((double)(countGeneration + 1) / (double)maxGenerations);
OnProgress(percentage);
}
//Sagt dem Betriebssystem das es seine Evenets abarbeiten soll.
//Das verhindert (u.A.) das einfrieren der GUI
while (Application.EventsPending ())
Application.RunIteration ();
// Fitness des besten Genoms, ist hoeher als bisherige beste Fitness
if (bestGenome.Fitness < bestFitness)
{
bestFitness = bestGenome.Fitness;
bestFitnessGeneration = countGeneration + 1;
bestList.Add(bestGenome.Copy());
}
else
{
// Zähle stableGenerations hoch, wenn sich bester Fitnesswert nicht geändert hat
stableGenerations++;
}
//alte Generation merken
p.SaveAsOldGen();
switch(SelPropType)
{
case Helper.Enums.SelPropType.Fitness :
Helper.Selection.CalcSelPropByFitness(p.oldGeneration);
break;
case Helper.Enums.SelPropType.Ranking :
Helper.Selection.CalcSelPropByRanking(p.oldGeneration);
break;
}
// 3. Erzeuge Kinder und füge sie P' hinzu
c = 0;
Random rnd = new Random(Guid.NewGuid().GetHashCode());
while (c < countChilds)
{
if (rnd.NextDouble() <= recombinationProbability)
{
// I. Rekombination zweier Individuen A und B aus Population P(0)
//todo: Genom aus der Populationsklasse liefern lassen damit der Genom-Typ immer passt
Genome mama = new GenomeReal();
Genome papa = new GenomeReal();
bool equals = true;
while (equals)
{
switch (SelType)
{
case main.Helper.Enums.SelType.Roulette :
mama = Selection.Roulette(p.oldGeneration);
papa = Selection.Roulette(p.oldGeneration);
break;
case main.Helper.Enums.SelType.SingleTournament :
mama = Selection.SingleTournament(p.oldGeneration, TournamentMemberCount);
papa = Selection.SingleTournament(p.oldGeneration, TournamentMemberCount);
break;
case main.Helper.Enums.SelType.MultiTournament :
mama = Selection.MultiTournament(p.oldGeneration, TournamentMemberCount);
papa = Selection.MultiTournament(p.oldGeneration, TournamentMemberCount);
break;
}
//Mama und Papa dürfen nicht die selben sein, sonst evtl. Duplikat
if (!mama.IsEqual(papa))
equals = false;
}
//Rekombinieren und Fitness berechnen
List<Genome> childs = Recombine(mama,papa);
// II. Mutiere Kind c
if (Encryption != Helper.Enums.Encryption.Binary)
Mutate(childs);
foreach (Genome genome in childs)
CalcFitness(genome);
// III. Füge Kinder C zu P' hinzu
//todo: Binäre Rekombination liefert 2 Kinder zurück
if (!p.ContainsGenome(childs[0]) || ((childs.Count > 1)? !p.ContainsGenome(childs[1]) : false))
// if (!p.ContainsGenome(childs[0]) )
{
p.curGeneration.AddRange(childs);
if (Encryption == Helper.Enums.Encryption.Binary)
c += 2;
else
c++;
}
}
}
// 5. Erzeuge Kind-Population -> die besten Individuen aus Kind- + Eltern-Generation
if (Encryption != Helper.Enums.Encryption.Binary)
Selection.Plus(p, countIndividuals);
else
{
int perc = (int)Math.Round((double)p.curGeneration.Count * 0.3);
// perc = countIndividuals - perc;
List<Genome> lst = new List<Genome>();
Random rnd1 = new Random(Guid.NewGuid().GetHashCode());
for (perc = countIndividuals - perc; perc <= p.oldGeneration.Count; perc++)
{
lst.Clear();
lst.Add(p.oldGeneration[rnd1.Next(0,p.oldGeneration.Count)]);
Mutate(lst);
p.curGeneration[perc-1] = lst[0];
}
foreach (Genome genome in p.curGeneration)
CalcFitness(genome);
p.curGeneration.Sort((a,b) => a.Fitness.CompareTo(b.Fitness));
}
bestGenome = p.curGeneration[0];
countGeneration++;
}
//Ausgabe der letzten Generation
// sb.AppendLine("Letzte Generation");
// foreach (Genome genome in p.curGeneration)
// sb.AppendLine(genome.AsString());
// Ausgabe der besten Lösungen
sb.AppendLine("\r\nBestenliste");
int counter = 1;
for (int i = bestList.Count-1; i >= 0; i--)
{
sb.AppendLine(counter + ".\t" + bestList[i].AsString());
counter++;
}
// Speichere den besten Fitnesswert und die Generation in der er aufgetreten ist zur späteren Auswertung (Evolutioniere x 10)
bestSolutions.Add(bestFitness);
bestSolutionsGeneration.Add(bestFitnessGeneration);
}
/// <summary>
/// Ausgabe der durchschnittlichen besten Fitness + Generation aus mehreren Durchläufen
/// </summary>
public void GetStats()
{
double bestAverageFitness = 0;
double bestAverageGenerations = 0;
for (int i = 0; i < bestSolutions.Count; i++)
{
bestAverageFitness += bestSolutions[i];
bestAverageGenerations += bestSolutionsGeneration[i];
}
bestAverageFitness = bestAverageFitness / bestSolutions.Count;
bestAverageGenerations = bestAverageGenerations / bestSolutionsGeneration.Count;
Console.WriteLine(String.Format("Beste Lösungen je Durchgang: {0}\r\nAufgetreten in Generation: {1}", Helper.ListToString(bestSolutions), Helper.ListToString(bestSolutionsGeneration)));
Console.WriteLine(String.Format("Durchschnittliche Fitness: {0}\r\nDurchschnittliche Generation: {1}", bestAverageFitness, bestAverageGenerations));
}
}
}
|
3b4593815b186c6ea7bf312d958a83e8ff17a962
|
C#
|
kobrynsky/iPetCare.API
|
/iPetCare/Persistence/Seeds/SeedExaminations.cs
| 2.8125
| 3
|
using Domain.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Persistence.Seeds
{
public class SeedExaminations
{
public static async Task Seed(DataContext context)
{
if (!context.Examinations.Any())
{
var pets = await context.Pets.ToListAsync();
var examinationTypes = await context.ExaminationTypes.ToListAsync();
var species = pets.Select(x => x.Race.Species).Distinct();
var examinations = new List<Examination>();
var random = new Random();
foreach (var speciesUnit in species)
{
var speciesExaminationTypes = examinationTypes.Where(x => x.SpeciesId == speciesUnit.Id).ToList();
foreach (var pet in pets.Where(x => x.Race.SpeciesId == speciesUnit.Id))
{
var randomizedId = random.Next(0, speciesExaminationTypes.Count);
var examinationType = speciesExaminationTypes[randomizedId];
var examinationValues = new List<ExaminationParameterValue>();
foreach (var parameter in examinationType.ExaminationParameters)
{
examinationValues.Add(new ExaminationParameterValue()
{
ExaminationParameter = parameter,
Value = random.Next((int)parameter.LowerLimit, (int)parameter.UpperLimit),
});
}
examinations.Add(new Examination()
{
Pet = pet,
Date = DateTime.Now,
ExaminationParameterValues = examinationValues,
ExaminationType = examinationType,
Content = "Badanie było w porząsiu",
});
}
}
context.AddRange(examinations);
await context.SaveChangesAsync();
}
}
}
}
|
0561a0d3833bba59461708c68f993f838401fd62
|
C#
|
tanchiba/DoAn_LTUDQL2
|
/DAO/CUSTOMER_GROUPDAO.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DTO;
using DAO.AppData;
namespace DAO
{
public class CUSTOMER_GROUPDAO
{
public static List<CUSTOMER_GROUPDTO> list()
{
List<CUSTOMER_GROUPDTO> dsEmpl = new List<CUSTOMER_GROUPDTO>();
using (QuanLyBanHangEntities db = new QuanLyBanHangEntities())
{
var query = from em in db.CUSTOMER_GROUP
select em;
foreach (var row in query)
{
CUSTOMER_GROUPDTO cg = new CUSTOMER_GROUPDTO();
cg.Active = (Boolean)row.Active;
cg.Description = row.Description;
cg.Customer_Group_ID = row.Customer_Group_ID;
cg.Customer_Group_Name = row.Customer_Group_Name;
//empl.Active = (row.Active);
dsEmpl.Add(cg);
}
return dsEmpl;
}
}
public static void deleteID(string id)
{
using (QuanLyBanHangEntities db = new QuanLyBanHangEntities())
{
var cg = db.CUSTOMER_GROUP.Single(a => a.Customer_Group_ID == id);
db.CUSTOMER_GROUP.Remove(cg);
db.SaveChanges();
}
}
public static void add(string groupid, string groupname, string description, bool active)
{
using (QuanLyBanHangEntities db = new QuanLyBanHangEntities())
{
CUSTOMER_GROUP cg = new CUSTOMER_GROUP();
cg.Active = active;
cg.Customer_Group_ID = groupid;
cg.Customer_Group_Name = groupname;
cg.Description = description;
db.CUSTOMER_GROUP.Add(cg);
db.SaveChanges();
}
}
public static void EditByID(string ID,string groupname,string desciption,bool active)
{
using (QuanLyBanHangEntities db = new QuanLyBanHangEntities())
{
var a = db.CUSTOMER_GROUP.Single(b => b.Customer_Group_ID == ID);
a.Active = active;
a.Customer_Group_ID = ID;
a.Customer_Group_Name = groupname;
a.Description = desciption;
db.SaveChanges();
}
}
public static CUSTOMER_GROUPDTO objectToDTO(object a)
{
return a as CUSTOMER_GROUPDTO;
}
}
}
|
8d7791eeee422f85f16a4b2c762b1b6551ff5960
|
C#
|
RomaBogdanov/BogdanovUtilities
|
/BogdanovCodeAnalyzer/ViewModel/SearchTextInFilesViewModel.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using BogdanovUtilitisLib.MVVMUtilsWrapper;
using System.Windows.Input;
namespace BogdanovCodeAnalyzer.ViewModel
{
class SearchTextInFilesViewModel : NotifyPropertyChanged
{
private string searchingText;
private string searchingPath;
private ObservableCollection<string> searchedPaths;
private ObservableCollection<string> allExtents;
private ObservableCollection<string> filteredExtents;
/// <summary>
/// Искомый текст, который должен содержаться в файле.
/// </summary>
public string SearchingText
{
get => searchingText;
set
{
searchingText = value;
OnPropertyChanged();
}
}
/// <summary>
/// Путь к списку файлов, в которых ищется текст.
/// </summary>
public string SearchingPath
{
get => searchingPath;
set
{
searchingPath = value;
OnPropertyChanged();
}
}
/// <summary>
/// Список файлов, в которых содержится текст.
/// </summary>
public ObservableCollection<string> SearchedPaths
{
get => searchedPaths;
set
{
searchedPaths = value;
OnPropertyChanged();
}
}
public ObservableCollection<string> AllExtents
{
get => allExtents;
set
{
allExtents = value;
OnPropertyChanged();
}
}
public ObservableCollection<string> FilteredExtents
{
get => filteredExtents;
set
{
filteredExtents = value;
OnPropertyChanged();
}
}
public bool SearchIsEnabled
{
get => searchIsEnabled;
set
{
searchIsEnabled = value;
OnPropertyChanged();
}
}
/// <summary>
/// Запускает поиск файлов, в которых содержится данная строка.
/// </summary>
public ICommand SearchFilesWithTextCommand { get; set; }
public ICommand AllExtentionsCommand { get; set; }
List<string> exts;
private bool searchIsEnabled = true;
public SearchTextInFilesViewModel()
{
SearchFilesWithTextCommand = new RelayCommand(obj => SearchFilesWithText());
AllExtentionsCommand = new RelayCommand(obj => AllExtentions());
SearchingPath = @"D:\Repository";
exts = new List<string>()
{
"config",
"htm",
"csproj",
"cs",
"resx",
"rtf",
"txt",
"settings",
"xml",
"html",
"doc"
};
}
/// <summary>
/// Находит все файлы, содержащие текст.
/// </summary>
private void SearchFilesWithText()
{
SearchIsEnabled = false;
Task.Run(() =>
{
string[] allFiles = System.IO.Directory.GetFiles(SearchingPath,
"*.*", System.IO.SearchOption.AllDirectories);
//.Where(
// p => exts.Contains(p.Split('.').Last())).ToArray();
SearchedPaths = new ObservableCollection<string>();
foreach (var item in allFiles)
{
try
{
string str = System.IO.File.ReadAllText(item);
if (System.Text.RegularExpressions.Regex.IsMatch(str, SearchingText))
{
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
SearchedPaths.Add(item);
});
}
}
catch (Exception err)
{
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
SearchedPaths.Add(err.Message);
});
}
}
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
SearchIsEnabled = true;
});
});
}
/// <summary>
/// Находит все расширения файлов
/// </summary>
private void AllExtentions()
{
string[] allFiles = System.IO.Directory.GetFiles(SearchingPath,
"*", System.IO.SearchOption.AllDirectories);
AllExtents = new ObservableCollection<string>(allFiles.Select(
p => p.Split('.').Last()).Distinct());
}
}
}
|
2011c70775782d732a331ba33044b8ba22db8f29
|
C#
|
overdd/BSUIR-C-
|
/Laba 1_5/Laba 1_5/Task 5/StartEndReader.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Laba_1_5.Task_5
{
class StartEndReader
{
int[] startEnd = new int[2];
public int[] readKeys()
{
Console.WriteLine("Введите значение start в виде int: ");
startEnd[0] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите значение end в виде int: ");
startEnd[1] = Convert.ToInt32(Console.ReadLine());
return startEnd;
}
}
}
|
c3055be28dabe55f5adb3d103515c324293521d9
|
C#
|
manakamic/Gesture
|
/Assets/Gesture/GestureManagerIF.cs
| 2.90625
| 3
|
using System.Collections.Generic;
namespace Gesture {
/// <summary>
/// partialで分割したGestureManagerクラス.
/// 各Gestureの操作インターフェイスを実装.
/// </summary>
public partial class GestureManager {
public void Clear() {
if (_listTap != null) {
_listTap.Clear();
}
if (_listLongTap != null) {
_listLongTap.Clear();
}
if (_listSwipe != null) {
_listSwipe.Clear();
}
if (_listFlick != null) {
_listFlick.Clear();
}
if (_listPinch != null) {
_listPinch.Clear();
}
}
public bool AddTap(GestureTap tap) {
if (tap == null) {
return false;
}
if (_listTap == null) {
_listTap = new List<GestureTap>();
}
_listTap.Add(tap);
return true;
}
public bool RemoveTap(GestureTap tap) {
if (tap == null || _listTap == null) {
return false;
}
return _listTap.Remove(tap);
}
public bool AddLongTap(GestureLongTap tap) {
if (tap == null) {
return false;
}
if (_listLongTap == null) {
_listLongTap = new List<GestureLongTap>();
}
_listLongTap.Add(tap);
return true;
}
public bool RemoveLongTap(GestureLongTap tap) {
if (tap == null || _listLongTap == null) {
return false;
}
return _listLongTap.Remove(tap);
}
public bool AddSwipe(GestureSwipe swipe) {
if (swipe == null) {
return false;
}
if (_listSwipe == null) {
_listSwipe = new List<GestureSwipe>();
}
_listSwipe.Add(swipe);
return true;
}
public bool RemoveSwipe(GestureSwipe swipe) {
if (swipe == null || _listSwipe == null) {
return false;
}
return _listSwipe.Remove(swipe);
}
public bool AddFlick(GestureFlick flick) {
if (flick == null) {
return false;
}
if (_listFlick == null) {
_listFlick = new List<GestureFlick>();
}
_listFlick.Add(flick);
return true;
}
public bool RemoveFlick(GestureFlick flick) {
if (flick == null || _listFlick == null) {
return false;
}
return _listFlick.Remove(flick);
}
public bool AddPinch(GesturePinch pinch) {
if (pinch == null) {
return false;
}
if (_listPinch == null) {
_listPinch = new List<GesturePinch>();
}
_listPinch.Add(pinch);
return true;
}
public bool RemovePinch(GesturePinch pinch) {
if (pinch == null || _listPinch == null) {
return false;
}
return _listPinch.Remove(pinch);
}
public bool AddPhase(GesturePhase phase) {
if (phase == null) {
return false;
}
if (_listPhase == null) {
_listPhase = new List<GesturePhase>();
}
_listPhase.Add(phase);
return true;
}
public bool RemovePhase(GesturePhase phase) {
if (phase == null || _listPhase == null) {
return false;
}
return _listPhase.Remove(phase);
}
}
}
|
7ff2c206d0e1c7a439bcca9dd49e7355c1fbe13d
|
C#
|
Glazed/Dredmor-XML-Validator
|
/DredmorXsdWordExtractor/Program.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace DredmorXsdWordExtractor
{
class Program
{
static void Main( string[] args )
{
if ( args.Length == 0 )
{
Console.WriteLine( "No file specified." );
}
else if ( !File.Exists( args[ 0 ] ) )
{
Console.WriteLine( "File not found." );
}
else
{
var path = args[ 0 ];
string xsd = File.ReadAllText( path );
//Make sure each element is on its own line.
xsd = Regex.Replace( xsd, @">\s*<", ">" + Environment.NewLine + "<" );
Regex wordRegex = new Regex( @"<xs:(?:(?:element )|(?:attribute )|(?:enumeration )).*(?:(?:name)|(?:value))=""(\w+)""" );
MatchCollection matches = wordRegex.Matches( xsd );
List<string> words = new List<string>();
foreach ( Match match in matches )
{
words.Add( match.Groups[ 1 ].Value );
}
var distinctWords = words.Distinct().OrderBy( p => p ).ToList();
#if DEBUG
WriteWordsFile( distinctWords, @".\words.txt" );
#else
WriteWordsFile( distinctWords, @"..\..\..\DredmorUtilities\words.txt" );
#endif
}
Console.Beep();
}
private static void WriteWordsFile( List<string> words, string path )
{
File.WriteAllLines( path, words );
}
}
}
|
cd2c4aec95df218eea332b77871fd056698d0f75
|
C#
|
nupurkulkarni411/Build-Server
|
/MockClient/Client.cs
| 2.734375
| 3
|
/////////////////////////////////////////////////////////////////////
// Clent.cs - This package provides functionality for creating //
// messages to test various functionalities of system //
// ver 1.0 //
// Language: C#, Visual Studio 2017 //
// Platform: Lenovo ideapad 500, Windows 10 //
// Application: Build Server //
// //
// Name : Nupur Kulkarni //
// CSE681: Software Modeling and Analysis, Fall 2017 //
/////////////////////////////////////////////////////////////////////
/*
* Module Operations:
* -------------------
The client Demo class which is used to kick off required functionalities of system.
* Public Interface:
* =================
* void send(Message msg) : This unables client to communicate with other packages
* by sending message to Common request handler.
* public string CreateBuildRequest() : Used to create Build request XML.
* public Message CreateBuildMessage() : Used to command repository to process build request by sending message
* public Message CreateViewLogMessage(): Used to create request for viewing logs
*
* Build Process:
* --------------
* Required Files: Client.cs BuilderMessages.cs IFederation.cs Messages.cs Serialization.cs IRequest.cs
* Build Command: csc Client.cs BuilderMessages.cs IFederation.cs Messages.cs Serialization.cs IRequest.cs
*
* Maintenance History:
- Ver 1.0 Oct 2017
* --------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BuildServerMessages;
using Utilities;
using Messages;
using FederationInterface;
using RequestHandlerInterface;
namespace MockClient
{
public class Client:IFederation
{
public Client(IRequest req):base(req)
{
Console.Write("\n Constructor of mock client is called.");
}
//This unables client to communicate with other packages
public void send(Message msg)
{
req.send(msg);
}
//Build Request for C#
public string CreateBuildRequest()
{
TestElement te1 = new TestElement();
te1.testName = "test1";
te1.addDriver("TestDriver2.cs");
te1.addTestConfiguration("C#");
te1.addCode("ITest.cs");
te1.addCode("CodeToTest2.cs");
TestElement te2 = new TestElement();
te2.testName = "test2";
te2.addDriver("TestDriver1.cs");
te2.addTestConfiguration("C#");
te2.addCode("ITest.cs");
te2.addCode("CodeToTest1.cs");
TestRequest tr = new TestRequest();
tr.author = "Jim Fawcett";
tr.timeStamp = DateTime.Now;
tr.tests.Add(te1);
tr.tests.Add(te2);
string trXml = tr.ToXml();
Console.Write("\n Test Request: \n{0}\n",trXml);
return trXml;
}
//Build Request for java
public string CreateJavaBuildRequest()
{
TestElement te1 = new TestElement();
te1.testName = "test1";
te1.addDriver("HelloWorld.java");
te1.addTestConfiguration("Java");
TestRequest tr = new TestRequest();
tr.author = "Jim Fawcett";
tr.timeStamp = DateTime.Now;
tr.tests.Add(te1);
string trXml = tr.ToXml();
Console.Write("\n Test Request: \n{0}\n", trXml);
return trXml;
}
//Command to process test request.
public Message CreateBuildMessage(string language)
{
string tr ="";
if (language == "c#")
tr = CreateBuildRequest();
if (language == "java")
tr = CreateJavaBuildRequest();
Message rqstMsg = new Message();
rqstMsg.author = "Fawcett";
rqstMsg.to = "Repository";
rqstMsg.from = "Client";
rqstMsg.type = "TestRequest";
rqstMsg.time = DateTime.Now;
rqstMsg.body = tr;
rqstMsg.show();
return rqstMsg;
}
//Request for viewing logs
public Message CreateViewLogMessage()
{
Message req = new Message();
req.author = "Fawcett";
req.to = "Repository";
req.from = "Client";
req.type = "ViewLog";
req.time = DateTime.Now;
req.body = "BuildLogJim Fawcett";
req.show();
return req;
}
//Request for different user to view logs
public Message CreateViewLogMessageLogNotFound()
{
Message req = new Message();
req.author = "Fawcett";
req.to = "Repository";
req.from = "Client";
req.type = "ViewLog";
req.time = DateTime.Now;
req.body = "TestLogNupur Kulkarni";
req.show();
return req;
}
}
class MockClientTest
{
#if (TEST_MockCLIENT)
static void Main(string[] args)
{
Console.Write("\n demo of client");
Console.Write("\n ==============================");
HelpRepoMock repo = new HelpRepoMock();
repo.getFiles("*.*");
Client dc = new Client(rh);
Message msg = dc.CreateBuildMessage();
dc.send(msg);
Console.Write("\n\n");
}
#endif
}
}
|
502886b897e543e8eb495768b9d749c027da43bb
|
C#
|
Fraham/CAS-CSharpStarter
|
/4-StartingWithClasses/Transaction.cs
| 3.609375
| 4
|
using System;
namespace _4_StartingWithClasses
{
public class Transaction
{
/*
All of these properties only have `get`
Once the property has been set it can not be updated
*/
public decimal Amount { get; }
public DateTime Date { get; }
public string Notes { get; }
/*
This is the constructor for this class
All of the values for the properties need to be set during the construction
*/
public Transaction(decimal amount, DateTime date, string note)
{
this.Amount = amount;
this.Date = date;
this.Notes = note;
}
}
}
|
9f1839204562e32f87ea39b6cbc5c343abe49b63
|
C#
|
hillinworks/tabml
|
/Source/TabML.Parser/AST/VoiceNode.cs
| 2.609375
| 3
|
using System.Collections.Generic;
using TabML.Core.Document;
using TabML.Parser.Parsing;
using System.Linq;
using TabML.Core.Logging;
using TabML.Core.MusicTheory;
using System;
namespace TabML.Parser.AST
{
class VoiceNode : Node
{
public List<BeatNode> Beats { get; }
public PreciseDuration ExpectedDuration { get; set; }
public override IEnumerable<Node> Children => this.Beats;
public VoiceNode()
{
this.Beats = new List<BeatNode>();
}
public PreciseDuration GetDuration() => this.Beats.Sum(b => b.NoteValue.ToNoteValue().GetDuration());
public bool ToDocumentElement(TablatureContext context, ILogger logger, VoicePart voicePart, out RhythmSegmentVoice voice)
{
voice = new RhythmSegmentVoice(voicePart)
{
Range = this.Range
};
context.CurrentVoice = voice;
foreach (var beat in this.Beats)
{
Beat documentBeat;
if (!beat.ToDocumentElement(context, logger, voice, out documentBeat))
return false;
voice.Beats.Add(documentBeat);
}
// try to fill voice with rests if insufficient notes fed
var duration = this.GetDuration();
if (duration < this.ExpectedDuration)
{
BaseNoteValue[] factors;
if (!BaseNoteValues.TryFactorize(this.ExpectedDuration - duration, out factors))
{
logger.Report(LogLevel.Error, this.Range,
Messages.Error_InconsistentVoiceDurationCannotBeFilledWithRest);
return false;
}
logger.Report(LogLevel.Suggestion, this.Range, Messages.Suggestion_InconsistentVoiceDuration);
foreach (var factor in factors)
{
var beat = new Beat()
{
NoteValue = new NoteValue(factor),
IsRest = true,
Notes = new BeatNote[0]
};
context.CurrentVoice.IsTerminatedWithRest = true;
voice.Beats.Add(beat);
}
}
return true;
}
public bool ValueEquals(RhythmSegmentVoice other)
{
if (other == null)
return false;
return other.Beats.Count == this.Beats.Count
&& this.Beats.Where((b, i) => !b.ValueEquals(other.Beats[i])).Any();
}
}
}
|
07f24cd8efa538839e3c3461435fb2f410f3b3a5
|
C#
|
DragonsLord/MathDetecting
|
/MathDetecting/Algorithms/Segmentation/FormatImage.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace MathDetecting.Algorithms.Segmentation
{
public static class FormatImage
{
public static void ChangeImage(Bitmap bm)
{
Color color;
List<Point> sym = new List<Point>();
for (int i = 0; i < bm.Width; i++)
{
for (int j = 0; j < bm.Height; j++)
{
if (Segmentation.GetBrightness(bm.GetPixel(i, j)) > 150 && !sym.Contains(new Point(i, j)))
{
bm.SetPixel(i, j, Color.Black);
sym.Add(new Point(i, j));
if (i > 1)
{
if (Segmentation.GetBrightness(bm.GetPixel(i-1, j)) < 100)
{
bm.SetPixel(i - 1, j, Color.Black);
sym.Add(new Point(i - 1, j));
}
}
//if (j > 1)
//{
// color = bm.GetPixel(i, j - 1);
// if (Segmentation.GetBrightness(bm.GetPixel(i, j-1)) < 100)
// {
// bm.SetPixel(i, j - 1, Color.Black);
// sym.Add(new Point(i, j - 1));
// }
//}
}
else
{
bm.SetPixel(i, j, Color.White);
}
}
}
}
public static Bitmap ResizeSmallImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
public static Bitmap ResizeImage(Image source, int width, int height)
{
Image dest = new Bitmap(width, height);
using (Graphics gr = Graphics.FromImage(dest))
{
gr.FillRectangle(Brushes.White, 0, 0, width, height); // Очищаем экран
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
float srcwidth = source.Width;
float srcheight = source.Height;
float dstwidth = width;
float dstheight = height;
if (srcwidth <= dstwidth && srcheight <= dstheight) // Исходное изображение меньше целевого
{
//Не изменяем размер картинки, а просто размещаем её по центру
//int left = (width - source.Width) / 2;
//int top = (height - source.Height) / 2;
//gr.DrawImage(source, left, top, source.Width, source.Height);
return ResizeSmallImage(source, width, height); // растягиваем до нужного размера
}
else if (srcwidth / srcheight > dstwidth / dstheight) // Пропорции исходного изображения более широкие
{
float cy = srcheight / srcwidth * dstwidth;
float top = ((float)dstheight - cy) / 2.0f;
if (top < 1.0f) top = 0;
gr.DrawImage(source, 0, top, dstwidth, cy);
}
else // Пропорции исходного изображения более узкие
{
float cx = srcwidth / srcheight * dstheight;
float left = ((float)dstwidth - cx) / 2.0f;
if (left < 1.0f) left = 0;
gr.DrawImage(source, left, 0, cx, dstheight);
}
return (Bitmap)dest;
}
}
}
}
|
a86b9bebe143ee44eee1536a2a83e58c964b09e6
|
C#
|
Plamen-Angelov/Fundamentals-Final-Exam
|
/02. Message Translator/Program.cs
| 3.453125
| 3
|
using System;
using System.Text.RegularExpressions;
namespace _02._Message_Translator
{
class Program
{
static void Main(string[] args)
{
int num = int.Parse(Console.ReadLine());
for (int i = 0; i < num; i++)
{
string message = Console.ReadLine();
Match match = Regex.Match(message, @"!([A-Z][a-z]{2,})!:\[([A-Za-z]{8,})\]");
if (!match.Success)
{
Console.WriteLine("The message is invalid");
continue;
}
else
{
string messageInfo = match.Groups[2].Value;
int[] ASCIIvalues = new int[messageInfo.Length];
for (int j = 0; j < ASCIIvalues.Length; j++)
{
ASCIIvalues[j] = messageInfo[j];
}
Console.WriteLine($"{match.Groups[1].Value}: {string.Join(' ', ASCIIvalues)}");
}
}
}
}
}
|
9f86edea21d5e1b04c5a463592be5829099928fb
|
C#
|
pjtucker/WebApiStrap
|
/WebApiStrap/Domain/Model.cs
| 2.609375
| 3
|
namespace WebApiStrap.Domain
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Infrastructure.Data;
using Infrastructure.Data.OrderBy;
using Infrastructure.Data.Repositories;
using Infrastructure.Data.Searching;
public abstract class Model
{
public static TModel Find<TModel>(IRepository<TModel> repository, object id) where TModel : Model
{
return repository.Find(id);
}
public static IEnumerable<TModel> Find<TModel>(IRepository<TModel> repository) where TModel : Model
{
return repository.Find();
}
public static IEnumerable<TModel> Find<TModel>(IRepository<TModel> repository, Expression<Func<TModel, bool>> filter) where TModel : Model
{
return repository.Find(filter);
}
public static SearchResultSet<TModel> Search<TModel>(IRepository<TModel> repository, Expression<Func<TModel, bool>> filter, OrderBy orderBy, Pagination pagination) where TModel : Model
{
return repository.Search(filter, orderBy, pagination);
}
}
}
|
aa27dbf9fa2eca9cf830d6bd69adf2cdf13119bb
|
C#
|
JornWildt/ZimmerBot
|
/OpenWeatherMap.ZimmerBot.AddOn/OpenWeatherMapProcessor.cs
| 2.640625
| 3
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using log4net;
using ZimmerBot.Core.Processors;
namespace OpenWeatherMap.ZimmerBot.AddOn
{
public static class OpenWeatherMapProcessor
{
static ILog Logger = LogManager.GetLogger(typeof(OpenWeatherMapProcessor));
class CacheEntry
{
public DateTime Timestamp { get; set; }
public ProcessorOutput Output { get; set; }
}
static ConcurrentDictionary<string, CacheEntry> Cache = new ConcurrentDictionary<string, CacheEntry>();
public static ProcessorOutput Weather(ProcessorInput input)
{
string location = input.GetParameter<string>(0);
Logger.Debug($"Lookup current weather for '{location}' at Open Weather Map.");
return GetCached(
CacheKey("weather", location),
() =>
{
Dictionary<string, object> result = GetWeather(location);
return new ProcessorOutput(result);
});
}
public static ProcessorOutput Forecast(ProcessorInput input)
{
string location = input.GetParameter<string>(0);
Logger.Debug($"Lookup weather forecast for '{location}' at Open Weather Map.");
return GetCached(
CacheKey("weather", location),
() =>
{
Dictionary<string, object> result = GetForecast(location);
return new ProcessorOutput(result);
});
}
private static ProcessorOutput GetCached(string key, Func<ProcessorOutput> action)
{
try
{
if (!Cache.ContainsKey(key) || Cache[key].Timestamp < DateTime.Now.AddHours(-1))
{
ProcessorOutput result = action();
Cache[key] = new CacheEntry
{
Timestamp = DateTime.Now,
Output = result
};
}
return Cache[key].Output;
}
catch (Exception ex)
{
Logger.Debug(ex);
return new ProcessorOutput("error", null);
}
}
private static string CacheKey(string function, string location) => function + ":" + location;
private static Dictionary<string, object> GetWeather(string location)
{
OpenWeatherMapAPI api = new OpenWeatherMapAPI();
OpenWeatherMapAPI.Current result = api.GetWeather(location);
var weatherData = new Dictionary<string, object>
{
["temp"] = Math.Round(result.Temperature.Value).ToString(),
["weather"] = result.Weather.Value,
["windDir"] = result.Wind.Direction.Name,
["windSpeed"] = Math.Round(result.Wind.Speed.MetersPerSecond).ToString(),
};
bool isRain = result.Precipitation?.Mode?.Contains("rain") ?? false;
bool isSnow = result.Precipitation?.Mode?.Contains("snow") ?? false;
CalculateState(weatherData, result.Wind.Speed.MetersPerSecond, result.Clouds.Value,
isRain, isSnow,
result.City.Sun.Rise, result.City.Sun.Set);
return weatherData;
}
private static Dictionary<string, object> GetForecast(string location)
{
var parameters = new Dictionary<string, object>();
OpenWeatherMapAPI api = new OpenWeatherMapAPI();
OpenWeatherMapAPI.Forecast result = api.GetForecast(location, 48);
var restOfDay = ForecastRestOfDay(result);
var tomorrow = ForecastTomorrow(result);
parameters["today"] = restOfDay;
parameters["tomorrow"] = tomorrow;
return parameters;
}
private static Dictionary<string, object> ForecastRestOfDay(OpenWeatherMapAPI.Forecast forecast)
{
int firstTomorrowIndex = FindFirstTomorrow(forecast, 0);
Dictionary<string, object> data = CalcForecastData(forecast, 0, firstTomorrowIndex);
data["period"] = "Resten af dagen";
return data;
}
private static Dictionary<string, object> ForecastTomorrow(OpenWeatherMapAPI.Forecast forecast)
{
int firstTomorrowIndex = FindFirstTomorrow(forecast, 6);
Dictionary<string, object> data = CalcForecastData(forecast, firstTomorrowIndex, forecast.List.Count);
data["period"] = "I morgen";
return data;
}
private static int FindFirstTomorrow(OpenWeatherMapAPI.Forecast forecast, int timeOfDay)
{
int today = DateTime.Now.DayOfYear;
int firstTomorrowIndex = 0;
for (int i = 0; i < forecast.List.Count; ++i)
{
if (forecast.List[i].From.DayOfYear != today && forecast.List[i].From.Hour >= timeOfDay)
{
firstTomorrowIndex = i;
break;
}
}
return firstTomorrowIndex;
}
private static Dictionary<string, object> CalcForecastData(OpenWeatherMapAPI.Forecast forecast, int start, int end)
{
decimal minTemp = 100;
decimal maxTemp = -100;
decimal minWind = 100;
decimal maxWind = -100;
decimal precipation = 0;
decimal clouds = 0;
bool isRain = false;
bool isSnow = false;
Dictionary<string, int> weatherTypeCount = new Dictionary<string, int>();
Dictionary<string, int> windDirCodeCount = new Dictionary<string, int>();
for (int i = start; i<end; ++i)
{
var f = forecast.List[i];
if (f.Temperature.Min < minTemp)
minTemp = f.Temperature.Min;
if (f.Temperature.Max > maxTemp)
maxTemp = f.Temperature.Max;
if (f.WindSpeed.MetersPerSecond < minWind)
minWind = f.WindSpeed.MetersPerSecond;
if (f.WindSpeed.MetersPerSecond > maxWind)
maxWind = f.WindSpeed.MetersPerSecond;
if (!weatherTypeCount.ContainsKey(f.Symbol.Name))
weatherTypeCount[f.Symbol.Name] = 0;
weatherTypeCount[f.Symbol.Name]++;
if (!windDirCodeCount.ContainsKey(f.WindDirection.Code))
windDirCodeCount[f.WindDirection.Code] = 0;
windDirCodeCount[f.WindDirection.Code]++;
clouds += f.Clouds.all;
precipation += f.Precipation?.Value ?? 0m;
isRain = isRain || (f.Precipation?.type?.Contains("rain") ?? false);
isSnow = isSnow || (f.Precipation?.type?.Contains("snow") ?? false);
}
var averageWind = (minWind + maxWind) / 2.0m;
var mostUsedWeatherType = weatherTypeCount.OrderBy(i => i.Value > i.Value).FirstOrDefault();
var mostUsedWindDirCode = windDirCodeCount.OrderBy(i => i.Value > i.Value).FirstOrDefault();
decimal averageClouds = clouds / (end - start);
var forecastData = new Dictionary<string, object>
{
["minTemp"] = Math.Round(minTemp).ToString(),
["maxTemp"] = Math.Round(maxTemp).ToString(),
["weather"] = mostUsedWeatherType.Key,
["windDir"] = mostUsedWindDirCode.Key,
["windMin"] = Math.Round(minWind).ToString(),
["windMax"] = Math.Round(maxWind).ToString(),
["windSpeed"] = Math.Round(averageWind).ToString()
};
CalculateState(forecastData, maxWind, averageClouds, isRain, isSnow, forecast.Sun.Rise, forecast.Sun.Set);
return forecastData;
}
private static void CalculateState(
Dictionary<string, object> output, decimal wind, decimal clouds,
bool isRain, bool isSnow,
DateTime sunrise, DateTime sunset)
{
bool isStrongBreeze = wind >= 10.8m;
bool isGale = wind >= 13.9m;
bool isStorm = wind >= 24.5m;
bool isCloudy = clouds > 75;
bool isClear = clouds < 15;
DateTime now = DateTime.Now;
bool isSunny = isClear && sunrise < now && now < sunset;
output["isStrongBreeze"] = isStrongBreeze ? "1" : null;
output["isGale"] = isGale ? "1" : null;
output["isStorm"] = isStorm ? "1" : null;
output["isRain"] = isRain ? "1" : null;
output["isSnow"] = isSnow ? "1" : null;
output["isClear"] = isClear ? "1" : null;
output["isCloudy"] = isCloudy ? "1" : null;
output["isSunny"] = isSunny ? "1" : null;
}
}
}
|
064b3194c16eb864af08c811ef64ec8ad7f0165f
|
C#
|
AndersChen123/NDatabase
|
/src/Tool/DLogger.cs
| 2.640625
| 3
|
using System.Collections.Generic;
namespace NDatabase.Tool
{
/// <summary>
/// Simple logging class
/// </summary>
internal static class DLogger
{
private static readonly IList<ILogger> Loggers = new List<ILogger>();
internal static void Register(ILogger logger)
{
Loggers.Add(logger);
}
internal static void Warning(object @object)
{
foreach (var logger in Loggers)
{
logger.Warning(@object == null
? "null"
: @object.ToString());
}
}
internal static void Debug(object @object)
{
foreach (var logger in Loggers)
{
logger.Debug(@object == null
? "null"
: @object.ToString());
}
}
internal static void Info(object @object)
{
foreach (var logger in Loggers)
{
logger.Info(@object == null
? "null"
: @object.ToString());
}
}
internal static void Error(object @object)
{
foreach (var logger in Loggers)
{
logger.Error(@object == null
? "null"
: @object.ToString());
}
}
}
}
|
9c3a3534393348c0b724c18e4d9a3cc621452dbf
|
C#
|
rakeshcreown/creown-tutor
|
/CreownTutor/CreownTutor/CreownTutor.Data/Repository/ReviewRepository.cs
| 2.765625
| 3
|
using CreownTutor.Data.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreownTutor.Data.Repository
{
public class ReviewRepository:BaseRepository
{
public int saverating(ReviewModel model)
{
int result = 0;
dbEntity.Reviews.Add(new Review
{
// UserID = 1,
ReviewRating = model.Rating,
ReviewComments = model.ReviewComment,
CourseID=1,
SessionID=1,
AddedTime=DateTime.Now
});
dbEntity.SaveChanges();
var newScore = (from a in dbEntity.Reviews
where a.SessionID.Equals(1)
group a by a.SessionID into aa
select new
{
Score = aa.Sum(a => a.ReviewRating) / aa.Count()
}).FirstOrDefault();
result = newScore.Score;
return result;
}
}
}
|
a4939210257e3b7f492e116365184dbd57ea4f62
|
C#
|
root-servers/ImageSharp
|
/tests/ImageSharp.Tests/TestFileSystem.cs
| 2.75
| 3
|
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Collections.Generic;
using System.IO;
namespace SixLabors.ImageSharp.Tests
{
/// <summary>
/// A test image file.
/// </summary>
public class TestFileSystem : ImageSharp.IO.IFileSystem
{
private readonly Dictionary<string, Stream> fileSystem = new Dictionary<string, Stream>(StringComparer.OrdinalIgnoreCase);
public void AddFile(string path, Stream data)
{
lock (this.fileSystem)
{
this.fileSystem.Add(path, data);
}
}
public Stream Create(string path)
{
// if we have injected a fake file use it instead
lock (this.fileSystem)
{
if (this.fileSystem.ContainsKey(path))
{
Stream stream = this.fileSystem[path];
stream.Position = 0;
return stream;
}
}
return File.Create(path);
}
public Stream OpenRead(string path)
{
// if we have injected a fake file use it instead
lock (this.fileSystem)
{
if (this.fileSystem.ContainsKey(path))
{
Stream stream = this.fileSystem[path];
stream.Position = 0;
return stream;
}
}
return File.OpenRead(path);
}
}
}
|
b1780f0090353d48a62c5c44d8cbb9dc98831573
|
C#
|
mabargiel/AdventOfCode
|
/AdventOfCode.Tests/2020/Day8.cs
| 2.75
| 3
|
using AdventOfCode.Tests.Helpers;
using NUnit.Framework;
using Shouldly;
namespace AdventOfCode.Tests._2020;
public class Day8
{
private static object[] Codes =
{
new object[]
{
@"nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6".TrimIndent(),
5
},
new object[]
{
@"nop +0
acc +100
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6".TrimIndent(),
104
}
};
[Test]
[TestCaseSource(nameof(Codes))]
public void Part1(string input, int expected)
{
var d8 = new Days._2020._8.Day8(input);
var result = d8.Part1();
result.ShouldBe(expected);
}
[Test]
public void Part2()
{
var input = @"nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6".TrimIndent();
var d8 = new Days._2020._8.Day8(input);
var result = d8.Part2();
result.ShouldBe(8);
}
}
|
b175a2b4ce84a31947d101efb1642e5a11854efc
|
C#
|
jhoerr/box-csharp-sdk-v2
|
/BoxApi.V2/Model/SharedLink.cs
| 2.890625
| 3
|
using System;
using BoxApi.V2.Model.Enum;
using Newtonsoft.Json;
namespace BoxApi.V2.Model
{
/// <summary>
/// An object representing this items shared link and associated permissions
/// </summary>
public class SharedLink
{
/// <summary>
/// Parameterless constructor required for deserialization
/// </summary>
public SharedLink()
{
}
/// <summary>
/// Creates a SharedLink to associate with a File or folder
/// </summary>
/// <param name="access">With whom the item should be shared</param>
/// <param name="unsharedAt">Automatically stop sharing at this time</param>
/// <param name="permissions">The </param>
public SharedLink(Access access, DateTime? unsharedAt = null, Permissions permissions = null) : this()
{
Access = access;
Permissions = permissions ?? new Permissions() {CanDownload = true, CanPreview = true};
if (unsharedAt.HasValue)
{
UnsharedAt = unsharedAt.Value;
}
}
/// <summary>
/// The level of access required for this shared link. Can be: Open, Company, Collaborators.
/// </summary>
public Access Access { get; set; }
/// <summary>
/// The day that this link should be disabled at. Timestamps are rounded off to the given day.
/// </summary>
[JsonProperty(PropertyName = "unshared_at")]
public DateTime? UnsharedAt { get; set; }
/// <summary>
/// The set of permissions that apply to this shared item
/// </summary>
public Permissions Permissions { get; set; }
/// <summary>
/// The URL to be used when requesting information about this item.
/// </summary>
public string Url { get; set; }
/// <summary>
/// The URL from which this item can be downloaded.
/// </summary>
public string DownloadUrl { get; set; }
/// <summary>
/// Whether this item is password-protected
/// </summary>
[JsonProperty(PropertyName = "is_password_enabled")]
public bool IsPasswordEnabled { get; set; }
/// <summary>
/// The number of times this item has been downloaded
/// </summary>
public int DownloadCount { get; set; }
/// <summary>
/// The number of times this item has been previewed
/// </summary>
public int PreviewCount { get; set; }
}
}
|
3ea37a2c68924e8efe4a18b81a5ab9742ab0870c
|
C#
|
swsandra/AIForGames
|
/Assets/FSM/StopAndTimePassTrans.cs
| 2.53125
| 3
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class StopAndTimePassTrans : Transition{
GameObject invocant;
DateTime creationTime;
float delay;
bool changeCreationTime;
string nextTransition;
public StopAndTimePassTrans(GameObject inv, float d, string transition){
invocant=inv;
delay=d;
nextTransition=transition;
changeCreationTime=true;
//Save creation time
//creationTime = System.DateTime.Now;
}
public override bool IsTriggered(){
//If it has no path, wait until time has passed
if(invocant.GetComponent<GraphPathFollowing>().path.Count==0){
//For now it cheks if n sec have passed
if (changeCreationTime){
creationTime = System.DateTime.Now;
changeCreationTime=false;
}
DateTime currentTime = System.DateTime.Now;
if (Mathf.Abs((float)((currentTime - creationTime).TotalSeconds))>delay){
//Debug.Log(delay+" seconds have passed.");
return true;
}
}
return false;
}
public override string GetTargetState(){
invocant.GetComponent<GraphPathFollowing>().astar_target=null; //Just in case
invocant.GetComponent<GraphPathFollowing>().path=new List<Node>();
changeCreationTime=true;
return nextTransition;
}
}
|
7ee1e625673c82d1ad19e06b09521befc803abe0
|
C#
|
KubaPr/TDD-Workshop
|
/RomanNumeralsConverter.Tests/RomanNumeralValidatorTests.cs
| 3.109375
| 3
|
using FluentAssertions;
using NUnit.Framework;
namespace RomanNumeralsConverter.Tests
{
internal class RomanNumeralValidatorTests
{
private RomanNumeralValidator _validator;
[SetUp]
public void SetUp()
{
_validator = new RomanNumeralValidator();
}
//TODO: tests with numerical values - how to test this? Reading lines from console returns string
[Test]
[TestCase("A")]
[TestCase("XP")]
[TestCase(" ")]
[TestCase("%")]
public void Should_ReturnNotValidRomanNumeralError_When_InputHasCharactersOtherThanValidRomanNumerals(string romanNumeral)
{
const string errorMessage = "Input is invalid - one or more input characters are not a valid Roman numeral";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
[TestCase(null)]
public void Should_ReturnNullInputValidationError_When_InputIsNull(string romanNumeral)
{
const string errorMessage = "Input not given";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
[TestCase("")]
public void Should_ReturnNullInputValidationError_When_InputIsEmpty(string romanNumeral)
{
const string errorMessage = "Input not given";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
[TestCase("XXXX")]
public void Should_ReturnThreeNumeralsInARowError_When_MoreThanThreeNumeralsOtherThanMInARow(string romanNumeral)
{
const string errorMessage = "Input is invalid - more than three numerals other than M in a row";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
[TestCase("IL")]
public void Should_ReturnSmallerIsLessThanOneTenthOfTheLargerError_When_SmallerIsLessThanOneTenthOfTheLarger(string romanNumeral) //TODO: to split into separate tests (edge cases), name is awful
{
const string errorMessage = "Input is invalid - smaller value to the left and is less then one tenth of the next numeral value found";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
[TestCase("VX")]
public void Should_ReturnSmallerValueFirstDigitDivisibleBy5Error_When_SmallerValueBeforeLarger_AndConvertedSmallerValueFirstDigitDivisibleBy5(string romanNumeral)
{
const string errorMessage = "Input is invalid - smaller value to the left and is either V, L or D";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
[TestCase("XXXVV")]
public void Should_ReturnVorLorDRepeatedMoreThanOnceError_When_VorLorDRepeatedMoreThanOnce(string romanNumeral)
{
const string errorMessage = "Input is invalid - V, L or D repeated more than once";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
[TestCase("VIX")]
[TestCase("IXC")]
[TestCase("XCX")]
public void Should_ReturnBiggerNumeralAfterSmallerNumeralError_When_BiggerNumeralAfterSmallerNumeral(string romanNumeral)
{
const string errorMessage = "Input is invalid - the value must never increase from one letter to the next unless substracting";
var result = _validator.Validate(romanNumeral);
result.Messages.Should().Contain(errorMessage);
}
}
}
|
aa40e20f9663a7aeb741bcc9d98f868e27b197a8
|
C#
|
marko-johnson/DevBuildLab_StackOverflow
|
/Models/DAL.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using Dapper.Contrib.Extensions;
using Dapper;
namespace FoC_StackOverflow.Models
{
public class DAL
{
//public static MySqlConnection DB = new MySqlConnection("Server=localhost;Database=foc_stackoverflow;Uid=root;Password=abc123");
public static MySqlConnection DB;
public static QuestionAnswers GetAnswerForQuestion(int thequestID)
{
var keyvalues = new { questID = thequestID };
string sql = "select * from answers where questionid = @questID";
QuestionAnswers qa = new QuestionAnswers();
qa.answer = DB.Query<Answers>(sql, keyvalues).ToList();
qa.quest = DAL.GetQuestions(thequestID);
return qa;
}
public static List<Questions> GetAllQuestions()
{
return DB.GetAll<Questions>().ToList();
}
public static Questions GetQuestions(int id)
{
return DB.Get<Questions>(id);
}
public static void UpdateQuestions(Questions quest)
{
DB.Update(quest);
}
public static void DeleteQuestion(int id)
{
Questions quest = new Questions();
quest.id = id;
DB.Delete<Questions>(quest);
}
public static void InsertQuestion(Questions quest)
{
DB.Insert(quest);
}
public static void InsertAnswer(Answers answer)
{
DB.Insert(answer);
}
}
}
|
1726a5378d1bb971c64e101b28bde51144b28219
|
C#
|
Geoffrotism/RPG
|
/Assets/Scripts/World/Tile.cs
| 3.09375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile {
public int X;
public int Y;
public int Z;
// 1 = fully passable, 0 = not passable.
public int pathWeight; // Tile movement speed. we change this whenever the modifier is changed. ALWAYS USE THIS TO CALCULATE MOVEMENT.
//public enum terrain; //use this later when dealing with multiple terrain types, for now we assume default terrain.
public Area area {get; protected set;}
public Tile()
{
}
public Tile(int x, int y, int z, int pathWeight = 1)
{
GameObject tile_go = new GameObject();
tile_go = MonoBehaviour.Instantiate(World.baseObjects["Ground"]) as GameObject;
this.X = x;
this.Y = y;
this.Z = z;
this.pathWeight = pathWeight;
tile_go.name = "Tile_" + x + "_" + y + "_" + z;
tile_go.transform.position = new Vector3(x, y, z);
}
public void setArea(Area inputArea)
{
area = inputArea;
}
/// <summary>
/// Get the adjacent tile in the direction given.
/// </summary>
/// <param name="ii">Use numbers 1-4, starting North and going clockwise.</param>
/// <returns>The tile adjacent to this one.</returns>
public Tile getAdjacentTile(int ii)
{
switch (ii)
{
case 1:
return North();
case 2:
return East();
case 3:
return South();
case 4:
return West();
default:
return North();
}
}
public Tile North()
{
return World.Instance.GetTileAt(this.X, this.Y, this.Z + 1) ?? null;
}
public Tile South()
{
return World.Instance.GetTileAt(this.X, this.Y, this.Z - 1) ?? null;
}
public Tile East()
{
return World.Instance.GetTileAt(this.X + 1, this.Y, this.Z) ?? null;
}
public Tile West()
{
return World.Instance.GetTileAt(this.X - 1, this.Y, this.Z + 1) ?? null;
}
public List<Tile> getAdjTiles()
{
List<Tile> list = new List<Tile>(4);
list.Add(this.North());
list.Add(this.South());
list.Add(this.East());
list.Add(this.West());
return list;
}
public string toString()
{
return "(" + this.X + ", " + this.Y + ", " + this.Z + ")";
}
}
|
ceea9ca943bdfa8304ab08587f83f2b4226ac9e5
|
C#
|
theoners/Programing-Basics-Exams
|
/Exam - 17 December 2017/03. Ivanovi's Holiday/Program.cs
| 3.453125
| 3
|
using System;
namespace _03._Ivanovi_s_Holiday
{
class Program
{
static void Main(string[] args)
{
int numberOfNights = int.Parse(Console.ReadLine());
string destination = Console.ReadLine();
string transport = Console.ReadLine();
double priceAdults = 0;
double priceChildren = 0;
double priceTransportAdult = 0;
double priceTransportChildren = 0;
if (destination=="Miami")
{
if (numberOfNights<=10)
{
priceAdults = 24.99;
priceChildren = 14.99;
}
else if (numberOfNights<=15)
{
priceAdults = 22.99;
priceChildren = 11.99;
}
else
{
priceAdults = 20;
priceChildren = 10;
}
}
else if (destination== "Canary Islands")
{
if (numberOfNights <= 10)
{
priceAdults = 32.50;
priceChildren = 28.50;
}
else if (numberOfNights <= 15)
{
priceAdults = 30.50;
priceChildren = 25.60;
}
else
{
priceAdults = 28;
priceChildren = 22;
}
}
else
{
if (numberOfNights <= 10)
{
priceAdults = 42.99;
priceChildren = 39.99;
}
else if (numberOfNights <= 15)
{
priceAdults = 41;
priceChildren = 36;
}
else
{
priceAdults = 38.50;
priceChildren = 32.40;
}
}
switch (transport)
{
case "train":
priceTransportAdult = 22.30;
priceTransportChildren =12.50;
break;
case "airplane":
priceTransportAdult = 90;
priceTransportChildren = 68.50;
break;
case "bus":
priceTransportAdult = 45;
priceTransportChildren = 37;
break;
}
double costHoliday =numberOfNights* (priceAdults * 2 + priceChildren * 3) * 1.25;
double costTransport = priceTransportAdult * 2 + priceTransportChildren * 3;
double totalCost = costHoliday + costTransport;
Console.WriteLine($"{totalCost:F3}");
}
}
}
|
eb99b46376f775e55b1c123795917d8da99980af
|
C#
|
KeithAnderson1345/ElevenNote
|
/ElevenNote.Data/Note.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElevenNote.Data //THIS LAYER WILL BE USED TO HOUSE THE INFO ABOUT THE DATA ENTITIES. THESE ENTITIES WILL MATCH THE DATA TABLES IN TH PROJECT.
{
public class Note //Entity model to be used as columns in the SQL table.
{
[Key]
public int NoteId { get; set; }
[ForeignKey(nameof(Category))]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
[Required]
public Guid OwnerId { get; set; } //Guid is a type that allows a unique, near impossible to replicate, ID for the users or items for the users.
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[Required]
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset? ModifiedUtc { get; set; }
}
}
|
fecb061e2d7c56e27710dcaedfdd9a1b01706a5c
|
C#
|
wwaii/Gaussian_Sotong-IP
|
/Assets/Scripts/IntObjects/Daruk.cs
| 2.734375
| 3
|
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
public class Daruk : MonoBehaviour
{
// Have an Idle and a Patrolling state
// In Idle state, it will stand still for a few seconds, before changing to Patrolling
// In Patrolling state, it will move towards a defined checkpoint.
// After it reaches the checkpoint, go back to Idle state.
/// <summary>
/// This stores the current state that the AI is in
/// </summary>
public string currentState;
/// <summary>
/// This stores the next state that the AI should transition to
/// </summary>
public string nextState;
/// <summary>
/// The NavMeshAgent component attached to the gameobject
/// </summary>
private NavMeshAgent agentComponent;
/// <summary>
/// The current player that is being seen by the AI
/// </summary>
public Transform target;
public PlayerBehaviour connectedPlayer;
public GameObject talkingPartOne;
public GameObject talkingPartTwo;
public GameObject talkingPartThree;
public GameController gameController;
private void Awake()
{
// Get the attached NavMeshAgent and store it in agentComponent
agentComponent = GetComponent<NavMeshAgent>();
}
// Start is called before the first frame update
void Start()
{
// Set the starting state as Idle
nextState = "Idle";
}
// Update is called once per frame
void Update()
{
// Check if the AI should change to a new state
if (nextState != currentState)
{
// Stop the current running coroutine first before starting a new one.
StopCoroutine(currentState);
currentState = nextState;
StartCoroutine(currentState);
}
}
/// <summary>
/// The behaviour of the AI when in the Idle state
/// </summary>
/// <returns></returns>
IEnumerator Idle()
{
while (currentState == "Idle")
{
// This while loop will contain the Idle behaviour
// The AI will wait for a few seconds before continuing.
yield return null;
agentComponent.speed = 20f;
// Change to Patrolling state.
if (!gameController.darukStopFollow)
{
if (gameController.darukMissionStart)
{
nextState = "Following";
}
}
}
}
/// <summary>
/// The behaviour of the AI when in the Patrolling state
/// </summary>
/// <returns></returns>
IEnumerator Following()
{
// Set the checkpoint that this AI should move towards
bool hasReached = false;
target = GameObject.Find("Player").transform;
while (currentState == "Following")
{
// This while loop will contain the Patrolling behaviour
agentComponent.SetDestination(target.position);
yield return null;
if (!hasReached)
{
agentComponent.speed -= Time.deltaTime*2;
// If agent has not reached destination, do the following code
// Check that the agent is at an acceptable stopping distance from the destination
if (agentComponent.remainingDistance <= agentComponent.stoppingDistance)
{
// We want to make sure this only happens once.
hasReached = true;
// Change back to Idle state.
nextState = "Idle";
}
}
}
}
public void talk()
{
talkingPartOne.SetActive(true);
gameController.PauseGame();
}
public void talkTwo()
{
talkingPartTwo.SetActive(true);
gameController.PauseGame();
gameController.woodCount -= 5;
gameController.darukStopFollow = true;
}
public void talkThree()
{
talkingPartThree.SetActive(true);
gameController.PauseGame();
}
}
|
19363ac8a6375b4a8ff7dd138eec1e9e853172c6
|
C#
|
carlreid/BlockEd
|
/MapTile.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlockEd
{
class MapTile
{
public MapTile(int spriteID, int xPos, int yPos)
{
_spriteID = spriteID;
_xPos = xPos;
_yPos = yPos;
}
public void newData(int spriteID, int xPos, int yPos)
{
_spriteID = spriteID;
_xPos = xPos;
_yPos = yPos;
}
public void setID(int ID)
{
_spriteID = ID;
}
public void setPosition(int X, int Y)
{
_xPos = X;
_yPos = Y;
}
public int getID()
{
return _spriteID;
}
public int getX()
{
return _xPos;
}
public int getY()
{
return _yPos;
}
private int _spriteID;
private int _xPos;
private int _yPos;
}
}
|
9b1dcf4a1faf63a16e8004057f4e361f9ffc634c
|
C#
|
Heinzman/DigiRcMan
|
/VisualStudio/Sources/SerialPortReader/SerialPortReaders/PortReaderWriter.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Elreg.BusinessObjects.DerivedEventArgs;
using Elreg.BusinessObjects.Interfaces;
namespace Elreg.SerialPortReader.SerialPortReaders
{
public class PortReaderWriter : PortReader, ISerialPortWriter
{
public PortReaderWriter(ISerialPort serialPort) : base(serialPort) {}
public event EventHandler<SerialLineDataSentEventArgs> LineDataSent;
public void Write(List<int> intValues)
{
int count = intValues.Count;
if (SerialPort.IsOpen && count > 0)
{
WriteBytesToSerialPort(intValues, count);
RaiseEventSerialLineDataSent(intValues);
}
}
private void RaiseEventSerialLineDataSent(IEnumerable<int> intValues)
{
if (LineDataSent != null)
{
string line = CreateLineString(intValues);
LineDataSent(this, new SerialLineDataSentEventArgs(line));
}
}
private string CreateLineString(IEnumerable<int> intValues)
{
StringBuilder lineBuilder = new StringBuilder();
foreach (int intValue in intValues)
{
lineBuilder.Append(intValue.ToString("X2", CultureInfo.InvariantCulture));
lineBuilder.Append(" ");
}
lineBuilder.Append("\n");
return lineBuilder.ToString();
}
private void WriteBytesToSerialPort(IEnumerable<int> intValues, int count)
{
const int offset = 0;
byte[] bytesToSend = new byte[count];
int index = 0;
foreach (int intValue in intValues)
bytesToSend[index++] = (byte) intValue;
SerialPort.Write(bytesToSend, offset, count);
}
}
}
|
32a6c02a27765c290958c17687dfcb61e5aec7d9
|
C#
|
Crogarox/HPA-Godot-Mono
|
/Scripts/Grid/Entrance.cs
| 2.625
| 3
|
using System.Collections;
using System;
using System.Linq;
using System.Collections.Generic;
using Godot;
[Serializable]
public class Entrance
{
public Cluster Cluster1 { get; private set; }
public Cluster Cluster2;
public Vector2 OriginPosition { get; private set; }
public Vector2 EndPosition { get; private set; }
public List<Cell> entranceTiles = new List<Cell>();
public List<Cell> symmEntranceTiles = new List<Cell>();
public List<Junction> entranceJunctions = new List<Junction>();
public bool isBlocked = false;
public Entrance()
{
}
public void SetOriginPosition(Vector2 position)
{
this.OriginPosition = position;
}
public void SetClusters(Cluster Cluster1, Cluster Cluster2)
{
this.Cluster1 = Cluster1;
this.Cluster2 = Cluster2;
}
public void SetClusters(Cluster[] pair)
{
if (pair.Length > 2)
{
throw new System.Exception("Cannot have more than 2 elements in argument array");
}
else
{
this.Cluster1 = pair[0];
this.Cluster2 = pair[1];
}
}
public void FillEntrance(List<Cell> entranceTiles)
{
this.entranceTiles = entranceTiles;
this.OriginPosition = entranceTiles[0].WorldPosition;
this.EndPosition = entranceTiles[entranceTiles.Count - 1].WorldPosition;
}
public void FillSymmEntrance(List<Cell> symmTiles)
{
symmEntranceTiles = symmTiles;
}
public Cluster[] GetClusters()
{
Cluster[] clusters = new Cluster[2];
clusters[0] = Cluster1;
clusters[1] = Cluster2;
return clusters;
}
public List<Cell> GetEntrance()
{
return entranceTiles;
}
public List<Cell> GetSymm()
{
return symmEntranceTiles;
}
public void AddJunction(Junction Junction)
{
this.entranceJunctions.Add(Junction);
}
public Cell GetSymmetricalCell(Cell Reference)
{
int index = entranceTiles.IndexOf(Reference);
try
{
Cell symmCell = symmEntranceTiles[index];
return symmCell;
}
catch (System.Exception)
{
return null;
}
}
public bool HaveEntrance(Cluster cluster1, Cluster cluster2)
{
bool entranceTilesInside = cluster1.IsEntranceInside(this.entranceTiles);
bool symmTilesInside = cluster2.IsEntranceInside(this.symmEntranceTiles);
if (entranceTilesInside && symmTilesInside)
{
return true;
}
return false;
}
public bool IsJunctionInside(Junction Junction)
{
return entranceJunctions.Contains(Junction);
}
public Entrance MergeEntrances(params Entrance[] entrances)
{
Entrance merged = new Entrance();
try
{
merged.SetClusters(entrances[0].GetClusters());
merged.OriginPosition = entrances[0].OriginPosition;
}
catch (System.Exception)
{
throw;
}
merged.EndPosition = entrances[entrances.Length - 1].EndPosition;
List<Cell> mergedTiles = new List<Cell>();
List<Cell> mergedSymmTiles = new List<Cell>();
List<Junction> mergedJunctions = new List<Junction>();
foreach (Entrance e in entrances)
{
mergedTiles = mergedTiles.Concat(e.entranceTiles).ToList();
mergedSymmTiles = mergedSymmTiles.Concat(e.symmEntranceTiles).ToList();
mergedJunctions = mergedJunctions.Concat(e.entranceJunctions).ToList();
}
merged.entranceTiles = mergedTiles;
merged.symmEntranceTiles = mergedSymmTiles;
merged.entranceJunctions = mergedJunctions;
if (mergedJunctions.Count == 0)
{
merged.isBlocked = true;
}
return merged;
}
}
|
a285512bd22db7629ee79444713f55349a69943a
|
C#
|
sebastianoscarlopez/Scraping
|
/scraping/Program.cs
| 2.53125
| 3
|
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using AngleSharp;
using AngleSharp.Dom;
namespace scraping
{
class Program
{
static void Main(string[] args)
{
var servicesProvider = BuildDi();
var runner = servicesProvider.GetRequiredService<Runner>();
runner.Run();
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
Console.WriteLine("fin");
Console.ReadKey();
}
private static IServiceProvider BuildDi()
{
var services = new ServiceCollection();
//Runner is the custom class
services.AddTransient<Runner>();
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
//configure NLog
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
NLog.LogManager.LoadConfiguration("nlog.config");
return serviceProvider;
}
}
}
|
40b33fb6b48baeb9e02f0b8b2b0fe68e1055b3c8
|
C#
|
jorgeLuizChaves/TCC
|
/MyKinectLibrary/PoseTracking/MathFunctionsManager.cs
| 2.84375
| 3
|
using Microsoft.Kinect;
using MyKinectLibrary.Enums;
using MyKinectLibrary.Model;
using MyKinectLibrary.Model.Auxiliary;
using MyLibrary.Util;
using System;
namespace MyKinectLibrary.PoseTracking
{
/// <summary>
/// This class manages all functions related to math functions
/// </summary>
internal static class MathFunctionsManager
{
#region [Public Methods]
/// <summary>
/// Calcula a lei dos cossenos em todos os planos
/// </summary>
/// <param name="subPose">SubPose que contém a posição dos joints</param>
/// <returns>Retorna um objeto que contém o resultado do angulo em cada um dos planos 2D utilizando a lei dos cossenos</returns>
internal static LawOfCosinesResult LawOfCosinesCalculation( SubPose subPose )
{
LawOfCosinesResult lawOfCosinesResult = new LawOfCosinesResult();
lawOfCosinesResult.PlanXY = LawOfCosinesPlanCalculation( subPose.AuxiliaryJoint1.Position, subPose.CenterJoint.Position, subPose.AuxiliaryJoint2.Position, Axis.X, Axis.Y );
lawOfCosinesResult.PlanXZ = LawOfCosinesPlanCalculation( subPose.AuxiliaryJoint1.Position, subPose.CenterJoint.Position, subPose.AuxiliaryJoint2.Position, Axis.X, Axis.Z );
lawOfCosinesResult.PlanYZ = LawOfCosinesPlanCalculation( subPose.AuxiliaryJoint1.Position, subPose.CenterJoint.Position, subPose.AuxiliaryJoint2.Position, Axis.Y, Axis.Z );
return lawOfCosinesResult;
}
/// <summary>
/// Calcula o produto escalar dos jointts da subpose em um sistema de coordenadas 3D
/// </summary>
/// <param name="subPose">SubPose que contém a posição dos joints</param>
/// <returns>Returna o valor do cálculo do produto escalar</returns>
internal static double ScalarProductCalculation( SubPose subPose )
{
Vector3D vectorV = Vector3DBetweenTwoJoints(subPose.AuxiliaryJoint1,subPose.CenterJoint);
Vector3D vectorW = Vector3DBetweenTwoJoints(subPose.AuxiliaryJoint2,subPose.CenterJoint);
double resultVW = vectorV.X * vectorW.X + vectorV.Y * vectorW.Y + vectorV.Z * vectorW.Z;
double resultModuleVW = Math.Sqrt( Math.Pow( vectorV.X, 2 ) + Math.Pow( vectorV.Y, 2 ) + Math.Pow( vectorV.Z, 2 ) ) * Math.Sqrt( Math.Pow( vectorW.X, 2 ) + Math.Pow( vectorW.Y, 2 ) + Math.Pow( vectorW.Z, 2 ) );
double resultInRadians = Math.Acos( resultVW / resultModuleVW );
double resultInDegrees = resultInRadians * 180 / Math.PI;
return resultInDegrees;
}
/// <summary>
/// Compara dois valores utilizando margem de erro
/// </summary>
/// <param name="value1">Primeiro valor</param>
/// <param name="value2">Segundo valor</param>
/// <param name="errorMargin">Margem de erro</param>
/// <returns>Retorna true caso o valor seja aceito considerando a margem de erro e false caso o valor não seja aceito</returns>
public static bool ComparisonWithErrorMargin( double value1, double value2, double errorMargin )
{
return value1 >= value2 - errorMargin && value1 <= value2 + errorMargin;
}
#endregion end of [Public Methods]
#region [Private Methods]
/// <summary>
/// Calcula o angule entre os três joints enviados por parâmetros
/// </summary>
/// <param name="auxiliaryJointPosition">Posição do primeiro Joint</param>
/// <param name="centerJointPosition">Posição do segundo Joint</param>
/// <param name="auxiliary2JointPosition">Posição do terceiro Joint</param>
/// <param name="firstAxis">Primeiro eixo para o cálculo</param>
/// <param name="secondAxis">Segundo eixo para o cálculo</param>
/// <returns>Retorna o resultado da lei dos cossenos em graus</returns>
private static double LawOfCosinesPlanCalculation( SkeletonPoint auxiliaryJointPosition, SkeletonPoint centerJointPosition,SkeletonPoint auxiliary2JointPosition, Axis firstAxis, Axis secondAxis )
{
double firstAxisCenterJointPosition = centerJointPosition.GetType().GetProperty( firstAxis.ToString() ).GetValue( centerJointPosition, null ).To<double>();
double secondAxisCenterJointPosition = centerJointPosition.GetType().GetProperty(secondAxis.ToString()).GetValue(centerJointPosition, null).To<double>();
double firstAxisAuxiliaryJointPosition = auxiliaryJointPosition.GetType().GetProperty(firstAxis.ToString()).GetValue(auxiliaryJointPosition, null).To<double>();
double secondAxisAuxiliaryJointPosition = auxiliaryJointPosition.GetType().GetProperty(secondAxis.ToString()).GetValue(auxiliaryJointPosition, null).To<double>();
double firstAxisAuxiliaryJoint2Position = auxiliary2JointPosition.GetType().GetProperty(firstAxis.ToString()).GetValue(auxiliary2JointPosition, null).To<double>();
double secondAxisAuxiliaryJoint2Position = auxiliary2JointPosition.GetType().GetProperty(secondAxis.ToString()).GetValue(auxiliary2JointPosition, null).To<double>();
double a = StraightSegmentBetweenTwoJoints( firstAxisAuxiliaryJointPosition, secondAxisAuxiliaryJointPosition, firstAxisCenterJointPosition, secondAxisCenterJointPosition );
double b = StraightSegmentBetweenTwoJoints( firstAxisCenterJointPosition, secondAxisCenterJointPosition, firstAxisAuxiliaryJoint2Position, secondAxisAuxiliaryJoint2Position );
double c = StraightSegmentBetweenTwoJoints( firstAxisAuxiliaryJointPosition, secondAxisAuxiliaryJointPosition, firstAxisAuxiliaryJoint2Position, secondAxisAuxiliaryJoint2Position );
double resultInRadians = Math.Acos( ( Math.Pow( a, 2 ) + Math.Pow( b, 2 ) - Math.Pow( c, 2 ) ) / ( 2 * a * b ) );
double ResultInDegrees = resultInRadians * 180 / Math.PI;
return ResultInDegrees;
}
/// <summary>
/// Cálcula o vetor de distância entre dois joints
/// </summary>
/// <param name="joint1Axis1">Posição do primeiro eixo do primeiro joint</param>
/// <param name="joint1Axis2">Posição do segundo eixo do primeiro joint</param>
/// <param name="joint2Axis1">Posição do primeiro eixo do segundo joint</param>
/// <param name="joint2Axis2">Posição do segundo eixo do segundo joint</param>
/// <returns>Distância entre o valor de distância entre dois joints enviados por parâmetros</returns>
private static double StraightSegmentBetweenTwoJoints( double joint1Axis1, double joint1Axis2, double joint2Axis1, double joint2Axis2 )
{
return Math.Sqrt( Math.Pow( joint1Axis1 - joint2Axis1, 2 ) + Math.Pow( joint1Axis2 - joint2Axis2, 2 ) );
}
/// <summary>
/// Calcula o vetor 3D dos dois joints
/// </summary>
/// <param name="joint1">Primeiro joint</param>
/// <param name="joint2">Segundo joint</param>
/// <returns>Vector3D entre os joints enviados por parâmetros</returns>
private static Vector3D Vector3DBetweenTwoJoints( Joint joint1, Joint joint2 )
{
Vector3D vector = new Vector3D();
vector.X = Math.Sqrt( Math.Pow( joint1.Position.X - joint2.Position.X, 2 ) );
vector.Y = Math.Sqrt( Math.Pow( joint1.Position.Y - joint2.Position.Y, 2 ) );
vector.Z = Math.Sqrt( Math.Pow( joint1.Position.Z - joint2.Position.Z, 2 ) );
return vector;
}
#endregion end of [Private Methods]
}
}
|
a4e88939ecf0e8c088b26a1816aad75dfaa46223
|
C#
|
Narvalex/EstanciaGanadera
|
/src/libs/Eventing.HttpClient-v1.0.0/HttpLite.cs
| 2.640625
| 3
|
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Eventing.Client.Http
{
/// <summary>
/// This could be a whole lot improved with a limited pool
/// https://pastebin.com/jftEbWrc
/// https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
/// This is a little discusion about it.
/// For multiclient (like a web server) there is no way to make a pool of http clients efficiently, but
/// for a single client (like a WinForm app) we could just have an instance of http lite
/// </summary>
public class HttpLite : IHttpLite
{
private readonly string hostUri;
private Func<string> threadSafeTokenProvider = () => string.Empty;
public HttpLite(string hostUri)
{
Ensure.NotNullOrWhiteSpace(hostUri, nameof(hostUri));
this.hostUri = hostUri;
}
public async Task<TResult> Get<TResult>(string uri, string token = null)
{
using (var client = this.CreateHttpClient(token))
{
var endpoint = new Uri(new Uri(this.hostUri), uri);
var response = await client.GetAsync(endpoint.AbsoluteUri);
this.EnsureResponseIsOk(uri, response);
var result = await response.Content.ReadAsAsync<TResult>();
return result;
}
}
public async Task<Stream> Get(string uri, string token = null)
{
using (var client = this.CreateHttpClient(token))
{
var endpoint = new Uri(new Uri(this.hostUri), uri);
var response = await client.GetAsync(endpoint.AbsoluteUri);
this.EnsureResponseIsOk(uri, response);
var stream = await response.Content.ReadAsStreamAsync();
return stream;
}
}
public async Task Post(string uri, string jsonContent, string token = null)
{
using (var client = this.CreateHttpClient(token))
{
var tokenEndpoint = new Uri(new Uri(this.hostUri), uri);
var stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await client.PostAsync(tokenEndpoint, stringContent);
this.EnsureResponseIsOk(uri, response);
}
}
public async Task<TResult> Post<TResult>(string uri, string jsonContent, string token = null)
{
using (var client = this.CreateHttpClient(token))
{
var tokenEndpoint = new Uri(new Uri(this.hostUri), uri);
var stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await client.PostAsync(tokenEndpoint, stringContent);
this.EnsureResponseIsOk(uri, response);
var responseContent = await response.Content.ReadAsAsync<TResult>();
return responseContent;
}
}
// to build a stream from a byte array = new MemoryStream(byteArray);
//
public async Task Upload(string uri, Stream fileStream, string fileName, string metadatos, string token = null)
{
// Reference: https://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload?noredirect=1&lq=1
using (var client = this.CreateHttpClient(token, false))
{
using (var content = new MultipartFormDataContent($"Upload----{DateTime.Now.ToString(CultureInfo.InvariantCulture)}"))
{
content.Add(new StreamContent(fileStream), "uploadedFile", fileName);
content.Add(new StringContent(metadatos));
var endpoint = new Uri(new Uri(this.hostUri), uri);
var url = endpoint.AbsoluteUri;
var response = await client.PostAsync(url, content);
this.EnsureResponseIsOk(uri, response);
}
}
}
public async Task<TResult> Upload<TResult>(string uri, Stream fileStream, string fileName, string metadatos, string token = null)
{
// Reference: https://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload?noredirect=1&lq=1
using (var client = this.CreateHttpClient(token, false))
{
using (var content = new MultipartFormDataContent($"Upload----{DateTime.Now.ToString(CultureInfo.InvariantCulture)}"))
{
content.Add(new StreamContent(fileStream), "uploadedFile", fileName);
content.Add(new StringContent(metadatos));
var endpoint = new Uri(new Uri(this.hostUri), uri);
var url = endpoint.AbsoluteUri;
var response = await client.PostAsync(url, content);
this.EnsureResponseIsOk(uri, response);
var dto = await response.Content.ReadAsAsync<TResult>();
return dto;
}
}
}
public async Task Post<TContent>(string uri, TContent content, string token = null)
{
await this.TryPostAsJson<TContent>(uri, content, token);
}
public async Task<TResult> Post<TContent, TResult>(string uri, TContent content, string token = null)
{
var response = await this.TryPostAsJson(uri, content, token);
var responseContent = await response.Content.ReadAsAsync<TResult>();
return responseContent;
}
private async Task<HttpResponseMessage> TryPostAsJson<TContent>(string uri, TContent content, string token)
{
using (var client = this.CreateHttpClient(token))
{
var endpoint = new Uri(new Uri(this.hostUri), uri);
var response = await client.PostAsJsonAsync<TContent>(endpoint.AbsoluteUri, content);
this.EnsureResponseIsOk(uri, response);
return response;
}
}
private HttpClient CreateHttpClient(string token, bool isJson = true)
{
var client = new HttpClient();
if (isJson)
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (token != null)
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
private void EnsureResponseIsOk(string uri, HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
return;
else if (response.StatusCode == HttpStatusCode.Unauthorized)
throw new RemoteUnauthrorizedResponseException();
else if (response.StatusCode == HttpStatusCode.ServiceUnavailable
|| response.StatusCode == HttpStatusCode.BadGateway)
throw new ServiceUnavailableException($"The uri {uri} is unavailable");
else
throw new Exception($"Error on posting to {uri}. Status Code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
}
}
}
|
e5156bdf44aececfeb94b071cb93a6644393268f
|
C#
|
11PluseHelp/ExploringRx
|
/TestingObservable/Reactive/Watcher.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestingObservable.Reactive {
public class Watcher : IObserver<string>, IDisposable {
IDisposable unsubscriber;
public void Subscribe(IObservable<string> subject) {
if (unsubscriber == null) {
unsubscriber = subject.Subscribe(this);
}
else {
throw new InvalidOperationException("This observer is already watching an observable!");
}
}
public void OnNext(string next) {
Console.WriteLine(next);
}
public void OnError(Exception ex) {
throw new InvalidOperationException("An error occured in subject of observation", ex);
}
public void OnCompleted() {
Dispose();
}
public void Dispose() {
unsubscriber.Dispose();
}
}
}
|
17e36cf3e41947771313c56df2ab570d4196d235
|
C#
|
rajexim/lessmsi
|
/src/Lessmsi.Tests/TestBase.cs
| 2.71875
| 3
|
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Xunit;
using LessIO;
using System.Linq;
namespace LessMsi.Tests
{
public class TestBase
{
[DebuggerHidden]
protected void ExtractAndCompareToMaster(string msiFileName)
{
var actualFileEntries = ExtractFilesFromMsi(msiFileName, null);
var expectedEntries = GetExpectedEntriesForMsi(msiFileName);
AssertAreEqual(expectedEntries, actualFileEntries);
}
[DebuggerHidden]
protected static void AssertAreEqual(FileEntryGraph expected, FileEntryGraph actual)
{
string msg;
if (!FileEntryGraph.CompareEntries(expected, actual, out msg))
{
throw new Exception(string.Format("FileEntryGraph entries are not the equal: {0}", msg));
}
}
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull)
{
return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, "");
}
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, string outputDir)
{
return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, new Path(outputDir), true);
}
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, Path outputDir, bool returnFileEntryGraph)
{
return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, outputDir, true, true);
}
/// <summary>
/// Extracts some or all of the files from the specified MSI and returns a <see cref="FileEntryGraph"/> representing the files that were extracted.
/// </summary>
/// <param name="msiFileName">The msi file to extract or null to extract all files.</param>
/// <param name="fileNamesToExtractOrNull">The files to extract from the MSI or null to extract all files.</param>
/// <param name="outputDir">A relative directory to extract output to or an empty string to use the default output directory.</param>
/// <param name="skipReturningFileEntryGraph">True to return the <see cref="FileEntryGraph"/>. Otherwise null will be returned.</param>
/// <param name="cleanOutputDirectoryBeforeExtracting">True to delete the output directory before extracting.</param>
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, Path outputDir, bool returnFileEntryGraph, bool cleanOutputDirectoryBeforeExtracting)
{
outputDir = GetTestOutputDir(outputDir, msiFileName);
if (cleanOutputDirectoryBeforeExtracting && FileSystem.Exists(outputDir))
{
FileSystem.RemoveDirectory(outputDir, true);
}
Debug.Assert(!FileSystem.Exists(outputDir), "Directory still exists!");
FileSystem.CreateDirectory(outputDir);
//ExtractViaCommandLine(outputDir, msiFileName);
ExtractInProcess(msiFileName, outputDir.PathString, fileNamesToExtractOrNull);
if (returnFileEntryGraph)
{
// build actual file entries extracted
var actualEntries = FileEntryGraph.GetActualEntries(outputDir.PathString, msiFileName);
// dump to actual dir (for debugging and updating tests)
actualEntries.Save(GetActualOutputFile(msiFileName));
return actualEntries;
}
else
{
return null;
}
}
/// <summary>
/// Returns a suitable output directory for test data while running the test.
/// If <paramref name="outputDir"/> is specified it is used and <paramref name="testNameOrMsiFileName"/> is ignored.
/// Alternatively, <paramref name="testNameOrMsiFileName"/> is used to generate a test dir.
/// </summary>
/// <param name="outputDir">The output dir to use or <see cref="Path.Empty"/>.</param>
/// <param name="testNameOrMsiFileName">
/// A test name (often the name of a msi file under test) to use to generate a test dir when <paramref name="testNameOrMsiFileName"/> is not specified.
/// </param>
/// <returns></returns>
protected Path GetTestOutputDir(Path outputDir, string testNameOrMsiFileName)
{
Path baseOutputDir = Path.Combine(AppPath, "MsiOutputTemp");
if (outputDir.IsEmpty || !outputDir.IsPathRooted)
outputDir = Path.Combine(baseOutputDir, "_" + testNameOrMsiFileName);
else
outputDir = Path.Combine(baseOutputDir, outputDir);
return outputDir;
}
private void ExtractInProcess(string msiFileName, string outputDir, string[] fileNamesToExtractOrNull)
{
//LessMsi.Program.DoExtraction(GetMsiTestFile(msiFileName).FullName, outputDir);
if (fileNamesToExtractOrNull == null)
{ //extract everything:
LessMsi.Msi.Wixtracts.ExtractFiles(GetMsiTestFile(msiFileName), outputDir);
}
else
{
LessMsi.Msi.Wixtracts.ExtractFiles(GetMsiTestFile(msiFileName), outputDir, fileNamesToExtractOrNull);
}
}
/// <summary>
/// This is an "old" way and it is difficul to debug (since it runs test out of proc), but it works.
/// </summary>
private void ExtractViaCommandLine(string msiFileName, string outputDir, string[] filenamesToExtractOrNull)
{
string args = string.Format(" /x \"{0}\" \"{1}\"", GetMsiTestFile(msiFileName), outputDir);
if (filenamesToExtractOrNull != null && filenamesToExtractOrNull.Length > 0)
throw new NotImplementedException();
string consoleOutput;
RunCommandLine(args, out consoleOutput);
}
protected int RunCommandLine(string commandlineArgs)
{
string temp;
return RunCommandLine(commandlineArgs, out temp);
}
/// <summary>
/// Runs lessmsi.exe via commandline.
/// </summary>
/// <param name="commandlineArgs">The arguments passed to lessmsi.exe</param>
/// <param name="consoleOutput">The console output.</param>
/// <returns>The exe return code.</returns>
protected int RunCommandLine(string commandlineArgs, out string consoleOutput)
{
// exec & wait
var startInfo = new ProcessStartInfo(LessIO.Path.Combine(AppPath, "lessmsi.exe").PathString, commandlineArgs);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
var p = Process.Start(startInfo);
// Internal stdout buffer overflows easily if the output is too long (e.g. with a progress indicator enabled), so an async approach is needed here.
// See https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
var outputStringBuilder = new StringBuilder();
var outputWaitHandle = new AutoResetEvent(false);
p.OutputDataReceived += (sender, e) => {
if (e.Data == null) {
outputWaitHandle.Set();
}
else {
outputStringBuilder.AppendLine(e.Data);
}
};
p.BeginOutputReadLine();
bool exited = p.WaitForExit(1000*60) && outputWaitHandle.WaitOne(1000 * 60);
consoleOutput = outputStringBuilder.ToString();
if (!exited)
{
p.Kill();
throw new Exception("Process did not exit for commandlineArgs:" + commandlineArgs + "\n" + consoleOutput + "\n\n" + p.StandardError.ReadToEnd());
}
if (p.ExitCode == 0)
Debug.WriteLine(consoleOutput);
else
{
var errorOutput = p.StandardError.ReadToEnd();
throw new ExitCodeException(p.ExitCode, errorOutput, consoleOutput);
}
return p.ExitCode;
}
/// <summary>
/// Same as <see cref="RunCommandLine"/>, is useful for debugging.
/// </summary>
/// <param name="commandLineArgs"></param>
protected int RunCommandLineInProccess(string commandLineArgs)
{
//NOTE: Obviously oversimplified splitting of args.
var args = commandLineArgs.Split(' ');
for (var i = 0; i < args.Length; i++ )
{
args[i] = args[i].Trim('\"');
}
return LessMsi.Cli.Program.Main(args);
}
internal sealed class ExitCodeException : Exception
{
public ExitCodeException(int exitCode, string errorOutput, string consoleOutput)
: base("lessmsi.exe returned an error code (" + exitCode + "). Error output was:\r\n" + errorOutput + "\r\nConsole output was:\r\n" + consoleOutput)
{
this.ExitCode = exitCode;
}
public int ExitCode { get; set; }
}
/// <summary>
/// Loads the expected entries for the specified MSI file from the standard location.
/// </summary>
/// <param name="forMsi">The msi filename (no path) to load entries for.</param>
/// <returns>The <see cref="FileEntryGraph"/> representing the files that are expected to be extracted from the MSI.</returns>
protected FileEntryGraph GetExpectedEntriesForMsi(string forMsi)
{
return FileEntryGraph.Load(GetExpectedOutputFile(forMsi), forMsi);
}
protected Path GetMsiTestFile(string msiFileName)
{
return Path.Combine(AppPath, "TestFiles", "MsiInput", msiFileName);
}
private Path GetExpectedOutputFile(string msiFileName)
{
return Path.Combine(AppPath, "TestFiles", "ExpectedOutput", msiFileName + ".expected.csv");
}
protected Path GetActualOutputFile(string msiFileName)
{
// strip any subdirectories here since some input msi files have subdirectories.
msiFileName = Path.GetFileName(msiFileName);
var fi = Path.Combine(AppPath, msiFileName + ".actual.csv");
return fi;
}
protected Path AppPath
{
get
{
var codeBase = new Uri(this.GetType().Assembly.CodeBase);
var local = new Path(codeBase.LocalPath);
return local.Parent;
}
}
[DebuggerHidden]
protected void ExpectTables(string sourceFileName, string[] expectedTableNames)
{
using (var msidb = Msi.MsiDatabase.Create(GetMsiTestFile(sourceFileName)))
{
Assert.NotNull(msidb);
var query = "SELECT * FROM `_Tables`";
using (var msiTable = new Msi.ViewWrapper(msidb.OpenExecuteView(query)))
{
Assert.NotNull(msiTable);
var tableNames = from record in msiTable.Records
select record[0] as string;
// Since we don't care about the order, we sort the lists
Assert.Equal(expectedTableNames.OrderBy(s => s), tableNames.OrderBy(s => s));
}
}
}
[DebuggerHidden]
protected void ExpectStreamCabFiles(string sourceFileName, bool hasCab)
{
using (var stg = new OleStorage.OleStorageFile(GetMsiTestFile(sourceFileName)))
{
var strm = stg.GetStreams().Where(elem => OleStorage.OleStorageFile.IsCabStream(elem));
if (strm != null)
{
// Rest of the CAB parsing logic is in the UI, can't extract filenames without duplicating code that we want to test..
Assert.True(hasCab);
}
else
{
// Not expecting to find a cab here
Assert.False(hasCab);
}
}
}
}
}
|
b60af9d137f695d7306522c694007a9ca35b151f
|
C#
|
udayaugustin/VechicleTracking
|
/VechcileTracking/Views/PendingAmount.xaml.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using SQLite;
using VechcileTracking.Models;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace VechcileTracking.Views
{
public partial class PendingAmount : ContentPage
{
SQLiteAsyncConnection connection;
Command CallCommand;
public PendingAmount()
{
InitializeComponent();
connection = DependencyService.Get<ISQLiteDb>().GetConnection();
GetData();
CallCommand = new Command<PendingList>((p) =>
{
PhoneDialer.Open(p.Customer.PhoneNo);
});
}
private async void GetData()
{
var paymentList = await connection.Table<PaymentInfo>().ToListAsync();
var pendingList = new List<PendingList>();
var totalPendingAmount = 0;
foreach(var payment in paymentList)
{
var customer = await connection.Table<Customer>().Where(c => c.Id == payment.CustomerId).FirstOrDefaultAsync();
var amount = payment.TotalAmount - payment.Settled;
totalPendingAmount += amount;
var pending = new PendingList
{
Customer = customer,
Amount = amount,
Command = CallCommand
};
pendingList.Add(pending);
}
TotalPendingAmount.Text = "Total Pending Amount Rs."+totalPendingAmount;
PendingListView.ItemsSource = pendingList;
}
class PendingList
{
public Customer Customer { get; set; }
public int Amount { get; set; }
public Command Command { get; set; }
}
}
}
|
0a3d1bd0933ba3ab165e81c240a08b9527276997
|
C#
|
xeon2007/WSProf
|
/Projects/Workshare.API/CSharpExamples/Program.cs
| 2.71875
| 3
|
using System;
using System.Text;
using System.Threading;
namespace CSharpExamples
{
class Program
{
static void Main(string[] args)
{
// pass the name of the file to redact on the command line
try
{
DiscoverToReportExample.Main(args);
Console.WriteLine("Discovery report example completed successfully");
CompareExample.Main(args);
Console.WriteLine("Compare example completed successfully");
RedactExample.Main(args);
Console.WriteLine("Redact example completed successfully");
CleanExample.Main(args);
Console.WriteLine("Clean example completed successfully");
DiscoverExample.Main(args);
Console.WriteLine("Discovery example completed successfully");
PDFExample.Main(args);
Console.WriteLine("PDF example completed successfully");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Environment.Exit(-1);
}
}
}
}
|
7a05d2d1f6f866e5feed9cbae4c901155d184346
|
C#
|
darronfrancis/GoldBadgeChallenges
|
/GoldBadgeConsoleApplicationChallenges/ProgramUI.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KomodoCafe
{
class ProgramUI
{
private MenuRepository _menuList = new MenuRepository();
public void Run()
{
SeedList();
Menu();
}
private void Menu()
{
bool running = true;
while (running)
{
Console.Clear();
Console.WriteLine("Select a menu option:\n" +
"1. Add a Menu Item\n" +
"2. See All Menu Items\n" +
"3. Delete a Menu Item\n" +
"4. Quit");
int userInput = int.Parse(Console.ReadLine());
switch (userInput)
{
case 1:
AddMenuItem();
break;
case 2:
SeeAllMenuItems();
break;
case 3:
DeleteMenuItem();
break;
case 4:
running = false;
break;
default:
break;
}
}
}
private void AddMenuItem()
{
Console.Clear();
Menu newMenu = new Menu();
Console.WriteLine("Meal Number:");
newMenu.MealNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Meal Name:");
newMenu.MealName = Console.ReadLine();
Console.WriteLine("Meal Ingredients (separated by commas):");
string joined = string.Join(",", Console.ReadLine());
newMenu.MealIngredients = new List<string>() { joined };
Console.WriteLine("Meal Description:");
newMenu.MealDescription = Console.ReadLine();
Console.WriteLine("Meal Price:");
newMenu.MealPrice = decimal.Parse(Console.ReadLine());
_menuList.AddMenuItem(newMenu);
Console.WriteLine($"Menu item created.\n" +
$"Meal Number: {newMenu.MealNumber}\n" +
$"Meal Name: {newMenu.MealName}\n" +
$"Meal Ingredients: {joined}\n" +
$"Meal Description: {newMenu.MealDescription}\n" +
$"Meal Price: ${newMenu.MealPrice}\n" +
$"Press any key to continue.");
Console.ReadKey();
}
private void SeeAllMenuItems()
{
Console.Clear();
List<Menu> menuItem = _menuList.GetMenuItem();
foreach (Menu item in menuItem)
{
string joined = string.Join(",", item.MealIngredients);
Console.WriteLine($"\nMeal Number: {item.MealNumber}\n" +
$"Meal Name: {item.MealName}\n" +
$"Meal Ingredients: {joined}\n" +
$"Meal Description: {item.MealDescription}\n" +
$"Meal Price: ${item.MealPrice}\n");
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadLine();
}
private void DeleteMenuItem()
{
Console.Clear();
Menu food = new Menu();
List<Menu> menuItem = _menuList.GetMenuItem();
foreach (Menu item in menuItem)
{
Console.WriteLine($"{item.MealNumber} - Meal Name: {item.MealName}");
}
Console.WriteLine("\n" +
"What's the number of the meal you would like to remove?");
int choice = int.Parse(Console.ReadLine());
_menuList.DeleteMenuItem(choice);
}
private void SeedList()
{
Menu newMenuItem1 = new Menu(1, "Big Mac Combo Meal", new List<string>() { "Big Mac Bun, 100% Beef Patty, Shredded Lettuce, Big Mac Sauce, American Cheese, Pickle Slices" }, "The one and only McDonald’s Big Mac Combo Meal. Big Mac Ingredients include a classic sesame hamburger bun, Big Mac Sauce, American cheese and sliced pickles. The Big Mac Combo Meal is served with our World Famous Fries and your choice of an icy Coca-Cola fountain drink.", 6.99m);
Menu newMenuItem2 = new Menu(2, "Quarter Pounder with Cheese", new List<string>() { "Quarter Pound 100% Beef Patty, Quarter Pound Bun, Pasteurized Process American Cheese, Ketchup, Pickle Slices, Onions, Mustard" }, "TheEach Quarter Pounder with Cheese burger features a ¼ lb.* of 100% fresh beef that’s hot, deliciously juicy and cooked when you order. It’s seasoned with just a pinch of salt and pepper, sizzled on a flat iron grill, then topped with slivered onions, tangy pickles and two slices of melty cheese on a sesame seed bun. Our QPC contains no artificial flavors, preservatives or added colors from artificial sources. **Our pickle contains an artificial preservative, so skip it if you like.", 5.99m);
Menu newMenuItem3 = new Menu(3, "McDouble", new List<string>() { "100% Beef Patty, Regular Bun, Pasteurized Process American Cheese, Pickle Slices, Ketchup, Onions, Grill Seasoning" }, "A classic double burger from McDonald’s, the McDouble stacks two 100% pure beef patties seasoned with just a pinch of salt and pepper. It’s topped with tangy pickles, chopped onions, ketchup, mustard and a slice of melty American cheese. It contains no artificial flavors, preservatives or added colors from artificial sources.* Our pickle contains an artificial preservative, so skip it if you like.", 6.99m);
_menuList.AddMenuItem(newMenuItem1);
_menuList.AddMenuItem(newMenuItem2);
_menuList.AddMenuItem(newMenuItem3);
}
}
}
|
db67f4f1955e51930f80913b7619de8f3246da0c
|
C#
|
qria/GGJ2018
|
/Assets/Scripts/Wall.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using UnityEngine;
[RequireComponent(typeof(PolygonCollider2D))]
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
[ExecuteInEditMode]
public class Wall : MonoBehaviour {
/// <summary>
/// Converts Collider2D to Mesh
/// Source: https://answers.unity.com/questions/835675/how-to-fill-polygon-collider-with-a-solid-color.html
/// </summary>
PolygonCollider2D pc2 ;
public Vector2[] points
{
// returns all absolutes positions of points
get
{
return pc2.points.Select(point => point + (Vector2)transform.position).ToArray();
}
}
void Start () {
pc2 = gameObject.GetComponent<PolygonCollider2D>();
//Render thing
int pointCount = 0;
pointCount = pc2.GetTotalPointCount();
MeshFilter mf = GetComponent<MeshFilter>();
Mesh mesh = new Mesh();
Vector2[] points = pc2.points;
Vector3[] vertices = new Vector3[pointCount];
Vector2[] uv = new Vector2[pointCount];
for(int j=0; j<pointCount; j++){
Vector2 actual = points[j];
vertices[j] = new Vector3(actual.x, actual.y, 0);
uv[j] = actual;
}
Triangulator tr = new Triangulator(points);
int [] triangles = tr.Triangulate();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uv;
mf.mesh = mesh;
//Render thing
}
#if UNITY_EDITOR
void Update(){
if (Application.isPlaying)
return;
if(pc2 != null){
Start();
}
}
#endif
}
|