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
|
|---|---|---|---|---|---|---|
a7081ff279f5446088abdf6b4acc5c3b89ab21b7
|
C#
|
irah2008/Dynamics-365-Workflow-Tools
|
/msdyncrmWorkflowTools/msdyncrmWorkflowTools/Class/DateFunctions.cs
| 2.515625
| 3
|
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace msdyncrmWorkflowTools
{
public class DateFunctions : CodeActivity
{
#region "Parameter Definition"
[RequiredArgument]
[Input("Date 1")]
public InArgument<DateTime> Date1 { get; set; }
[Input("Date 2")]
public InArgument<DateTime> Date2 { get; set; }
[Output("Total Days")]
public OutArgument<double> TotalDays { get; set; }
[Output("Total Hours")]
public OutArgument<double> TotalHours { get; set; }
[Output("Total Milliseconds")]
public OutArgument<double> TotalMilliseconds { get; set; }
[Output("Total Minutes")]
public OutArgument<double> TotalMinutes { get; set; }
[Output("Total Seconds")]
public OutArgument<double> TotalSeconds { get; set; }
[Output("Day Of Week")]
public OutArgument<int> DayOfWeek { get; set; }
[Output("Day Of Year")]
public OutArgument<int> DayOfYear { get; set; }
[Output("Day")]
public OutArgument<int> Day { get; set; }
[Output("Month")]
public OutArgument<int> Month { get; set; }
[Output("Year")]
public OutArgument<int> Year { get; set; }
[Output("Week Of Year")]
public OutArgument<int> WeekOfYear { get; set; }
#endregion
protected override void Execute(CodeActivityContext executionContext)
{
#region "Load CRM Service from context"
Common objCommon = new Common(executionContext);
objCommon.tracingService.Trace("Load CRM Service from context --- OK");
#endregion
#region "Read Parameters"
DateTime date1 = this.Date1.Get(executionContext);
DateTime date2 = this.Date2.Get(executionContext);
#endregion
msdyncrmWorkflowTools_Class commonClass = new msdyncrmWorkflowTools_Class(objCommon.service, objCommon.tracingService);
TimeSpan difference = new TimeSpan();
int DayOfWeek = 0;
int DayOfYear = 0;
int Day = 0;
int Month = 0;
int Year = 0;
int WeekOfYear = 0;
commonClass.DateFunctions(date1, date2, ref difference,
ref DayOfWeek, ref DayOfYear, ref Day, ref Month, ref Year, ref WeekOfYear);
this.TotalDays.Set(executionContext, difference.TotalDays);
this.TotalHours.Set(executionContext, difference.TotalHours);
this.TotalMilliseconds.Set(executionContext, difference.TotalMilliseconds);
this.TotalMinutes.Set(executionContext, difference.TotalMinutes);
this.TotalSeconds.Set(executionContext, difference.TotalSeconds);
this.DayOfWeek.Set(executionContext, DayOfWeek);
this.DayOfYear.Set(executionContext, DayOfYear);
this.Day.Set(executionContext, Day);
this.Month.Set(executionContext, Month);
this.Year.Set(executionContext, Year);
this.WeekOfYear.Set(executionContext, WeekOfYear);
}
}
}
|
871bc748f5dfa89e0f46764464358951d5642dd4
|
C#
|
hvgmbdmg/LeetCodeSoluction
|
/CSharp/108. Convert Sorted Array to Binary Search Tree.cs
| 3.328125
| 3
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode SortedArrayToBST(int[] nums) {
return CreatBST( nums, nums.Length/2, 0, nums.Length-1);
}
private TreeNode CreatBST( int[] nums, int rootIndex, int start, int end ){
if( end < start )
return null;
TreeNode newNode = new TreeNode( nums[rootIndex] );
newNode.left = CreatBST( nums, (start+rootIndex-1)/2, start, rootIndex-1);
newNode.right = CreatBST( nums, (rootIndex+1+end)/2, rootIndex+1, end);
return newNode;
}
}
|
c4b9e5e1cb173a6109bce3fb37a109a38261fd7d
|
C#
|
Malsly/Supplement-to-the-system-of-books-for-the-library
|
/Library/DAL.Imp/Mappers/BookMapper.cs
| 2.84375
| 3
|
using DAL.Abs;
using DTObjects;
using Entities.Imp;
using System;
using System.Linq;
namespace DAL.Imp.Mappers
{
public class BookMapper : IMapper<Book, BookDTO>
{
public GenericRepository<Book> repo;
public BookMapper(GenericRepository<Book> repo)
{
this.repo = repo;
}
public Book DeMap(BookDTO dto)
{
Book book = repo.GetByID(dto.PrintedEditionOrderID);
if (book == null)
{
return EntityDTOConverter.BookDTOtoBook(dto);
}
book.PrintedEditionOrderID = dto.PrintedEditionOrderID;
book.Name = dto.Name;
book.Rate = dto.Rate;
book.Authors = dto.Authors.Select(author => EntityDTOConverter.AuthorDTOtoAuthor(author)).ToList();
return book;
}
public BookDTO Map(Book entity)
{
return EntityDTOConverter.BooktoBookDTO(entity);
}
}
}
|
b22971b94a084d1247197addab49b75913ea3578
|
C#
|
desolangel/code-test
|
/src/Shortenurl.Model/SqlDataAccess.cs
| 2.90625
| 3
|
using Microsoft.Extensions.Options;
using shortenurl.model.Interfaces;
using shortenurl.model.Settings;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace shortenurl.model
{
public class SqlDataAccess : ISqlDataAccess
{
private readonly ConnectionStrings _connString;
public SqlDataAccess(IOptions<ConnectionStrings> connStrings)
{
_connString = connStrings.Value;
var conn = _connString.DefaultConnection;
if (string.IsNullOrEmpty(conn))
throw new Exception("The connection string is empty. " +
"Please add an entry in the settings.json file with the key 'DefaultConnection' containing the connection string. " +
"Or set the connection string on 'connectionKey' parameter");
}
private async Task<SqlConnection> NewConnection()
{
var conn = new SqlConnection(_connString.DefaultConnection);
await conn.OpenAsync();
return conn;
}
private void SetParams(SqlCommand cmd, Dictionary<string, object> listParams)
{
foreach (var param in listParams)
{
cmd.Parameters.Add(new SqlParameter(param.Key, param.Value));
}
}
private T DataReaderMapToObject<T>(IDataReader dr)
{
T obj = default(T);
var columNames = new List<string>();
for (int i = 0; i < dr.FieldCount; i++)
{
columNames.Add(dr.GetName(i));
}
if (dr.Read())
{
obj = Activator.CreateInstance<T>();
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
if (columNames.Contains(prop.Name) && !object.Equals(dr[prop.Name], DBNull.Value))
{
prop.SetValue(obj, dr[prop.Name], null);
}
}
}
return obj;
}
public async Task Execute(string procedureName, Dictionary<string, object> listParams)
{
using (var conn = await NewConnection())
{
using (var cmd = new SqlCommand(procedureName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
SetParams(cmd, listParams);
await cmd.ExecuteNonQueryAsync();
}
}
}
public async Task<T> GetOne<T>(string procedureName, Dictionary<string, object> listParams)
{
T mappedObj;
using (var conn = await NewConnection())
{
using (var cmd = new SqlCommand(procedureName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SetParams(cmd, listParams);
var reader = cmd.ExecuteReader();
mappedObj = DataReaderMapToObject<T>(reader);
}
}
return mappedObj;
}
}
}
|
2bc3b0eb11aaaea71d4eab9a5d67c6a98f3853ba
|
C#
|
MarianBecher/Blobed
|
/Assets/Scripts/Level/Trigger.cs
| 2.5625
| 3
|
using UnityEngine;
using UnityEngine.Events;
using System.Collections.Generic;
using System;
public abstract class Trigger : TilePrefab {
public List<Triggerable> targets;
public override void configure(TileSettings settings, LevelLoader loader)
{
foreach(int targetID in settings.triggerTargets)
{
Debug.Log(targetID);
TilePrefab target = loader.getTileInstance(targetID);
Debug.Log(target);
Debug.Log(target.GetType());
if (typeof(Triggerable).IsAssignableFrom(target.GetType()))
targets.Add((Triggerable) target);
}
}
protected void informTargets()
{
foreach(Triggerable t in targets)
t.performTriggerEvent(this);
}
}
|
4786bb87d23859b7d3d5e257490efa4ca57f8fa0
|
C#
|
ChrisDoerr/CustomTitleBarWindow
|
/CustomWindow/MainWindow.xaml.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace CustomWindow
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private double _currentWindowTop = 0f;
private double _currentWindowLeft = 0f;
private double _currentWindowWidth = 0f;
private double _currentWindowHeight = 0f;
private string _currentWindowState = "Normal";
private double _screenWidth = 0f;
private double _screenHeight = 0f;
private double _fullScreenWidth = 0f;
private double _fullScreenHeight = 0f;
/**
* The whole point of "overriding" the standard window TitleBar is
* so you can style it in a way that fits into your application theme.
*
* The downside is, of course, that will have to implement the functionality again and on your own!
*/
public MainWindow()
{
InitializeComponent();
_currentWindowWidth = Application.Current.MainWindow.Width;
_currentWindowHeight = Application.Current.MainWindow.Height;
_screenWidth = SystemParameters.FullPrimaryScreenWidth; // Not sure why, but MaximizedPrimaryScreenWidth seems slightly bigger than my actual resolution?!
_screenHeight = SystemParameters.MaximizedPrimaryScreenHeight; // ...whereas the *Height value seems right (resoltuion/height - taskbar/height)
_fullScreenWidth = SystemParameters.VirtualScreenWidth;
_fullScreenHeight = SystemParameters.VirtualScreenHeight;
// Update these values when the window is being moved or resized manually
_currentWindowTop = ((_fullScreenHeight - _currentWindowHeight) / 2);
_currentWindowLeft = ((_fullScreenWidth - _currentWindowWidth) / 2);
/**
* 🗕 Minimize
* 🗗 Restore Down
* 🗖 Maximize
* 🗙 Close
*/
}
private void HandleClick_BtnMinimze(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void HandleClick_BtnMaximize(object sender, RoutedEventArgs e)
{
_currentWindowState = ( _currentWindowState == "Normal" ? "Maximized" : "Normal" );
if( _currentWindowState == "Normal" )
{
Application.Current.MainWindow.Top = _currentWindowTop;
Application.Current.MainWindow.Left = _currentWindowLeft;
Application.Current.MainWindow.Width = _currentWindowWidth;
Application.Current.MainWindow.Height = _currentWindowHeight;
}
else if( _currentWindowState == "Maximized" )
{
Application.Current.MainWindow.Top = 0;
Application.Current.MainWindow.Left = 0;
Application.Current.MainWindow.Width = _screenWidth;
Application.Current.MainWindow.Height = _screenHeight;
}
}
private void HandleClick_BtnClose( object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
// @todo How do you trigger this??
private void OnApplicationExit( object sender, EventArgs e )
{
// This still allows you to propertly shut down your own processes.
MessageBox.Show("Goodbye");
}
}
}
|
f2e22f47324320f9cbc069ffdf9596fecdf805d2
|
C#
|
danehoff/cowboy-cafe
|
/PointOfSale/CoinControl.xaml.cs
| 2.6875
| 3
|
/*
* Author: Dane Hoffman
* Edited by: (If you are not the original author like the CowpokeChili class)
* Class name: Coin Control
* Purpose: Has all the controls for the coins.
*/
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 CashRegister;
namespace PointOfSale
{
/// <summary>
/// Interaction logic for CoinControl.xaml
/// </summary>
public partial class CoinControl : UserControl
{
/// <summary>
/// Making a denomination Property
/// </summary>
public static readonly DependencyProperty DenominationProperty =
DependencyProperty.Register(
"Denomination",
typeof(Coins),
typeof(CoinControl),
new PropertyMetadata(Coins.Penny)
);
/// <summary>
/// Coin Denomination
/// </summary>
public Coins Denomination
{
get
{
return (Coins)GetValue(DenominationProperty);
}
set
{
SetValue(DenominationProperty, value);
}
}
/// <summary>
/// Making of quantity property
/// </summary>
public static readonly DependencyProperty QuantityProperty =
DependencyProperty.Register(
"Quantity",
typeof(int),
typeof(CoinControl),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);
/// <summary>
/// Quantity of coins
/// </summary>
public int Quantity
{
get => (int)GetValue(QuantityProperty);
set => SetValue(QuantityProperty, value);
}
/// <summary>
/// Constructor
/// </summary>
public CoinControl()
{
InitializeComponent();
}
/// <summary>
/// Increases the number of coin
/// </summary>
public void OnIncreaseClicked(object sender, RoutedEventArgs e)
{
Quantity++;
}
/// <summary>
/// Decreases the number of coin
/// </summary>
public void OnDecreaseClicked(object sender, RoutedEventArgs e)
{
Quantity--;
}
}
}
|
3a0dc826d34add4235b43d133c7108037ca2085f
|
C#
|
AlexBrad1ey/CoBuilderSDK
|
/CoBuilder.Interfaces/Infrastructure/Config/PropertySetDefinition.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using CoBuilder.Service.Helpers;
using CoBuilder.Service.Interfaces;
namespace CoBuilder.Service.Infrastructure.Config
{
public class PropertySetDefinition : Definition, IPropertySetDefinition
{
public PropertySetDefinition() : base(DefinitionType.PropertySet)
{
Properties = new Dictionary<string, PropertyDefinition>();
}
public IDictionary<string, PropertyDefinition> Properties { get; }
public string PSetId { get; set; }
public IPropertyDefinition AddProperty(IPropertyDefinition property)
{
if (property == null) throw new ArgumentNullException(nameof(property));
var key = property.Identifier;
if (Properties.ContainsKey(key)) throw new ArgumentException("Property Definition with the Same Key Identifier already Present", nameof(property));
Properties.Add(key, (PropertyDefinition) property);
return property;
}
public bool RemoveProperty(IPropertyDefinition property)
{
if (property == null) throw new ArgumentNullException(nameof(property));
var key = property.Identifier;
return Properties.Remove(key);
}
public IPropertyDefinition GetPropertyByName(string name)
{
return Properties.FirstOrDefault(k => k.Value.DisplayName == name).Value;
}
public IPropertyDefinition GetPropertyByIdentifier(string identifier)
{
return Properties.FirstOrDefault(k => k.Value.Identifier == identifier).Value;
}
public bool HasProperty(PropertyDefinition definition)
{
return definition != null && Properties.ContainsKey(definition.Identifier);
}
}
}
|
2bca14e8dfaf805f9ae6699bbb2d41b33ecf8498
|
C#
|
emilia98/SoftwareUniversity
|
/Programming Basics/Programming Basics - C#/Exercises/06. Drawing with Loops/06. Drawing with Loops/RhombusOfStars/RhombusOfStars.cs
| 3.84375
| 4
|
using System;
namespace RhombusOfStars
{
class RhombusOfStars
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int intervals;
int stars;
if (n == 1)
{
Console.WriteLine("*");
}
else
{
//This code is for the top part
for (int i = 1; i <= n; i++)
{
intervals = n - i;
stars = i;
for (int j = 1; j <= intervals; j++)
{
Console.Write(" ");
}
for (int m = 1; m <= stars; m++)
{
Console.Write("* ");
}
Console.WriteLine();
}
//This code is for the bottom part
for (int i = n - 1; i >= 1; i--)
{
intervals = n - i;
stars = i;
for (int j = 1; j <= intervals; j++)
{
Console.Write(" ");
}
for (int m = 1; m <= stars; m++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
}
}
|
b44a42f6da9dd7646981fbf8ef73458d7f99634e
|
C#
|
solarwinds/OrionSDK
|
/Src/SwqlStudio/ObjectExplorer/DocumentationBuilder.cs
| 2.65625
| 3
|
using System;
using System.Text;
using System.Windows.Forms;
using SwqlStudio.Metadata;
namespace SwqlStudio
{
internal class DocumentationBuilder
{
public static Documentation Build(TreeNode node)
{
var data = node.Tag;
var connectedNode = node as TreeNodeWithConnectionInfo;
var provider = connectedNode?.Provider;
if (provider == null)
return Documentation.Empty;
if (data is SwisMetaDataProvider)
return ProviderDocumentation(provider);
if (data is string nameSpace)
return NamespaceDocumentation(nameSpace, node.Nodes.Count);
if (data is Entity entity)
return EntityDocumentation(provider, entity);
if (data is Property property)
return PropertyDocumentation(property);
if (data is Verb verb)
return VerbDocumentation(verb);
if (data is VerbArgument verbArg)
return VerbArgumentDocumentation(verbArg);
return Documentation.Empty;
}
private static Documentation VerbArgumentDocumentation(VerbArgument verbArg)
{
var docs = MetadataDocumentation(verbArg);
return new Documentation("Verb argument", docs);
}
private static Documentation VerbDocumentation(Verb verb)
{
var builder = new StringBuilder();
builder.AppendName(verb.Name);
builder.AppendObsoleteSection(verb);
builder.AppendSummaryParagraph(verb.Summary);
var docs = builder.ToString();
return new Documentation("Verb", docs);
}
private static Documentation EntityDocumentation(IMetadataProvider provider, Entity entity)
{
var builder = new StringBuilder();
builder.AppendName(entity.FullName);
builder.Append($"Base type: {entity.BaseType}\r\n");
builder.AppendAccessControl(provider.ConnectionInfo, entity);
builder.AppendObsoleteSection(entity);
builder.AppendSummaryParagraph(entity.Summary);
var docs = builder.ToString();
return new Documentation("Entity", docs);
}
private static Documentation NamespaceDocumentation(string nameSpace, int childrenCount)
{
var builder = new StringBuilder();
builder.AppendName(nameSpace);
var children = ChildrenText(childrenCount);
builder.Append(children);
var docs = builder.ToString();
return new Documentation("Namespace", docs);
}
private static Documentation PropertyDocumentation(Property property)
{
var builder = new StringBuilder();
builder.Append(MetadataDocumentation(property));
builder.AppendObsoleteSection(property);
return new Documentation("Property", builder.ToString());
}
private static Documentation ProviderDocumentation(IMetadataProvider provider)
{
var documents = $@"Connection: {provider.Name}";
return new Documentation("Database", documents);
}
private static string MetadataDocumentation(ITypedMetadata metadata)
{
var builder = new StringBuilder();
builder.AppendName(metadata.Name);
builder.AppendType(metadata.Type);
builder.AppendSummaryParagraph(metadata.Summary);
return builder.ToString();
}
public static string ToToolTip(ITypedMetadata metadata)
{
var builder = new StringBuilder();
builder.AppendSummary(metadata.Summary);
return builder.ToString();
}
public static string ToToolTip(ITypedMetadata metadata, IObsoleteMetadata obsoleteMetadata)
{
var builder = new StringBuilder();
builder.AppendSummary(metadata.Summary);
builder.AppendObsoleteSection(obsoleteMetadata);
return builder.ToString();
}
public static string ToToolTip(ConnectionInfo connection, Entity entity)
{
var builder = new StringBuilder();
builder.AppendSummary(entity.Summary);
builder.AppendObsoleteSection(entity);
return builder.ToString();
}
public static string ToToolTip(Verb verb)
{
var builder = new StringBuilder();
builder.AppendSummary(verb.Summary);
builder.AppendObsoleteSection(verb);
return builder.ToString();
}
public static string ToNodeText(string name, int childrenCount)
{
var children = ChildrenText(childrenCount);
return $"{name} ({children})";
}
private static string ChildrenText(int childrenCount)
{
var countSuffix = childrenCount > 1 ? "s" : string.Empty;
return $"{childrenCount} item{countSuffix}";
}
public static string ToNodeText(ITypedMetadata metadata)
{
return $"{metadata.Name} ({metadata.Type})";
}
public static string ToBaseNodeText(TreeNode baseNode, int childrenCount)
{
var entitiesSuffix = childrenCount > 1 ? "ies" : "y";
return $"{baseNode.Text} ({childrenCount} derived entit{entitiesSuffix})";
}
}
}
|
6ce2856d039580aea006a3c446f64407f71eca37
|
C#
|
tonto7973/xim
|
/src/Xim.Simulators.Api/Body(TObject).cs
| 2.546875
| 3
|
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.AspNetCore.Http;
using Xim.Simulators.Api.Internal;
namespace Xim.Simulators.Api
{
/// <summary>
/// Represents a generic HTTP response body.
/// </summary>
/// <typeparam name="TObject">The type of the body content.</typeparam>
public sealed class Body<TObject> : Body
{
private const string JsonEncoding = "application/json";
private const string XmlEncoding = "application/xml";
private const string AlternateXmlEncoding = "text/xml";
private const string BinaryEncoding = "application/octet-stream";
private readonly Encoding _encoding;
/// <summary>
/// Gets the body content.
/// </summary>
public new TObject Content => (TObject)base.Content;
internal Body(TObject content, string contentType, long? contentLength)
: base(content, contentType, contentLength) { }
internal Body(TObject content, Encoding encoding)
: base(content, null, null)
{
_encoding = encoding;
}
/// <summary>
/// Deserializes object from request <see cref="Body"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <param name="context">The <see cref="HttpContext"/>.</param>
/// <param name="settings">The <see cref="ApiSimulatorSettings"/>.</param>
/// <returns>A task that represents the asynchronous read operation.</returns>
protected override Task<T> ReadAsync<T>(HttpContext context, ApiSimulatorSettings settings)
=> ReadStreamAsync<T>(context.Request.Body, context.Request, settings);
/// <summary>
/// Writes the body to the response stream.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/>.</param>
/// <param name="settings">The <see cref="ApiSimulatorSettings"/>.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
protected override Task WriteAsync(HttpContext context, ApiSimulatorSettings settings)
=> Content is Stream stream
? WriteStreamAsync(stream, context.Response)
: WriteContentAsync(context, settings);
private Task WriteStreamAsync(Stream stream, HttpResponse response)
{
response.ContentType = ContentType ?? BinaryEncoding;
response.ContentLength = ContentLength ?? response.ContentLength;
return CopyBytesAsync(stream, response.Body, response.ContentLength);
}
private Task WriteContentAsync(HttpContext context, ApiSimulatorSettings settings)
{
ILookup<string, bool> accepts = ((string)context.Request.Headers["Accept"] ?? "")
.Split(',')
.Where(accept => !string.IsNullOrWhiteSpace(accept))
.Select(accept => accept.Split(';')[0].Trim())
.Distinct()
.ToLookup(key => key, _ => true, StringComparer.InvariantCultureIgnoreCase);
var acceptsAny = accepts["*/*"].Any();
var acceptsJson = acceptsAny || accepts[JsonEncoding].Any();
var acceptsTextXml = accepts[AlternateXmlEncoding].Any();
var acceptsXml = acceptsAny || accepts[XmlEncoding].Any() || acceptsTextXml;
byte[] data;
string contentType;
Encoding charset;
if (settings.XmlSettings != null && ((acceptsXml && !acceptsJson) || settings.JsonSettings == null))
{
XmlWriterSettings xmlSettings = settings.XmlSettings;
contentType = !acceptsTextXml ? XmlEncoding : AlternateXmlEncoding;
charset = _encoding ?? xmlSettings.Encoding ?? Encoding.UTF8;
data = SerializeXml(Content, xmlSettings, charset);
}
else if (settings.JsonSettings != null)
{
JsonSerializerOptions jsonSettings = settings.JsonSettings;
contentType = JsonEncoding;
charset = _encoding ?? Encoding.UTF8;
data = SerializeJson(Content, jsonSettings, charset);
}
else
{
throw new FormatException(SR.Format(SR.ApiResponseNotFormatted));
}
context.SetApiSimulatorBodyEncoding(charset);
context.Response.ContentType = contentType + "; charset=" + charset.HeaderName;
context.Response.ContentLength = data.Length;
return context.Response.Body.WriteAsync(data, 0, data.Length);
}
private static byte[] SerializeJson<T>(T value, JsonSerializerOptions options, Encoding encoding)
=> encoding == null || encoding == Encoding.UTF8
? JsonSerializer.SerializeToUtf8Bytes(value, typeof(T), options)
: encoding.GetBytes(JsonSerializer.Serialize(value, typeof(T), options));
private static byte[] SerializeXml<T>(T value, XmlWriterSettings xmlSettings, Encoding encoding)
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream, encoding))
using (var xmlWriter = XmlWriter.Create(streamWriter, xmlSettings))
{
var xmlSerializer = new XmlSerializer(typeof(T));
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(xmlWriter, value, namespaces);
return memoryStream.ToArray();
}
}
private static async Task<T> ReadStreamAsync<T>(Stream body, HttpRequest request, ApiSimulatorSettings settings)
{
if (request.GetMediaType() == JsonEncoding)
{
using (var ms = new MemoryStream())
{
await CopyBytesAsync(body, ms, request.ContentLength).ConfigureAwait(false);
ms.Position = 0;
Encoding charset = request.HttpContext.GetApiSimulatorBodyEncoding() ?? request.GetCharset();
return await DeserializeJsonAsync<T>(ms, settings.JsonSettings, charset).ConfigureAwait(false);
}
}
else if (new[] { XmlEncoding, AlternateXmlEncoding }.Contains(request.GetMediaType()))
{
using (var ms = new MemoryStream())
{
await CopyBytesAsync(body, ms, request.ContentLength).ConfigureAwait(false);
ms.Position = 0;
Encoding charset = request.HttpContext.GetApiSimulatorBodyEncoding() ?? request.GetCharset() ?? Encoding.UTF8;
return DeserializeXml<T>(ms, new XmlReaderSettings(), charset);
}
}
else
{
throw new NotSupportedException(SR.Format(SR.ApiRequestFormatNotSupported, request.ContentType));
}
}
private static ValueTask<T> DeserializeJsonAsync<T>(Stream data, JsonSerializerOptions options, Encoding encoding)
{
if (encoding == null || encoding == Encoding.UTF8)
{
return JsonSerializer
.DeserializeAsync<T>(data, options);
}
else
{
using (var streamReader = new StreamReader(data, encoding))
{
var json = streamReader.ReadToEnd();
T result = JsonSerializer.Deserialize<T>(json, options);
return new ValueTask<T>(result);
}
}
}
private static T DeserializeXml<T>(Stream data, XmlReaderSettings xmlSettings, Encoding encoding)
{
var xmlSerializer = new XmlSerializer(typeof(T));
using (var streamReader = new StreamReader(data, encoding ?? Encoding.UTF8))
using (var xmlReader = XmlReader.Create(streamReader, xmlSettings))
{
return (T)xmlSerializer.Deserialize(xmlReader);
}
}
}
}
|
d48de0fb918d2e1e179a80844c127bb69ad8db6d
|
C#
|
wilbennett/Wil.Library
|
/Wil.Reactive/ObservableEx.Stale.cs
| 2.515625
| 3
|
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Wil.Core.Interfaces;
using Wil.Reactive.Interfaces;
namespace Wil.Reactive
{
public static partial class ObservableEx
{
public static IObservable<Stale<T>> DetectStale<T>(this IObservable<T> source, Duration period, IScheduler scheduler = null)
{
return Observable.Create<Stale<T>>(o =>
{
scheduler = scheduler ?? Scheduler.Default;
source = source.Publish().RefCount();
var complete = new Subject<Unit>();
IDisposable sourceSub = source.Subscribe(_ => { }, o.OnError, () => complete.OnNext(Unit.Default));
IDisposable sub = source
.StartWith(default(T))
.Throttle(period, scheduler)
.TakeUntil(complete)
.Select(_ => Stale<T>.Empty)
.Subscribe(o);
return new CompositeDisposable(sub, sourceSub, complete);
});
}
public static IObservable<Stale<T>> DetectStaleScan<T>(this IObservable<T> source, Duration period, IScheduler scheduler = null)
{
return Observable.Create<Stale<T>>(o =>
{
scheduler = scheduler ?? Scheduler.Default;
source = source.Publish().RefCount();
var complete = new Subject<Unit>();
IDisposable sourceSub = source.Subscribe(_ => { }, o.OnError, () => complete.OnNext(Unit.Default));
IObservable<Stale<T>> sourceStale = source.Select(x => new Stale<T>(x));
IObservable<Stale<T>> stale = source
.StartWith(default(T))
.Throttle(period, scheduler)
.TakeUntil(complete)
.Select(_ => Stale<T>.Empty);
IDisposable sub = sourceStale.Merge(stale, scheduler).Subscribe(o);
return new CompositeDisposable(sub, sourceSub, complete);
});
}
public static IObservable<StaleGroup<TGroup, TValue>> DetectStaleGroup<TGroup, TValue>(
this IObservable<TValue> source, Func<TValue, TGroup> keySelector, Duration period, IScheduler scheduler = null)
{
return Observable.Create<StaleGroup<TGroup, TValue>>(o =>
{
scheduler = scheduler ?? Scheduler.Default;
source = source.Publish().RefCount();
var complete = new Subject<Unit>();
IDisposable sourceSub = source.Subscribe(_ => { }, o.OnError, () => complete.OnNext(Unit.Default));
IDisposable sub = source
.GroupByUntil(keySelector, grp => grp.Throttle(period, scheduler))
.SelectMany(grp => grp.TakeLast(1, scheduler).TakeUntil(complete).Select(x => new StaleGroup<TGroup, TValue>(grp.Key)))
.Subscribe(o);
return new CompositeDisposable(sub, sourceSub, complete);
});
}
public static IObservable<StaleGroup<TGroup, TValue>> DetectStaleGroupScan<TGroup, TValue>(
this IObservable<TValue> source, Func<TValue, TGroup> keySelector, Duration period, IScheduler scheduler = null)
{
return Observable.Create<StaleGroup<TGroup, TValue>>(o =>
{
scheduler = scheduler ?? Scheduler.Default;
source = source.Publish().RefCount();
var complete = new Subject<Unit>();
IDisposable sourceSub = source.Subscribe(_ => { }, o.OnError, () => complete.OnNext(Unit.Default));
IObservable<StaleGroup<TGroup, TValue>> timeout = source
.GroupByUntil(keySelector, grp => grp.Throttle(period, scheduler))
.SelectMany(grp => grp.TakeLast(1, scheduler).TakeUntil(complete).Select(x => new StaleGroup<TGroup, TValue>(grp.Key)));
IObservable<StaleGroup<TGroup, TValue>> data = source.Select(x => new StaleGroup<TGroup, TValue>(keySelector(x), x));
IDisposable sub = data.Merge(timeout, scheduler).Subscribe(o);
return new CompositeDisposable(sub, sourceSub, complete);
});
}
}
}
|
6142b10f525233f31ce9533964f40ace74caefb7
|
C#
|
Veivan/MorphApp
|
/AsmApp/Types/LexemaAsm.cs
| 2.6875
| 3
|
using System;
using Schemas;
using Schemas.BlockPlatform;
namespace AsmApp.Types
{
/// <summary>
/// Класс хранит одну лемму :
/// обозначение части речи и значение.
/// </summary>
public class LexemaAsm : AssemblyBase
{
#region Privates
private AssemblyBase srcAsm; // Сборка, из которой был сформирован объект
private int grenPart;
private string lemma;
#endregion
#region Constructors
/// <summary>
/// Конструктор объекта из данных БД.
/// </summary>
public LexemaAsm(AssemblyBase srcAsm) : base(srcAsm)
{
this.srcAsm = srcAsm;
this.grenPart = Convert.ToInt32(srcAsm.GetValue("GrenPart"));
this.lemma = (string)srcAsm.GetValue("Lemma");
}
/// <summary>
/// Конструктор нового объекта.
/// </summary>
/// <param name="_grenPart">ID части речи (значение константы GrenPart из ConstantEnums)</param>
/// <param name="_lemma">Лемма (в нижнем регистре)</param>
/// <returns></returns>
public LexemaAsm(int _grenPart, string _lemma) : base(Session.Instance().GetBlockTypeByNameKey(Session.lexTypeName))
{
grenPart = _grenPart;
lemma = _lemma;
}
#endregion
#region Properties
/// <summary>
/// Идентификатор части речи - знчение члена перечисления Schemas.GrenPart.
/// </summary>
public int GrenPart
{
get
{
return grenPart;
}
}
/// <summary>
/// Лемма.
/// </summary>
public string Lemma
{
get
{
return lemma;
}
}
#endregion
#region Methods
public override void Save()
{
var store = Session.Instance().Store;
srcAsm = store.GetLexema(grenPart, lemma, true);
this.BlockID = srcAsm.BlockID;
this.ParentID = srcAsm.ParentID;
this.FactID = srcAsm.FactID;
}
#endregion
}
}
|
ccdc52d6835abbeb24cc3dcea886c7243be16c93
|
C#
|
shendongnian/download4
|
/latest_version_download2/3030-351799-140124583-2.cs
| 2.96875
| 3
|
public static void InsertAfter(this DataColumnCollection columns,
DataColumn currentColumn, DataColumn newColumn)
{
if (!columns.Contains(currentColumn.ColumnName))
throw new ArgumentException(/** snip **/);
columns.Add(newColumn);
//add the new column after the current one
columns[newColumn.ColumnName].SetOrdinal(currentColumn.Ordinal + 1);
}
|
161fd785ee21b6344e9b1f9952b7b6455d0be07a
|
C#
|
aliardan/Bars
|
/QuickSort/QuickSort/Program.cs
| 3.265625
| 3
|
using System;
using System.Linq;
using Microsoft.FSharp.Collections;
using QuickSortFSharpLib;
namespace QuickSort
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите элементы массива через пробел и нажмите Enter");
var inString = Console.ReadLine();
var splittedInString = inString.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var intArray = splittedInString.Select(x => Int32.Parse(x));
var fSharpIntArray = ListModule.OfSeq(intArray);
var sortedArray = QuickSortFSharpLib.QuickSort.Qsort(fSharpIntArray).ToArray();
var joinedString = String.Join(' ', sortedArray);
Console.WriteLine(joinedString);
Console.ReadKey();
}
}
}
|
a2cb7e1546b332d633cb3d69fe38fa36e4ea16e9
|
C#
|
Xnco/Data-Structures-and-Algorithms
|
/TitleProject/0226_翻转二叉树.cs
| 3.484375
| 3
|
using System;
public class Class1
{
public Class1()
{
}
#region 226_翻转二叉树
/*
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
备注:
这个问题是受到 Max Howell 的 原问题 启发的 :
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
*/
// 152ms, 9.1MB
static TreeNode InvertTree(TreeNode root)
{
if (root == null)
{
return null;
}
Swap(root);
InvertTree(root.left);
InvertTree(root.right);
return root;
}
static void Swap(TreeNode root)
{
TreeNode node = root.left;
root.left = root.right;
root.right = node;
}
//Definition for a binary tree node.
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
#endregion
}
|
eb6064bcd1e363a6e8196ae8121c617d1f955463
|
C#
|
michael-kokorin/dsl-engine
|
/Src/Common/Common/Extensions/StringExtensions.cs
| 3.34375
| 3
|
namespace Common.Extensions
{
using System;
using System.Globalization;
using System.IO;
using System.Text;
using JetBrains.Annotations;
/// <summary>
/// Provides extension methods for strings.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Checks whether two string are equal ignore case.
/// </summary>
/// <param name="first">The first.</param>
/// <param name="second">The second.</param>
/// <returns><see langword="true"/> if strings are equal; otherwise, <see langword="false"/>.</returns>
public static bool EqualIgnoreCase(this string first, string second)
=> string.Equals(first, second, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Formats string with the specified arguments.
/// </summary>
/// <param name="template">The format.</param>
/// <param name="args">The arguments.</param>
/// <returns>Formatted string.</returns>
public static string FormatWith(this string template, params object[] args)
=> string.Format(CultureInfo.InvariantCulture, template, args);
/// <summary>
/// Replaces the first occurence of <paramref name="placeholder"/> by <paramref name="replacement"/>.
/// </summary>
/// <param name="template">The template.</param>
/// <param name="placeholder">The placeholder.</param>
/// <param name="replacement">The replacement.</param>
/// <returns>String with replacement.</returns>
public static string ReplaceOnce([NotNull] this string template, string placeholder, string replacement)
{
if (string.IsNullOrEmpty(placeholder))
return template;
var num = template.IndexOf(placeholder, StringComparison.Ordinal);
if (num < 0)
return template;
return
new StringBuilder(template.Substring(0, num))
.Append(replacement)
.Append(template.Substring(num + placeholder.Length))
.ToString();
}
/// <summary>
/// update string to the valid path
/// </summary>
/// <param name="source">The source string.</param>
/// <returns>Path string</returns>
public static string ToValidPath([NotNull] this string source)
{
var invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(Path.GetInvalidFileNameChars()));
var invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars);
return System.Text.RegularExpressions.Regex.Replace(source, invalidRegStr, "_");
}
}
}
|
0bc91d40a12a720126c8cb27327cc55e60970063
|
C#
|
montegava/rental
|
/Rental/src/Common.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using RentalCommon;
using System.Reflection;
namespace Rental
{
class Common
{
/// <summary>
/// Saves an image as a jpeg image, with the given quality
/// </summary>
/// <param name="path">Path to which the image would be saved.</param>
// <param name="quality">An integer from 0 to 100, with 100 being the
/// highest quality</param>
public static string SaveJpeg(Image img, int quality)
{
var maxW = 500;
var maxH = 500;
double mul1 = (double)maxW / img.Width;
double mul2 = (double)maxH / img.Height;
double mul = Math.Max(mul1, mul2); // mul1 >= mul2 ? mul1 : mul2;
var newWidth = (int)(img.Width * mul);
var newHeight = (int)(img.Height * mul);
if (quality < 0 || quality > 100)
throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
// Encoder parameter for image quality
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
// Jpeg image codec
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.Default;
gr.InterpolationMode = InterpolationMode.Default;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(img, new Rectangle(0, 0, newWidth, newHeight));
}
var RepositoryDirectory = @"Media";
string fileName = Guid.NewGuid() + ".jpg";
//String.Format("{0}_{1}\\{2}", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString(), fileName)
string filePath = Path.Combine(RepositoryDirectory, fileName);
string dir = Path.GetDirectoryName(filePath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
newImage.Save(filePath, jpegCodec, encoderParams);
return fileName;
}
/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
public static double DoubleCut(double val)
{
double valr = Math.Round(val, 2);
if (valr > val)
valr += -0.01;
return valr;
}
public static string GetMd5Hash(string input)
{
if (input != null)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("X2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
return null;
}
public static void DoubleAllow(object sender, KeyPressEventArgs e)
{
double res;
if (char.IsLetter(e.KeyChar) ||
char.IsSymbol(e.KeyChar) ||
char.IsWhiteSpace(e.KeyChar) || (e.KeyChar != '\b' &&
!Double.TryParse((sender as TextBox).Text + e.KeyChar, out res)))
e.Handled = true;
}
public static void DigitalAllow(object sender, KeyPressEventArgs e)
{
if (char.IsLetter(e.KeyChar) ||
char.IsSymbol(e.KeyChar) ||
char.IsWhiteSpace(e.KeyChar) ||
char.IsPunctuation(e.KeyChar))
e.Handled = true;
}
public static void SetAutoComplete(ComboBox combo)
{
if (combo != null)
{
combo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
combo.AutoCompleteSource = AutoCompleteSource.ListItems;
}
}
public static void SetAutoComplete(TextBox combo)
{
if (combo != null)
{
combo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
combo.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}
public static void FillComboBox(ComboBox combo, IList dataSource, string displayMember, string valueMember, bool addEmty = false)
{
if (combo != null)
{
combo.DropDownStyle = ComboBoxStyle.DropDownList;
if (dataSource != null && dataSource.Count > 0)
{
if (addEmty)
{
Type t = dataSource[0].GetType();
var obj = Activator.CreateInstance(t);
t.GetProperty("name").SetValue(obj, "-неизевестно-", null);
t.GetProperty("id").SetValue(obj, -1, null);
dataSource.Insert(0, obj);
}
combo.DataSource = dataSource;
combo.DisplayMember = displayMember;
combo.ValueMember = valueMember;
}
}
}
public static void SetGridStyle(DataGridView grid)
{
if (grid != null)
{
grid.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point);
grid.ColumnHeadersDefaultCellStyle.BackColor = SystemColors.ControlDark;
grid.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
grid.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
grid.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
grid.DefaultCellStyle.BackColor = Color.Empty;
grid.AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
grid.CellBorderStyle = DataGridViewCellBorderStyle.Single;
grid.GridColor = SystemColors.ControlDarkDark;
}
}
public static void SetColumlOption(DataGridView grid, Fields field, int width, ref int displayIndex, bool visible = true)
{
SetColumlOption(grid, field.ToString(), Convetor.FieldToString(field), width, ref displayIndex, visible);
}
public static void SetColumlOption(DataGridView grid, string columnName, string headerText, int width, ref int displayIndex, bool visible = true)
{
if (grid.Columns[columnName] == null)
grid.Columns.Add(columnName, columnName);
grid.Columns[columnName].Visible = visible;
grid.Columns[columnName].DisplayIndex = displayIndex;
grid.Columns[columnName].Width = width;
grid.Columns[columnName].HeaderText = headerText;
displayIndex++;
grid.Columns[columnName].SortMode = DataGridViewColumnSortMode.Programmatic;
}
}
}
|
074b79befcf2c4374989f860cc3732cdbf622494
|
C#
|
Nethereum/Nethereum
|
/generators/Nethereum.Generators/ABI/GeneratorModel/ParameterABIModel.cs
| 2.5625
| 3
|
using System.Collections.Generic;
using Nethereum.Generators.Model;
namespace Nethereum.Generators.Core
{
public class ParameterABIModel : ParameterModel<ParameterABI>
{
public const string AnonymousInputParameterPrefix = "ParamValue";
public const string AnonymousOutputParameterPrefix = "ReturnValue";
public ParameterABIModel(ParameterABI parameter, CodeGenLanguage codeGenLanguage) : base(parameter, codeGenLanguage)
{
}
public ParameterABIModel(CodeGenLanguage codeGenLanguage) : base(codeGenLanguage)
{
}
public override string GetVariableName()
{
return GetVariableName(Parameter.Name, Parameter.Order);
}
public override string GetPropertyName()
{
return GetPropertyName(Parameter.Name, Parameter.Order);
}
public string GetPropertyName(ParameterDirection parameterDirection)
{
return GetPropertyName(Parameter.Name, Parameter.Order, parameterDirection);
}
public string GetVariableName(string name, int order)
{
return CommonGenerators.GenerateVariableName(NameOrDefault(name, order), CodeGenLanguage);
}
public string GetPropertyName(string name, int order, ParameterDirection parameterDirection = ParameterDirection.Output)
{
if (string.IsNullOrEmpty(name))
{
name = NameOrDefault(name, order, parameterDirection);
}
return CommonGenerators.GeneratePropertyName(name, CodeGenLanguage);
}
public virtual string GetStructTypeClassName()
{
if (string.IsNullOrEmpty(Parameter.StructType)) return null;
return CommonGenerators.GenerateClassName(Parameter.StructType);
}
private string NameOrDefault(string name, int order, ParameterDirection parameterDirection = ParameterDirection.Output)
{
if (!string.IsNullOrEmpty(name))
return name;
var prefix = parameterDirection == ParameterDirection.Input
? AnonymousInputParameterPrefix
: AnonymousOutputParameterPrefix;
return $"{prefix}{order}";
}
}
}
|
b60afe1e5c483f70374fc2ad568aa87af8ffda92
|
C#
|
kiki2702/reporter
|
/src/Reporter.DAL/GenericRepository.cs
| 2.859375
| 3
|
using Reporter.DAL.Entities.Contracts;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Reporter.DAL
{
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class, IEntity, new()
{
protected readonly DbContext context;
public GenericRepository(DbContext context)
{
this.context = context;
}
public Task DeleteAsync(Guid entityId)
{
TEntity entity = new TEntity();
entity.Id = entityId;
this.context.Set<TEntity>().Attach(entity);
this.context.Entry<TEntity>(entity).State = EntityState.Deleted;
return this.context.SaveChangesAsync();
}
public async Task<IList<TEntity>> GetAllAsync()
{
return await this.context.Set<TEntity>().AsNoTracking().Where(p => p != null).ToListAsync();
}
public Task<TEntity> GetAsync(Guid entityId)
{
return this.context.Set<TEntity>().AsNoTracking().SingleOrDefaultAsync(e => e.Id == entityId);
}
public Task InsertAsync(TEntity entity)
{
this.context.Set<TEntity>().Add(entity);
return this.context.SaveChangesAsync();
}
public Task UpdateAsync(TEntity entity)
{
this.context.Set<TEntity>().Attach(entity);
this.context.Entry<TEntity>(entity).State = EntityState.Modified;
this.context.Entry<TEntity>(entity).Property(x => x.DateCreated).IsModified = false;
return this.context.SaveChangesAsync();
}
}
}
|
d59ebea269e482839a7085d4daf53dd0ffcb4206
|
C#
|
shristoff/TelerikAcademy
|
/C#/PartI/2.Primitive-Data-Types-and-Variables/10.MarketingFirm/MarketingFirm.cs
| 3.484375
| 3
|
using System;
class MarketingFirm
{
static void Main()
{
Console.WriteLine("Please enter in this order First name, Family name, age, gender (m/f), IDnumber and UniqueNumber (4 digits):\n");
string FirstName = Console.ReadLine();
string FamilyName = Console.ReadLine();
byte age = byte.Parse(Console.ReadLine()); //byte (0 to 255): unsigned 8-bit
char gender = char.Parse(Console.ReadLine());
ushort IDnumber = ushort.Parse(Console.ReadLine()); //ushort (0 to 65,535): unsigned 16-bit
string UniqueNumber = ("2756" + ushort.Parse(Console.ReadLine())); //uint (0 to 4,294,967,295): unsigned 32-bit
Console.WriteLine("\nName: {0} {1}\nAge: {2}\nGender: {3}\nID: {4}\nUnique: {5}", FirstName, FamilyName, age, gender, IDnumber, UniqueNumber);
}
}
|
95a5c792436b201bef9fa50bf8b5fbce95ca5697
|
C#
|
Tochukz/MCSD_Study_Guide
|
/Chapter8/Chapter8/Program.cs
| 3.4375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chapter8
{
using System.Threading;
class Program
{
[ThreadStatic]
static int count = 0;
static void Main(string[] args)
{
//Thread myThread = new Thread(new ThreadStart(MyCustomThread));
Thread myThread = new Thread(new ParameterizedThreadStart(MyCustomThread));
// myThread.IsBackground = true;
//myThread.Start();
/*
myThread.Start(5);
myThread.Join();
for(int i=0; i<5; i++)
{
Thread.Sleep(100);
Console.Write("{0} ", i);
}
Console.WriteLine("\n" + "Hello from main Thread");
*/
Thread threadOne = new Thread(new ThreadStart(PriorityCount));
Thread threadTwo = new Thread(new ThreadStart(PriorityCount));
Thread threadThree = new Thread(new ThreadStart(PriorityCount));
threadOne.Priority = ThreadPriority.BelowNormal;
threadTwo.Priority = ThreadPriority.Highest;
threadThree.Priority = ThreadPriority.AboveNormal;
/*
//Runs to infinity.
threadOne.Start();
threadTwo.Start();
threadThree.Start();
*/
/*
Thread threadA = new Thread(() =>
{
for(int x = 0; x<10; x++)
{
Console.WriteLine($"Thread A {count++}");
}
});
Thread threadB = new Thread(() =>
{
for(int y = 0; y<10; y++)
{
Console.WriteLine($"Thread B {count++}");
}
});
threadA.Start();
threadB.Start();
*/
ThreadPool.QueueUserWorkItem(new WaitCallback(Pool));
Console.Write("The main method stays here...");
Console.ReadLine();
Console.WriteLine("Main method here again...");
ThreadPool.QueueUserWorkItem((s) =>
{
Console.WriteLine("\nThread pool from Lambda Expression");
});
Console.ReadLine();
}
static void MyCustomThread()
{
Console.WriteLine("Hello from Custom thread.");
for(int i=0; i<10; i++)
{
Console.Write("{0} ", i);
}
Console.WriteLine("\nBye from custom thread");
}
static void MyCustomThread(object obj)
{
Console.WriteLine("Hello from custom thread");
int count = (int)obj;
for(int x=0; x<count; x++)
{
Thread.Sleep(100);
Console.Write("{0} ",x);
}
Console.WriteLine("\nBye from custom thread");
}
static void PriorityCount()
{
string threadName = Thread.CurrentThread.Name;
string threadPriority = Thread.CurrentThread.Priority.ToString();
int count = 0;
bool stop = false;
while(stop != true)
{
count++;
}
Console.WriteLine($"Thread: {threadName} with Priority{threadPriority} has CPU count of {count}");
}
static void Pool(object obj)
{
Console.WriteLine("\nThread pool from Pool method.");
}
}
}
|
18050f0c3ac499805c18a0edc2bd724a94c73c00
|
C#
|
NikolaiLutsenko/diplomformasha
|
/DiplomaWork/Data/Models/CategoryConfiguration.cs
| 2.578125
| 3
|
using DiplomaWork.Data.Constants;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DiplomaWork.Data.Models
{
public class CategoryConfiguration : IEntityTypeConfiguration<Category>
{
public void Configure(EntityTypeBuilder<Category> builder)
{
builder.ToTable("Categories");
builder.HasKey(x => x.Id);
builder.HasIndex(x => x.Name).IsUnique();
builder.Property(x => x.Id).IsRequired();
builder.Property(x => x.Name).IsRequired();
builder.HasMany<Service>(x => x.Services)
.WithOne(x => x.Category)
.HasForeignKey(x => x.CategoryId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasData(new Category[]
{
new Category { Id = DefaultCategories.PhonesCategoryId, Name = "Телефоны"},
new Category { Id = DefaultCategories.NoteBooksCategoryId, Name = "Ноутбуки"},
new Category { Id = DefaultCategories.PrintersCategoryId, Name = "Принтеры"},
});
}
}
}
|
904812540da685f91b357e871a03cbf0fa7ff009
|
C#
|
kmanev073/wpfsudoku
|
/wpfsudokulib/Services/SudokuService.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wpfsudokulib.Enums;
namespace wpfsudokulib.Services
{
/// <summary>
/// The main functionality of the sudoku game
/// </summary>
public class SudokuService
{
#region PublicMethods
/// <summary>
/// Generates a new sudoku board
/// </summary>
/// <param name="difficulty"></param>
/// <returns></returns>
public byte?[] GenerateNew(GameDifficulties difficulty)
{
//Byte array used to store the board
byte?[] SudokuBoard;
//Boards are generated until a valid one is generated (can be optimized)
do
{
//Initialize the sudoku board to 9x9=81
SudokuBoard = new byte?[81];
//Holds all possible numbers for a cell
var pencilMarks = new List<byte?>[81];
//Fill in the pencil marks with all numbers as in the beggining the board is empty
for (int i = 0; i < 81; i++)
{
pencilMarks[i] = new List<byte?>();
for (byte j = 1; j <= 9; j++)
{
pencilMarks[i].Add(j);
}
//Smooth list shuffle
pencilMarks[i] = pencilMarks[i].OrderBy(_ => Guid.NewGuid()).ToList();
}
for (int i = 0; i < 81; i++)
{
//The cell's row
var row = i / 9;
//The cell's column
var column = i % 9;
//The starting row of the current sudoku block (3x3 square)
var blockRow = row / 3;
//The starting column of the current sudoku block
var blockColumn = column / 3;
//The cell's row relative to its block
var blockLocalRow = row % 3;
//The cell's column relative to its block
var blockLocalColumn = column % 3;
//Loop through all pencil marks until a good number is found
for (int index = 0; index < pencilMarks[i].Count; index++)
{
var value = pencilMarks[i][index];
bool flag = false;
//Check if we can place that number in the row
for (int k = 0; k < 9; k++)
{
if (column == k)
{
continue;
}
if (SudokuBoard[row * 9 + k] == value || (pencilMarks[row * 9 + k].Any(_ => _ == value) && pencilMarks[row * 9 + k].Count == 1))
{
flag = true;
}
}
if (flag)
{
continue;
}
//Check if we can place that number in the column
for (int k = 0; k < 9; k++)
{
if (row == k)
{
continue;
}
if (SudokuBoard[k * 9 + column] == value || (pencilMarks[k * 9 + column].Any(_ => _ == value) && pencilMarks[k * 9 + column].Count == 1))
{
flag = true;
}
}
if (flag)
{
continue;
}
//Check if we can place that number in the block
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
if (blockLocalRow == k && blockLocalColumn == l)
{
continue;
}
if (SudokuBoard[(blockRow * 3) * 9 + blockColumn * 3 + k * 9 + l] == value || (pencilMarks[(blockRow * 3) * 9 + blockColumn * 3 + k * 9 + l].Any(_ => _ == value) && pencilMarks[(blockRow * 3) * 9 + blockColumn * 3 + k * 9 + l].Count == 1))
{
flag = true;
}
}
}
if (flag)
{
continue;
}
//A good number was found
SudokuBoard[i] = value;
pencilMarks[i].Clear();
break;
}
//Remove pencil marks from row
for (int k = 0; k < 9; k++)
{
if (column == k)
{
continue;
}
pencilMarks[row * 9 + k].RemoveAll(_ => _ == SudokuBoard[i]);
}
//Remove pencil marks from column
for (int k = 0; k < 9; k++)
{
if (row == k)
{
continue;
}
pencilMarks[k * 9 + column].RemoveAll(_ => _ == SudokuBoard[i]);
}
//Remove pencil marks from block
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
if (blockLocalRow == k && blockLocalColumn == l)
{
continue;
}
pencilMarks[(blockRow * 3) * 9 + blockColumn * 3 + k * 9 + l].RemoveAll(_ => _ == SudokuBoard[i]);
}
}
}
}
while (CheckBoard(SudokuBoard) == false);
//Loop until the board is full and valid
//Generate random bytes
Random random = new Random();
var randomNumber = new byte[1];
//Depending on the difficulty certain amont of the cells will be set to null
switch (difficulty)
{
case GameDifficulties.Hard:
for (int i = 0; i < 81; i += 9)
{
//Gets a random byte number
random.NextBytes(randomNumber);
//Makes it a valid sudoku number
randomNumber[0] %= 9;
//Checks if the number can be found on the current row and removes if yes
for (int j = 0; j < 9; j++)
{
if (SudokuBoard[i + j] == randomNumber[0])
{
SudokuBoard[i + j] = null;
}
}
//Same logic for removing numbers
random.NextBytes(randomNumber);
randomNumber[0] %= 9;
for (int j = 0; j < 9; j++)
{
if (SudokuBoard[i + j] == randomNumber[0])
{
SudokuBoard[i + j] = null;
}
}
}
goto case GameDifficulties.Medium;
case GameDifficulties.Medium:
for (int i = 0; i < 81; i += 9)
{
//Same logic for removing numbers
random.NextBytes(randomNumber);
randomNumber[0] %= 9;
for (int j = 0; j < 9; j++)
{
if (SudokuBoard[i + j] == randomNumber[0])
{
SudokuBoard[i + j] = null;
}
}
//Same logic for removing numbers
random.NextBytes(randomNumber);
randomNumber[0] %= 9;
for (int j = 0; j < 9; j++)
{
if (SudokuBoard[i + j] == randomNumber[0])
{
SudokuBoard[i + j] = null;
}
}
}
goto case GameDifficulties.Easy;
case GameDifficulties.Easy:
for (int i = 0; i < 81; i += 9)
{
//Same logic for removing numbers
random.NextBytes(randomNumber);
randomNumber[0] %= 9;
for (int j = 0; j < 9; j++)
{
if (SudokuBoard[i + j] == randomNumber[0])
{
SudokuBoard[i + j] = null;
}
}
//Same logic for removing numbers
randomNumber = new byte[1];
random.NextBytes(randomNumber);
randomNumber[0] %= 9;
for (int j = 0; j < 9; j++)
{
if (SudokuBoard[i + j] == randomNumber[0])
{
SudokuBoard[i + j] = null;
}
}
}
break;
}
//Returns the new board as a byte array
return SudokuBoard;
}
/// <summary>
/// Check if a provided byte array is a solved sudoku board
/// </summary>
/// <param name="SudokuBoard">The sudoku board</param>
/// <returns></returns>
public bool CheckBoard(byte?[] SudokuBoard)
{
for (int i = 0; i < 81; i++)
{
//Same as in GenerateNew
var row = i / 9;
var column = i % 9;
var blockRow = row / 3;
var blockColumn = column / 3;
var blockLocalRow = row % 3;
var blockLocalColumn = column % 3;
//If an empty cell is found this means that the board is invalid
if (SudokuBoard[i] == null)
{
return false;
}
//Validate row
for (int k = 0; k < 9; k++)
{
if (column == k)
{
continue;
}
if (SudokuBoard[row * 9 + k] == SudokuBoard[row * 9 + column])
{
return false;
}
}
//Validate column
for (int k = 0; k < 9; k++)
{
if (row == k)
{
continue;
}
if (SudokuBoard[k * 9 + column] == SudokuBoard[row * 9 + column])
{
return false;
}
}
//Validate block
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
if (blockLocalRow == k && blockLocalColumn == l)
{
continue;
}
if (SudokuBoard[(blockRow * 3) * 9 + blockColumn * 3 + k * 9 + l] == SudokuBoard[(blockRow * 3) * 9 + blockColumn * 3 + blockLocalRow * 9 + blockLocalColumn])
{
return false;
}
}
}
}
//Returns true if all the checks pass
return true;
}
#endregion
}
}
|
fee5d40696271c23843cf81c956d1433b7bfa8ae
|
C#
|
longde123/maps
|
/Solution/Maps.Data.OpenStreetMap/OsmGeo.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using Maps.Extensions;
namespace Maps.Data.OpenStreetMap
{
/// <summary>
/// Enum to describe the geometry type
/// </summary>
public enum OsmGeoType
{
Node = 0,
Way = 1,
Relation = 2,
}
/// <summary>
/// Base class for OpenStreetMap geometries
/// </summary>
public abstract class OsmGeo
{
/// <summary>
/// The id for the geometry
/// </summary>
public readonly long Id;
/// <summary>
/// The tags for the geometry
/// </summary>
public readonly IReadOnlyDictionary<string, string> Tags;
/// <summary>
/// The globally unique id for the geometry
/// </summary>
public Guid Guid => Id.ToGuid((long)Type);
/// <summary>
/// The name of the geometry
/// </summary>
public string Name => Tags.ContainsKey("name") ? Tags["name"] : null;
/// <summary>
/// The enum matching this geometry
/// </summary>
protected abstract OsmGeoType Type
{
get;
}
private static readonly IReadOnlyDictionary<string, string> EmptyTags =
new Dictionary<string, string>();
/// <summary>
/// Initializes a new instance of OsmGeo
/// </summary>
/// <param name="id">The id of the geometry</param>
protected OsmGeo(long id) : this(id, null)
{
}
/// <summary>
/// Initializes a new instance of OsmGeo
/// </summary>
/// <param name="id">The id of the geometry</param>
/// <param name="tags">The tags for the geometry</param>
protected OsmGeo(long id, IDictionary<string, string> tags)
{
if (tags == null || tags.Count <= 0)
{
Tags = EmptyTags;
}
else
{
foreach (var tag in tags)
{
if (tag.Key == null)
{
throw new ArgumentException("Contains a null tag " +
"key", nameof(tags));
}
}
Tags = new Dictionary<string, string>(tags);
}
Id = id;
}
/// <inheritdoc />
public override string ToString()
{
return $"{Type} : {Id}";
}
}
}
|
0cfb113cee046a7f955f81aead8bbc9a8c825cf0
|
C#
|
harley333/common-dataAccess
|
/Common.DataAccess/Mapper.cs
| 3.234375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Common.DataAccess {
/// <summary>
/// This class contains helper methods for mapping properties from one type to another.
/// </summary>
/// <remarks>
/// Remodeling data can be a very costly operation (performance-wise). A best-case will always
/// be represented by a mapping function which is hand-written by a developer. However, the
/// upfront development cost and on-going maintenance of mapping functions can become daunting
/// (investment-wise) as well.
/// <para>
/// Spending resource investments on explicitly-defined mapping functions seems silly and a
/// waste. After all, the vast majority of mapping functions are a simple matter of naming
/// conventions. For example, "I want to take the value from the 'Name' property from this
/// object and put it in the 'Name' property of this other object."
/// </para>
/// <para>
/// When an explicitly-defined mapping function is a waste of time for a developer, the
/// <see cref="Mapper"/> class will instantiate an instance of the
/// <see cref="Mapper{TFrom, TTo}"/> class.
/// </para>
/// <para>
/// Any delegate created via these methods is cached for future use.
/// </para>
/// </remarks>
public class Mapper {
#region Using Explicit Mapper (fastest - the developer supplies a custom-made mapper)
/// <summary>
/// Maps the properties of one type to another using an explicitly-defined mapper.
/// </summary>
/// <typeparam name="TIncoming">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <typeparamref name="TIncoming"/></param>
/// <param name="mapper">An explicitly-defined mapper.</param>
/// <returns>A <typeparamref name="TOutgoing"/></returns>
public static TOutgoing Remodel<TIncoming, TOutgoing>(TIncoming source, Func<TIncoming, TOutgoing> mapper)
where TIncoming : class
where TOutgoing : class {
return Remodel(new[] { source }, mapper).First();
}
/// <summary>
/// Maps the properties of one type to another using an explicitly-defined mapper.
/// </summary>
/// <typeparam name="TIncoming">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <see cref="IEnumerable"/><<typeparamref name="TIncoming"/>></param>
/// <param name="mapper">An explicitly-defined mapper.</param>
/// <returns>An <see cref="IEnumerable"/><<typeparamref name="TOutgoing"/>></returns>
public static IEnumerable<TOutgoing> Remodel<TIncoming, TOutgoing>(IEnumerable<TIncoming> source, Func<TIncoming, TOutgoing> mapper)
where TIncoming : class
where TOutgoing : class {
var list = new List<TOutgoing>();
if (source != null) {
foreach (var item in source) {
list.Add(mapper(item));
}
}
return list;
}
/// <summary>
/// Maps the properties of one type to another using an explicitly-defined mapper.
/// </summary>
/// <typeparam name="TIncoming">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <see cref="PagedData"/><<typeparamref name="TIncoming"/>></param>
/// <param name="mapper">An explicitly-defined mapper.</param>
/// <returns>A <see cref="PagedData"/><<typeparamref name="TOutgoing"/>></returns>
public static PagedData<TOutgoing> Remodel<TIncoming, TOutgoing>(PagedData<TIncoming> source, Func<TIncoming, TOutgoing> mapper)
where TIncoming : class
where TOutgoing : class {
var list = Remodel(source.Data, mapper);
return new PagedData<TOutgoing>(source.TotalRecords, source.PageSize, source.StartIndex, list);
}
#endregion
#region Using Default Mapper (a little slower - a Mapper is compiled by reflective inspection)
/// <summary>
/// Maps the properties of a known type to another by automatically building a mapper.
/// </summary>
/// <remarks>
/// The mapper will be an instance of <see cref="Mapper{TFrom, TTo}"/>.
/// </remarks>
/// <typeparam name="TIncoming">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <typeparamref name="TIncoming"/></param>
/// <param name="checkMissingColumns">
/// When properties are in the source object, but absent in the destination object, this
/// value determines if an exception is thrown during the mapping operation.
/// </param>
/// <returns>A <typeparamref name="TOutgoing"/></returns>
public static TOutgoing Remodel<TIncoming, TOutgoing>(TIncoming source, bool checkMissingColumns = true)
where TIncoming : class
where TOutgoing : class {
return Remodel<TIncoming, TOutgoing>(new[] { source }, checkMissingColumns).First();
}
/// <summary>
/// Maps the properties of a known type to another by automatically building a mapper.
/// </summary>
/// <remarks>
/// The mapper will be an instance of <see cref="Mapper{TFrom, TTo}"/>.
/// </remarks>
/// <typeparam name="TIncoming">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <see cref="IEnumerable"/><<typeparamref name="TIncoming"/>></param>
/// <param name="checkMissingColumns">
/// When properties are in the source object, but absent in the destination object, this
/// value determines if an exception is thrown during the mapping operation.
/// </param>
/// <returns>A <see cref="IEnumerable"/><<typeparamref name="TOutgoing"/>></returns>
public static IEnumerable<TOutgoing> Remodel<TIncoming, TOutgoing>(IEnumerable<TIncoming> source, bool checkMissingColumns = true)
where TIncoming : class
where TOutgoing : class {
return Remodel(source, GetMapDelegate<TIncoming, TOutgoing>(checkMissingColumns));
}
/// <summary>
/// Maps the properties of a known type to another by automatically building a mapper.
/// </summary>
/// <remarks>
/// The mapper will be an instance of <see cref="Mapper{TFrom, TTo}"/>.
/// </remarks>
/// <typeparam name="TIncoming">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <see cref="PagedData"/><<typeparamref name="TIncoming"/>></param>
/// <param name="checkMissingColumns">
/// When properties are in the source object, but absent in the destination object, this
/// value determines if an exception is thrown during the mapping operation.
/// </param>
/// <returns>A <see cref="PagedData"/><<typeparamref name="TOutgoing"/>></returns>
public static PagedData<TOutgoing> Remodel<TIncoming, TOutgoing>(PagedData<TIncoming> source, bool checkMissingColumns = true)
where TIncoming : class
where TOutgoing : class {
var list = Remodel<TIncoming, TOutgoing>(source.Data, checkMissingColumns);
return new PagedData<TOutgoing>(source.TotalRecords, source.PageSize, source.StartIndex, list);
}
#endregion
#region Using Default Mapper - Generic Destination with Unknown Source (slowest - reflection is used to find the "GetMapDelegate" method and execute it, which then compiles a Mapper by reflective inspection)
/// <summary>
/// Maps the properties of an unknown type to another by automatically building a mapper.
/// </summary>
/// <remarks>
/// The mapper will be an instance of <see cref="Mapper{TFrom, TTo}"/>.
/// <para>
/// The <paramref name="source"/> parameter is assumed to be an instance of
/// <see cref="IEnumerable{T}"/>. The generic argument "T" is discovered from the source
/// collection and used to create an instance of <see cref="Mapper{TFrom, TTo}"/>.
/// </para>
/// </remarks>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <see cref="IEnumerable"/></param>
/// <param name="checkMissingColumns">
/// When properties are in the source object, but absent in the destination object, this
/// value determines if an exception is thrown during the mapping operation.
/// </param>
/// <returns>A <see cref="IEnumerable"/><<typeparamref name="TOutgoing"/>></returns>
public static IEnumerable<TOutgoing> Remodel<TOutgoing>(IEnumerable source, bool checkMissingColumns = true)
where TOutgoing : class {
Type tIncoming = null;
foreach (Type i in source.GetType().GetInterfaces()) {
if (i.IsGenericType && i.GetGenericTypeDefinition().Equals(typeof(IEnumerable<>))) {
tIncoming = i.GetGenericArguments()[0];
break;
}
}
Type tOutgoing = typeof(TOutgoing);
Type me = typeof(Mapper);
MethodInfo method = me.GetMethod("GetMapDelegate");
MethodInfo generic = method.MakeGenericMethod(tIncoming, tOutgoing);
var map = generic.Invoke(null, new object[] { checkMissingColumns });
var sourceType = typeof(IEnumerable<>).MakeGenericType(tIncoming);
var delegateType = typeof(Func<,>).MakeGenericType(tIncoming, tOutgoing);
method = me.GetGenericMethod("Remodel", new[] { sourceType, delegateType });
generic = method.MakeGenericMethod(tIncoming, tOutgoing);
return (IEnumerable<TOutgoing>)generic.Invoke(null, new[] { source, map });
}
/// <summary>
/// Maps the properties of an unknown type to another by automatically building a mapper.
/// </summary>
/// <remarks>
/// The mapper will be an instance of <see cref="Mapper{TFrom, TTo}"/>.
/// <para>
/// The <paramref name="source"/> parameter is assumed to be an instance of
/// <see cref="PagedData{TEntity}"/>. The generic argument "TEntity" is discovered from the
/// source collection and used to create an instance of <see cref="Mapper{TFrom, TTo}"/>.
/// </para>
/// </remarks>
/// <typeparam name="TOutgoing">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="source">An instance of <see cref="PagedData"/></param>
/// <param name="checkMissingColumns">
/// When properties are in the source object, but absent in the destination object, this
/// value determines if an exception is thrown during the mapping operation.
/// </param>
/// <returns>A <see cref="PagedData"/><<typeparamref name="TOutgoing"/>></returns>
public static PagedData<TOutgoing> Remodel<TOutgoing>(PagedData source, bool checkMissingColumns = true)
where TOutgoing : class {
var list = Remodel<TOutgoing>(source.Data, checkMissingColumns);
return new PagedData<TOutgoing>(source.TotalRecords, source.PageSize, source.StartIndex, list);
}
#endregion
#region Map-cache Helper Methods
// here's a collection of delegate functions
// each delegate is responsible for performing a specific map operation (FROM one type of object, TO another type of object)
// the key of the collection is generated by the GetMapName method
private static SortedList<string, object> _Mappers = new SortedList<string, object>();
// here's a collection of delegate functions which are currently being built
// keeping this collection allows us to build recursive mappers
private static List<string> _MappersBeingBuilt = new List<string>();
/// <summary>
/// Returns a delegate which maps the properties from one object to another and returns the
/// destination object.
/// </summary>
/// <typeparam name="TFrom">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TTo">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="checkMissingColumns">
/// When properties are in the source object, but absent in the destination object, this
/// value determines if an exception is thrown during the mapping operation.
/// </param>
/// <returns>A <see cref="Func{TFrom, TTo}"/></returns>
public static Func<TFrom, TTo> GetMapDelegate<TFrom, TTo>(bool checkMissingColumns = true)
where TFrom : class
where TTo : class {
var map = GetMap<TFrom, TTo>(checkMissingColumns);
return delegate(TFrom source) {
var destination = Activator.CreateInstance<TTo>();
map(source, destination);
return destination;
};
}
/// <summary>
/// Returns a delegate which maps the properties from one supplied object to another
/// supplied object.
/// </summary>
/// <typeparam name="TFrom">
/// The data-type that is being mapped from.
/// </typeparam>
/// <typeparam name="TTo">
/// The data-type that is being mapped to.
/// </typeparam>
/// <param name="checkMissingColumns">
/// When properties are in the source object, but absent in the destination object, this
/// value determines if an exception is thrown during the mapping operation.
/// </param>
/// <returns>An <see cref="Action{TFrom, TTo}"/></returns>
public static Action<TFrom, TTo> GetMap<TFrom, TTo>(bool checkMissingColumns = true)
where TFrom : class
where TTo : class {
var tFrom = typeof(TFrom);
var tTo = typeof(TTo);
object temp = null;
Action<TFrom, TTo> mapper = null;
var mapName = GetMapName(tFrom, tTo, checkMissingColumns);
if (!_Mappers.TryGetValue(mapName, out temp)) {
if (_MappersBeingBuilt.Contains(mapName)) {
// If the requested map is currently being built, we must be building a
// recursive map. We cannot return the map, because it's still being built.
// Instead, we'll return a delegate which can request the map after it has
// been built.
return (x, y) => GetMap<TFrom, TTo>(checkMissingColumns);
} else {
_MappersBeingBuilt.Add(mapName);
mapper = new Mapper<TFrom, TTo>(checkMissingColumns).GetMap();
_Mappers.Add(mapName, mapper);
_MappersBeingBuilt.Remove(mapName);
}
} else {
mapper = (Action<TFrom, TTo>)temp;
}
return mapper;
}
private static string GetMapName(Type tFrom, Type tTo, bool checkMissingColumns) {
return string.Concat(checkMissingColumns ? "STRICT_" : "", tFrom.FullName, "_|_", tTo.FullName);
}
#endregion
}
}
|
abb7deea119a8aecd2a70a6c3ba1112e2d32750a
|
C#
|
adamyWA/ApiDemo
|
/Format.cs
| 2.96875
| 3
|
using System;
namespace Enom
{
public static class Format
{
public static string Input(Parameters parameters)
{
string _queryString = "";
char[] _end = { Convert.ToChar("&") };
foreach (Parameter p in parameters)
{
_queryString += p.Key + "=" + p.Value + "&";
}
return _queryString.TrimEnd(_end);
}
public static void Output(Parameters parameters)
{
//will format XML nodes as Node=Value and return string
}
}
}
|
355da04afc208ea26f4bcfdc1a9546f2310f6099
|
C#
|
mdamyanova/SoftUni-CSharp-Web-Development
|
/02.Advanced C#/Homework/05.Regular Expressions/04.ExtractEmails/ExtractEmails.cs
| 3.0625
| 3
|
//Write a program to extract all email addresses from a given text.
//The text comes at the only input line. Print the emails on the console,
//each at a separate line. Emails are considered to be in format <user>@<host>, where:
//• <user> is a sequence of letters and digits, where '.', '-' and '_' can appear
//between them. Examples of valid users: "stephan", "mike03", "s.johnson", "st_steward",
//"softuni-bulgaria", "12345". Examples of invalid users: ''--123", ".....", "nakov_-",
//"_steve", ".info".
//• <host> is a sequence of at least two words, separated by dots '.'. Each word is
//sequence of letters and can have hyphens '-' between the letters. Examples of hosts:
//"softuni.bg", "software-university.com", "intoprogramming.info", "mail.softuni.org".
//Examples of invalid hosts: "helloworld", ".unknown.soft.", "invalid-host-", "invalid-".
using System;
using System.Text.RegularExpressions;
class ExtractEmails
{
static void Main()
{
string input = Console.ReadLine();
string pattern = @"(?<=\s|^)([a-z0-9]+(?:[_.-][a-z0-9]+)*@[a-z]+\-?[a-z]+(?:\.[a-z]+)+)\b";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(input);
foreach (Match item in matches)
{
Console.WriteLine(item.Groups[0]);
}
}
}
|
3eea9050bf0efdd58a5fcbce8878e7460629712c
|
C#
|
Rezivel/FlymeArena
|
/Assets/MainMenu/Scripts/AttachmentBase58.cs
| 3
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Numerics;
using System.Linq;
using System;
public class AttachmentBase58{
static string alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
public static string DecimalToHex(BigInteger dec)
{
var s = dec.ToString();
var result = new List<byte>();
result.Add(0);
foreach (char c in s)
{
int val = (int)(c - '0');
for (int i = 0; i < result.Count; i++)
{
int digit = result[i] * 10 + val;
result[i] = (byte)(digit & 0x0F);
val = digit >> 4;
}
if (val != 0)
result.Add((byte)val);
}
var hex = "";
foreach (byte b in result)
hex = "0123456789ABCDEF"[b] + hex;
return hex;
}
public static string HexToDecimal(string hex)
{
List<int> dec = new List<int> { 0 };
foreach (char c in hex)
{
int carry = Convert.ToInt32(c.ToString(), 16);
for (int i = 0; i < dec.Count; ++i)
{
int val = dec[i] * 16 + carry;
dec[i] = val % 10;
carry = val / 10;
}
while (carry > 0)
{
dec.Add(carry % 10);
carry /= 10;
}
}
var chars = dec.Select(d => (char)('0' + d));
var cArr = chars.Reverse().ToArray();
return new string(cArr);
}
public static string Base58NumericEncode(BigInteger num)
{
string encoded = string.Empty;
if (num == 0)
{
encoded = alphabet[0] + encoded;
}
while (num > 0)
{
BigInteger numRem = num % 58;
num = num / 58;
encoded = alphabet[(int)numRem] + encoded;
}
return encoded;
}
public static string Base58NumericDecode(string encoded)
{
BigInteger conv = 0;
BigInteger numTemp = 1;
if (!string.IsNullOrEmpty(encoded))
{
while (encoded.Length > 0)
{
char currentChar = encoded[encoded.Length - 1];
conv += (numTemp * alphabet.IndexOf(currentChar));
numTemp *= 58;
encoded = encoded.Remove(encoded.Length - 1);
}
}
return DecimalToHex(conv);
}
}
|
d88ccdeaa92d940631b835035f41657910ffd339
|
C#
|
lewisliang82/MemPowered
|
/MemPowered/Publisher.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enyim.Caching.Memcached;
namespace MemPowered
{
public static class Publisher
{
static List<Action<MemcachedNode>> registrants = new List<Action<MemcachedNode>>();
public static void Register(Action<MemcachedNode> action)
{
registrants.Add(action);
}
public static void Publish(MemcachedNode node)
{
registrants.ForEach(a => a.Invoke(node));
}
public static void Unregister(Action<MemcachedNode> action)
{
registrants.Remove(action);
}
}
}
|
def89da77d2820c11e7be2e700602f18fc64bca7
|
C#
|
vscheffer/SqlQueryBuilder
|
/src/Peerislands.SqlQueryBuilder.Core/Query/Clauses/WhereClause.cs
| 2.828125
| 3
|
using Peerislands.SqlQueryBuilder.Core.Enums;
using System;
using System.Collections.Generic;
using System.Text;
namespace Peerislands.SqlQueryBuilder.Core.Entities.Clauses
{
public struct WhereClause
{
private string m_FieldName;
private QueryComparison m_ComparisonOperator;
private object m_Value;
internal struct SubClause
{
public LogicOperator LogicOperator;
public QueryComparison ComparisonOperator;
public object Value;
public SubClause(LogicOperator logic, QueryComparison compareOperator, object compareValue)
{
LogicOperator = logic;
ComparisonOperator = compareOperator;
Value = compareValue;
}
}
internal List<SubClause> SubClauses;
public string FieldName
{
get { return m_FieldName; }
set { m_FieldName = value; }
}
public QueryComparison ComparisonOperator
{
get { return m_ComparisonOperator; }
set { m_ComparisonOperator = value; }
}
public object Value
{
get { return m_Value; }
set { m_Value = value; }
}
public WhereClause(string field, QueryComparison firstCompareOperator, object firstCompareValue)
{
m_FieldName = field;
m_ComparisonOperator = firstCompareOperator;
m_Value = firstCompareValue;
SubClauses = new List<SubClause>();
}
public void AddClause(LogicOperator logic, QueryComparison compareOperator, object compareValue)
{
SubClause NewSubClause = new SubClause(logic, compareOperator, compareValue);
SubClauses.Add(NewSubClause);
}
}
}
|
7e7fd86bcba68d97d17b26797960f1846b447e8f
|
C#
|
andonovskakristina/Vizuelno-Programiranje
|
/AV07/Hangman/Hangman/ArrayWordSelector.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman
{
class ArrayWordSelector : IWordSelector
{
private readonly string[] words = {
"Argentina",
"Australia",
"Greenland",
"Guatemala",
"Indonesia",
"Lithuania",
"Macedonia",
"Mauritius",
"Nicaragua",
"Venezuela"
};
private Random random;
public ArrayWordSelector()
{
random = new Random();
}
public string pick()
{
int index = random.Next(words.Length);
return words[index];
}
}
}
|
8aa843e20ea87eecbbe289efeeb375cab9f71ae8
|
C#
|
Jeffry38/Stealers-Collection
|
/[corclub]Govnofile/Mystery Stealer + Panel/mystery stealer source(1)/MailRy.Linq/DelegateComparer.cs
| 2.625
| 3
|
using NoiseMe.Drags.App.Models.Delegates;
using System;
using System.Collections.Generic;
namespace MailRy.Linq
{
internal class DelegateComparer<TSource, TKey> : IComparer<TSource> where TKey : IComparable<TKey>
{
private Func<TSource, TKey> m_Getter;
public DelegateComparer(Func<TSource, TKey> getter)
{
m_Getter = getter;
}
public int Compare(TSource x, TSource y)
{
return m_Getter(x).CompareTo(m_Getter(y));
}
}
}
|
441c5fe889fbc62d0cbdd68735cc3adaa23c352e
|
C#
|
MatviiSuslenko/unity-important
|
/railway-builder-demo/BezierPoint.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteAlways]
public class BezierPoint : MonoBehaviour
{
public Transform current;
public Transform left;
public Transform right;
private Vector3 leftOldPos;
private Vector3 rightOldPos;
private float compareConst = 0.0001f;
private void Start()
{
Update();
leftOldPos = left.position;
rightOldPos = right.position;
}
void Update()
{
if((left.position - leftOldPos).magnitude > compareConst)
{
leftOldPos = left.position;
rightOldPos = transform.position - (leftOldPos - transform.position);
right.position = rightOldPos;
}
else if ((right.position - rightOldPos).magnitude > compareConst)
{
rightOldPos = right.position;
leftOldPos = transform.position - (rightOldPos - transform.position);
left.position = leftOldPos;
}
}
void OnDrawGizmos()
{
//Gizmos.color = Color.black;
//Gizmos.DrawLine(left.position, right.position);
//Gizmos.color = Color.white;
}
}
|
475510bc008d040f344c256e5027fedd2d13c76f
|
C#
|
lpixley1/DnD
|
/DnD/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace DnD
{
class Program
{
static void Main(string[] args)
{
DiceRoll.chooser();
CharacterSheet.start();
Console.ReadKey();
}
}
class DiceRoll
{
public static void chooser()
{
Console.WriteLine("What dice would you like to roll?");
Console.WriteLine("d2, d4, d6, d8, d10, d12, d20, d100, or other kind of dice");
string choice = Console.ReadLine();
if (choice == "")
{
Console.WriteLine("Please input an actual value");
chooser();
}
string die = new String(choice.Where(Char.IsDigit).ToArray());
roller(Int32.Parse(die));
}
public static void roller(int die)
{
Random rnd = new Random();
int roll = 0;
int total = 0;
int counter = 1;
Console.WriteLine("How many would you like to roll?");
string choice = Console.ReadLine();
string number = new String(choice.Where(char.IsDigit).ToArray());
int num = Int32.Parse(number);
while (counter <= num)
{
roll = rnd.Next(1, die + 1);
Console.WriteLine("Roll " + counter + " is: " + roll);
counter++;
total += roll;
}
Console.WriteLine("Total is: " + total);
Continue();
}
public static void Continue()
{
Console.WriteLine("Would you like to continue?");
string choice = Console.ReadLine();
choice.ToLower();
if (choice == "y" || choice == "yes" || choice == "")
{
Console.Clear();
chooser();
}
if (choice == "n" || choice == "no")
{
Environment.Exit(0);
}
}
}
class CharacterSheet
{
public static void start()
{
Console.WriteLine("Would you like to access a character sheet or make a new one?");
string choice = Console.ReadLine();
string Choice = new String(choice.Where(char.IsDigit).ToArray());
Choice.ToLower();
if (Choice == "new")
{
newCharacter();
}
else if (Choice == "access")
{
accessCharacter();
}
else
{
Console.WriteLine("Please input either 'new' or 'access'");
Console.ReadKey();
Console.Clear();
start();
}
}
public static void newCharacter()
{
Console.WriteLine("Welcome to character creation!");
Console.WriteLine("First, input your race:");
string choice = Console.ReadLine();
string race = new String(choice.Where(Char.IsDigit).ToArray());
StreamReader sr = new StreamReader("c:\\home\\loganpixley\\races\\" + race + ".txt");
}
public static void accessCharacter()
{
Console.WriteLine("What is the name of your character?");
string name = Console.ReadLine();
}
}
}
|
4664d70e715f8c2b900af171b30ee3458c093c67
|
C#
|
robertocarlostf/btest
|
/Bertoni.Domain/AlbumService.cs
| 2.8125
| 3
|
using Bertoni.Data.Abstraction;
using Bertoni.Data.Entitites;
using Bertoni.Domain.Abstraction;
using Bertoni.Domain.BusinessObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bertoni.Domain
{
public class AlbumService : IService<Album>
{
private IRepository<Albums> _albumRepo = null;
public AlbumService(IRepository<Albums> _albumRepository)
{
_albumRepo = _albumRepository;
}
public IList<Album> GetAll()
{
List<Album> _return = null;
try
{
var _data = _albumRepo.GetAll();
if(_data != null)
{
_return = new List<Album>();
foreach (var d in _data)
{
_return.Add(new Album(d));
}
}
return _return;
}
catch (Exception)
{
throw;
}
}
public Album GetById(int id)
{
try
{
var _data = _albumRepo.Get(id);
return new Album(_data);
}
catch (Exception)
{
throw;
}
}
public IList<Album> QueryBy(Func<Album, bool> filter)
{
List<Album> _return = null;
try
{
var _data = _albumRepo.GetAll();
if(_data != null)
{
_return = new List<Album>();
foreach (var d in _data)
{
_return.Add(new Album(d));
}
}
return _return.Where(filter).ToList();
}
catch (Exception)
{
throw;
}
}
}
}
|
9dc0f3ce7d09929ed0afd756cd87c89774ebb765
|
C#
|
PUPA42/Pattern
|
/Pattern/Visitor/Computer.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pattern.Visitor
{
class Computer : IComputerPart
{
private IComputerPart[] m_computerParts;
public Computer(IComputerPart[] computerParts)
{
m_computerParts = computerParts;
}
public void Accept(IComputerVisitor computerVisitor)
{
for (int i = 0; i < m_computerParts.Length; i++)
{
m_computerParts[i].Accept(computerVisitor);
}
computerVisitor.Visit(this);
}
}
}
|
f45976c33eea59afabef10c027e0a135016b9e2f
|
C#
|
DreamRunnerMoshi/LeetCode
|
/LeetCode.Solutions/_39CombinationSum.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.Solutions
{
public class _39CombinationSum
{
public IList<IList<int>> CombinationSum(int[] candidates, int target)
{
List<IList<int>> ans = new List<IList<int>>();
FindCombination(candidates, target, new List<int>(), 0, ans);
return ans;
}
private void FindCombination(int[] candidates, int target, List<int> result, int currentIndex, List<IList<int>> ans)
{
Array.Sort(candidates);
if (target < 0) return;
if (target == 0)
{
var r = new List<int>(result);
ans.Add(r);
return;
}
while (currentIndex < candidates.Length && target - candidates[currentIndex] >= 0)
{
result.Add(candidates[currentIndex]);
FindCombination(candidates, target - candidates[currentIndex], result, currentIndex, ans);
currentIndex++;
result.RemoveAt(result.Count - 1);
}
}
}
}
|
2c73141564cf6916e5a0a6609eea45c9ff3c3b85
|
C#
|
green-fox-academy/Albert-Bach
|
/Homework/DoableHomework/DoableHomework/Program.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoableHomework
{
class Program
{
static void Main(string[] args)
{
string tree1 = "mapple, red, 10,male";
string tree2 = "birch,green, 20, female";
string tree3 = "pine, darkgreen, 10, male";
string tree4 = "quaking aspen, yellow, 7, male";
string tree5 = " walnut, brown, 30, male";
var Trees = new List<string>() { tree1, tree2, tree3, tree4, tree5 };
}
}
}
|
1f470b86b27c19dee6f61fa2d91a14d08ce20052
|
C#
|
modmoto/HeroShoote
|
/Assets/Scripts/Player/FollowObject.cs
| 2.703125
| 3
|
using UnityEngine;
namespace Player
{
public class FollowObject : MonoBehaviour
{
public Transform objectToFollow;
public float smoothSpeed = 0.125f;
void LateUpdate()
{
var positionOfFollowingObject = objectToFollow.position;
var currentPosition = transform.position;
var desiredPosition = new Vector3(
positionOfFollowingObject.x,
positionOfFollowingObject.y,
currentPosition.z);
var lerpedPosition = Vector3.Lerp(currentPosition, desiredPosition, smoothSpeed);
transform.position = lerpedPosition;
}
}
}
|
23070811f682383808b663e512cea5262ebadee4
|
C#
|
ozgend/definder
|
/DeFinderLib/Models/SearchModel.cs
| 2.5625
| 3
|
using denolk.DeFinder.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace denolk.DeFinder.Models
{
[Serializable]
internal class SearchModel
{
public string Path { get; set; }
public List<string> Filenames { get; set; }
public SearchModel(string path)
{
Path = path;
}
public void Populate(bool rebuild)
{
Filenames = IndexedResultHelper.GetContents(Path,rebuild);
}
public byte[] ToBytes()
{
byte[] bytes;
var format = new BinaryFormatter();
using (var stream = new MemoryStream())
{
format.Serialize(stream, this);
bytes = stream.ToArray();
}
return bytes;
}
public Dictionary<string, List<string>> ToDictionary()
{
var dictionary = new Dictionary<string, List<string>>();
dictionary[this.Path] = this.Filenames;
return dictionary;
}
}
}
|
d135506d6e7dbc480b7dedc0ae74318fa1b49813
|
C#
|
petargg/UserApi.Consumer
|
/UserApi.Consumer/UserClient.cs
| 2.921875
| 3
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace UserApi.Consumer
{
public class UsersClient
{
private HttpClient client;
public UsersClient()
{
client = new HttpClient();
client.BaseAddress = new Uri("");
}
public async Task<User> GetUser(int id)
{
var response = await client.GetAsync("/api/users/" + id).ConfigureAwait(false);
var user = JsonConvert.DeserializeObject<User>(await response.Content.ReadAsStringAsync());
return user;
}
public async Task<IEnumerable<User>> GetUsers(IEnumerable<int> ids)
{
var response = await client
.PostAsync("/api/users/GetMany", new StringContent(JsonConvert.SerializeObject(ids), Encoding.UTF8, "application/json"))
.ConfigureAwait(false);
var users = JsonConvert.DeserializeObject<IEnumerable<User>>(await response.Content.ReadAsStringAsync());
return users;
}
}
}
|
5fc66a0e200dc77e3313db5db8319fccc0773690
|
C#
|
wowowoxuan/buildserver
|
/project#4/681proj4/repo/repository.cs
| 2.515625
| 3
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//repository.cs:Repository Server for proj#4 //
//Author:Chai,Weiheng,wchai01@syr.edu //
//Application:CSE681 Proj4-repo //
//Environment:c# console //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Package Operations:
* ===================
*1.send list of files and dirs to the Client 2.when receive the send build request command from the Client, send the build request to the mother builder
*
* Public Interface
* ==================================================================
* No public interface in this package
*
* All Other Functions used in this package
* ==================================================================
* void initializeEnvironment()-----set Environment properties needed by server
* repository()-----(constructor)initialize server processing
* void initializeDispatche()-----define how each message will be processed
*
*
* Required Files:
* =============================================
* Environment1
* FileMgr1
* wcfcom1
*
*
* Build command:
* =============================================
* csc{App.config,repository.cs}
* dnvenv repo.csproj
*
* * Maintenance History:
* --------------------
* ver 1.0 : 07/12/2017
* - first release
*/
using Navigator;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wcfcom1;
namespace repo
{
class repository
{
IFileMgr localFileMgr { get; set; } = null;
Dictionary<string, Func<CommMessage, CommMessage>> messageDispatcher =
new Dictionary<string, Func<CommMessage, CommMessage>>();
void initializeEnvironment() //set Environment properties needed by server
{
Environment1.root = ServerEnvironment.root;
Environment1.address = ServerEnvironment.address;
Environment1.port = ServerEnvironment.port;
Environment1.endPoint = ServerEnvironment.endPoint;
}
repository() //initialize repository processing
{
initializeEnvironment();
localFileMgr= FileMgrFactory.create(FileMgrType.Local);
}
void initializeDispatcher() //define how each message will be processed
{
CommMessage reply = new CommMessage();
reply.Source = "repo";
reply.Destinaiton = "gui";
Func<CommMessage, CommMessage> getTopFiles = (CommMessage msg) =>
{
localFileMgr.currentPath = "";
reply.command = "getTopFiles";
reply.arguments = localFileMgr.getFiles().ToList<string>();
return reply;
};
messageDispatcher["getTopFiles"] = getTopFiles;
Func<CommMessage, CommMessage> getBuildRequest = (CommMessage msg) =>
{
localFileMgr.currentPath = "";
reply.command = "getBuildRequest";
reply.arguments = localFileMgr.getFiles().ToList<string>();
return reply;
};
messageDispatcher["getBuildRequest"] = getBuildRequest;
Func<CommMessage, CommMessage> getTopDirs = (CommMessage msg) =>
{
localFileMgr.currentPath = "";
reply.command = "getTopDirs";
reply.arguments = localFileMgr.getDirs().ToList<string>();
return reply;
};
messageDispatcher["getTopDirs"] = getTopDirs;
Func<CommMessage, CommMessage> moveIntoFolderFiles = (CommMessage msg) =>
{
if (msg.arguments.Count() == 1)localFileMgr.currentPath = msg.arguments[0];
reply.command = "moveIntoFolderFiles";
reply.arguments = localFileMgr.getFiles().ToList<string>();
return reply;
};
messageDispatcher["moveIntoFolderFiles"] = moveIntoFolderFiles;
Func<CommMessage, CommMessage> moveIntoFolderDirs = (CommMessage msg) =>
{
if (msg.arguments.Count() == 1)localFileMgr.currentPath = msg.arguments[0];
reply.command = "moveIntoFolderDirs";
reply.arguments = localFileMgr.getDirs().ToList<string>();
return reply;
};
messageDispatcher["moveIntoFolderDirs"] = moveIntoFolderDirs;
}
static void Main(string[] args)
{
Console.WriteLine("===========================this is the Repository============================");
Receiver receiver = new Receiver();
receiver.CreateHost("http://localhost:2017");
repository repo = new repository();
repo.initializeDispatcher();
while (true) //the repository will receive three kinds of message, with each kind of message, the repository
{ //will do different things.
CommMessage msg = receiver.GetMessage();
if (msg.Command == CommMessage.MessageCommand.getfiles) //command=getfiles, send the list of files'name to the Client
{
CommMessage reply = repo.messageDispatcher[msg.command](msg);
Sender sender = new Sender();
sender.CreateChannel("http://localhost:1234");
Console.WriteLine("\nsend list of files to the client!");
sender.PostMessage(reply);
}
else if (msg.Command == CommMessage.MessageCommand.Sendbuildrequest) //command=Sendbuildrequest, send the buildrequest to the mother builder and send a message to
{ //it to let it work(the work of the system is drived by message)
Console.WriteLine("\nreceive command to send build request to the mother builder,the build request is:{0}", msg.Body);
Sender sender1 = new Sender();
sender1.CreateChannel("http://localhost:9999");
Console.WriteLine("\nbuild request has send to the motherbuilder, the path is:{0}",Path.GetFullPath(@"..\..\..\motherstorage"));
sender1.postFile(msg.Body, RepoEnvironment.repostopath, 1024, @"..\..\..\motherstorage");
CommMessage msg1 = new CommMessage();
msg1.Destinaiton = "motherbuilder";
msg1.Source = "repo";
msg1.Body = msg.Body;
msg1.Command = CommMessage.MessageCommand.BuildRequest;
sender1.PostMessage(msg1);
}
else if (msg.Command == CommMessage.MessageCommand.requestfiles) //command=requestfiles,send the files that are needed to build to the child builder
{
Console.WriteLine("\nreceive file request from the child builder,the port is:{0}", msg.Source);
Console.WriteLine("\nsend the file to the child builder,the file is:{0},the path is:{1}",msg.Body,Path.GetFullPath(@"..\..\..\ChildBuilderstorage"));
Sender sender2 = new Sender();
sender2.CreateChannel("http://localhost:" + msg.Source);
sender2.postFile(msg.Body, RepoEnvironment.repostopath, 1024, @"..\..\..\ChildBuilderstorage");
}
}
}
}
}
|
ae821f424aa057ea956237ba7c89cac633f183f2
|
C#
|
zengxiding/Weick.Learn.Solution
|
/Redis/RedisHelper/Wdj.Redis.HelperTest/HashTest.cs
| 2.5625
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Wdj.Redis.Helper;
using Wdj.Redis.HelperTest.Model;
using System.Collections.Generic;
namespace Wdj.Redis.HelperTest
{
/// <summary>
/// Redis常用Hash数据类型 操作方法测试
/// </summary>
[TestClass]
public class HashTest
{
/// <summary>
/// 同步方法测试
/// </summary>
[TestMethod]
public void TestHashAction()
{
var redis = RedisHelper.HashService;
string key = "Test_HaskKey";
string listKey = "Test_HasklistKey";
string incrementKey = "Test_HaskIncrementKey";
UserModel user1 = new UserModel()
{
Age = 33,
Id = 1,
UserName = "Wdj"
};
UserModel user2 = new UserModel()
{
Age = 33,
Id = 2,
UserName = "Wang"
};
List<UserModel> userList = new List<UserModel>()
{
user1,user2
};
//添加
Assert.IsTrue(redis.HashSet<UserModel>(key, "user1", user1));
Assert.IsTrue(redis.HashSet<UserModel>(key, "user2", user2));
Assert.IsTrue(redis.HashSet(listKey, "userList", userList));
//是否存在
Assert.IsTrue(redis.HashExists(key, "user1"));
Assert.IsTrue(redis.HashExists(key, "user2"));
Assert.IsTrue(redis.HashExists(listKey, "userList"));
//获取
Assert.AreEqual(user1.Id, redis.HashGet<UserModel>(key, "user1").Id);
Assert.AreEqual(userList.Count, redis.HashGet<List<UserModel>>(listKey, "userList").Count);
//获取所有Key
Assert.AreEqual(2, redis.HashKeys(key).Length);
//获取所有Key与值
var dicList = redis.HashGetAll<UserModel>(key);
Assert.AreEqual(2, dicList.Count);
//递增,递减
Assert.AreEqual(1, redis.HashIncrement(incrementKey, "Increment"));
Assert.AreEqual(3, redis.HashIncrement(incrementKey, "Increment", 2));
Assert.AreEqual(2, redis.HashDecrement(incrementKey, "Increment"));
Assert.AreEqual(0, redis.HashDecrement(incrementKey, "Increment", 2));
//删除
Assert.IsTrue(redis.HashDelete(listKey, "userList"));
Assert.AreEqual(2, redis.HashDelete(key, "user2", "user1"));
}
/// <summary>
/// 异步方法测试
/// </summary>
[TestMethod]
public async Task TestHashAsync()
{
var redis = RedisHelper.HashService;
string key = "Test_HaskAsyncKey";
string listKey = "Test_HaskAsynclistKey";
string incrementKey = "Test_HaskAsyncIncrementKey";
UserModel user1 = new UserModel()
{
Age = 33,
Id = 1,
UserName = "Wdj"
};
UserModel user2 = new UserModel()
{
Age = 33,
Id = 2,
UserName = "Wang"
};
List<UserModel> userList = new List<UserModel>()
{
user1,user2
};
//添加
Assert.IsTrue(await redis.HashSetAsync<UserModel>(key, "user1", user1));
Assert.IsTrue(await redis.HashSetAsync<UserModel>(key, "user2", user2));
Assert.IsTrue(await redis.HashSetAsync(listKey, "userList", userList));
//是否存在
Assert.IsTrue(await redis.HashExistsAsync(key, "user1"));
Assert.IsTrue(await redis.HashExistsAsync(key, "user2"));
Assert.IsTrue(await redis.HashExistsAsync(listKey, "userList"));
//获取
Assert.AreEqual(user1.Id, (await redis.HashGetAsync<UserModel>(key, "user1")).Id);
Assert.AreEqual(userList.Count, (await redis.HashGetAsync<List<UserModel>>(listKey, "userList")).Count);
//获取所有Key
Assert.AreEqual(2, (await redis.HashKeysAsync(key)).Length);
//获取所有Key与值
var dicList = await redis.HashGetAllAsync<UserModel>(key);
Assert.AreEqual(2, dicList.Count);
//递增,递减
Assert.AreEqual(1, await redis.HashIncrementAsync(incrementKey, "Increment"));
Assert.AreEqual(3, await redis.HashIncrementAsync(incrementKey, "Increment", 2));
Assert.AreEqual(2, await redis.HashDecrementAsync(incrementKey, "Increment"));
Assert.AreEqual(0, await redis.HashDecrementAsync(incrementKey, "Increment", 2));
//删除
Assert.IsTrue(redis.HashDelete(listKey, "userList"));
Assert.AreEqual(2, redis.HashDelete(key, "user2", "user1"));
}
}
}
|
e09ef6e75bcc2f4eae3482e968787f49c35b9ac1
|
C#
|
sebastian-dev/SharpDX
|
/Source/SharpDX.Direct2D1/SvgDocument.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpDX.Direct2D1
{
public partial class SvgDocument
{
/// <summary>
/// Finds an svg element by id
/// </summary>
/// <param name="id">Id to lookup for</param>
/// <returns>SvgElement if found, null otherwise</returns>
public SvgElement FindElementById(string id)
{
SharpDX.Result __result__;
SvgElement svgElement;
__result__ = TryFindElementById_(id, out svgElement);
__result__.CheckError();
return svgElement;
}
}
}
|
32565cb242f46450bb78a8aafae2b33933e9c14d
|
C#
|
eternal1025/Demo
|
/QuantBox.Demo/Helper/TimeHelper.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuantBox.Demo.Helper
{
public enum EnumTradingTime
{
TradingTime_0915_1515, // 金融
TradingTime_0900_1515, // 金融
TradingTime_0900_1500, // 商品
TradingTime_2300,
TradingTime_2330,
TradingTime_0100,
TradingTime_0230, // 黄金、白银
}
public class TimeHelper
{
public int[] WorkingTime;
public int EndOfDay { get; private set; }
public int BeginOfDay { get; private set; }
public int[] WorkingTime_0915_1515 = { 915, 1130, 1300, 1515 }; //IF,TF,IO
public int[] WorkingTime_0900_1515 = { 900, 1130, 1300, 1515 }; //EF,AF
public int[] WorkingTime_0900_1500 = { 900, 1015, 1030, 1130, 1330, 1500 }; //商品
public int[] WorkingTime_2300 = { 900, 1015, 1030, 1130, 1330, 1500, 2100, 2300 };//天然橡胶
public int[] WorkingTime_2330 = { 900, 1015, 1030, 1130, 1330, 1500, 2100, 2330 };//白糖、棉花、菜粕、甲醇、PTA
public int[] WorkingTime_0100 = { 0, 100, 900, 1015, 1030, 1130, 1330, 1500, 2100, 2400 };//铜、铝、铅、锌
public int[] WorkingTime_0230 = { 0, 230, 900, 1015, 1030, 1130, 1330, 1500, 2100, 2400 };//au,ag,p,j
private int EndOfDay_1515 = 1515; //IF
private int EndOfDay_1500 = 1500; //商品
private int BeginOfDay_0900 = 900;
private int BeginOfDay_0915 = 915;
private int BeginOfDay_2100 = 2100;
public TimeHelper(EnumTradingTime tt)
{
switch (tt)
{
case EnumTradingTime.TradingTime_0915_1515:
WorkingTime = WorkingTime_0915_1515;
BeginOfDay = BeginOfDay_0915;
EndOfDay = EndOfDay_1515;
break;
case EnumTradingTime.TradingTime_0900_1515:
WorkingTime = WorkingTime_0900_1515;
BeginOfDay = BeginOfDay_0900;
EndOfDay = EndOfDay_1515;
break;
case EnumTradingTime.TradingTime_0900_1500:
WorkingTime = WorkingTime_0900_1500;
BeginOfDay = BeginOfDay_0900;
EndOfDay = EndOfDay_1515;
break;
case EnumTradingTime.TradingTime_2300:
WorkingTime = WorkingTime_2300;
BeginOfDay = BeginOfDay_2100;
EndOfDay = EndOfDay_1500;
break;
case EnumTradingTime.TradingTime_2330:
WorkingTime = WorkingTime_2330;
BeginOfDay = BeginOfDay_2100;
EndOfDay = EndOfDay_1500;
break;
case EnumTradingTime.TradingTime_0100:
WorkingTime = WorkingTime_0100;
BeginOfDay = BeginOfDay_2100;
EndOfDay = EndOfDay_1500;
break;
case EnumTradingTime.TradingTime_0230:
WorkingTime = WorkingTime_0230;
BeginOfDay = BeginOfDay_2100;
EndOfDay = EndOfDay_1500;
break;
}
}
public TimeHelper(string instrument)
: this(GetTradingTime(instrument))
{
}
public TimeHelper(int[] workingTime, int beginOfDay, int ennOfDay)
{
WorkingTime = workingTime;
BeginOfDay = beginOfDay;
EndOfDay = ennOfDay;
}
public override string ToString()
{
return string.Format("{0}", WorkingTime);
}
public static EnumTradingTime GetTradingTime(string instrument)
{
string prefix = instrument.Substring(0, 2);
switch (prefix)
{
case "IF":// 中金所 沪深300股指期货
case "TF":// 中金所 国债期货
case "IO":// 中金所 沪深300股指期权
case "IH":// 中金所 上证50股指期货
case "IC":// 中金所 中证500股指期货
case "HO":// 中金所 上证50股指期权
return EnumTradingTime.TradingTime_0915_1515;
case "EF":// 中金所 欧元兑美元期货
case "AF":// 中金所 澳元兑美元期货
return EnumTradingTime.TradingTime_0900_1515;
case "ru":// 上期所 天然橡胶
return EnumTradingTime.TradingTime_2300;
case "SR":// 郑商所 白糖
case "CF":// 郑商所 棉花
case "RM":// 郑商所 菜粕
case "ME":// 郑商所 甲醇 50吨每手
case "MA":// 郑商所 甲醇 10吨每手 1506开始
case "TA":// 郑商所 PTA
return EnumTradingTime.TradingTime_2330;
case "cu":// 上期所 铜
case "al":// 上期所 铝
case "pb":// 上期所 铅
case "zn":// 上期所 锌
case "rb":// 上期所 螺纹纲
case "hc":// 上期所 热轧卷板
case "bu":// 上期所 石油沥青
return EnumTradingTime.TradingTime_0100;
case "au":// 上期所 黄金
case "ag":// 上期所 白银
case "jm":// 大商所 焦煤
return EnumTradingTime.TradingTime_0230;
default:
prefix = instrument.Substring(0, 1);
switch (prefix)
{
case "p":// 大商所 棕榈油
case "j":// 大商所 焦炭
case "a":// 大商所 黄大豆一号
case "b":// 大商所 黄大豆二号
case "m":// 大商所 豆粕
case "y":// 大商所 豆油
case "i":// 大商所 铁矿石
return EnumTradingTime.TradingTime_0230;
default:
return EnumTradingTime.TradingTime_0900_1500;
}
}
}
public bool IsTradingTime(int time)
{
int index = -1;
for (int i = 0; i < WorkingTime.Length; ++i)
{
if (time < WorkingTime[i])
{
break;
}
else
{
index = i;
}
}
if (index % 2 == 0)
{
// 交易时段
return true;
}
// 非交易时段
return false;
}
public int GetNextTradingTime(int time)
{
int index = -1;
for (int i = 0; i < WorkingTime.Length; ++i)
{
if (time < WorkingTime[i])
{
break;
}
else
{
index = i;
}
}
if (index % 2 == 0)
{
// 交易时段
return time;
}
if (index+1 >= WorkingTime.Length)
return WorkingTime[0];
// 非交易时段
return WorkingTime[index+1];
}
public DateTime GetNextTradingTime(DateTime dt)
{
int time1 = GetTime(dt);
int time2 = GetNextTradingTime(time1);
if(time1 == time2)
{
return dt;
}
else if(time2>time1)
{
return dt.Date.AddHours((int)(time2 / 100)).AddMinutes(time2 % 100);
}
else
{
return dt.Date.AddDays(1).AddHours((int)(time2 / 100)).AddMinutes(time2 % 100);
}
}
public static int GetTime(DateTime dt)
{
return dt.Hour * 100 + dt.Minute;
}
public static int GetDate(DateTime dt)
{
return dt.Year * 10000 + dt.Month * 100 + dt.Day;
}
public bool IsTradingTime(DateTime dt)
{
return IsTradingTime(GetTime(dt));
}
}
}
|
167c3b944c66401fce76f31ebe0643929617366d
|
C#
|
apiad/SciSharp
|
/Source/SciSharp/Numerics/DifferentialFunctions.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
namespace SciSharp.Numerics
{
//TODO : Step Size Control
// Implementar Step Size Control.
// IDEA: Usar un delegate para computar el siguiente step.
//TODO : Chequear si OperateOnNew == true
// Modificar los métodos en consecuencia.
//TODO: Chequear si UseParallelOptimizations = true
// Modificar los métodos en consecuencia.
// Creo que esto va mejor en Matrix y Vector.
/// <summary>
/// Contiene implementaciones para solvers de ecuaciones diferenciales.
/// </summary>
public static class DifferentialFunctions
{
private static IEnumerable<Vector> SolveInternal(DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod method)
{
Debug.Post("DifferentialEquations.Solve (SingleStep)");
Debug.Indent();
Debug.Post("Dimension = {0}.", y.Dimension);
Debug.Unindent();
while (true)
{
y = method(function, x, y, step);
x += step;
yield return y;
}
}
private static IEnumerable<Vector> SolveInternal(DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod starter, MultiStepMethod method,
int iterations)
{
Debug.Post("DifferentialEquations.Solve (MultiStep)");
Debug.Indent();
Debug.Post("Dimension = {0}.", y.Dimension);
var values = new Vector[iterations];
for (int i = 0; i < iterations; i++)
{
y = starter(function, x, y, step);
values[iterations - i - 1] = y;
x += step;
yield return y;
}
while (true)
{
Vector result = method(function, x, values, step);
for (int j = values.Length - 1; j >= 1; j--)
values[j] = values[j - 1];
values[0] = result;
x += step;
yield return result;
}
}
private static IEnumerable<Vector> SolveInternal(DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod predictor, SingleStepCorrector corrector,
int iterations)
{
Debug.Post("DifferentialEquations.Solve (Predictor-Corrector)");
Debug.Indent();
Debug.Post("Dimension = {0}.", y.Dimension);
Debug.Unindent();
while (true)
{
Vector yIter = predictor(function, x, y, step);
for (int j = 0; j < iterations; j++)
{
Vector result = corrector(function, x, y, yIter, step);
yIter = result;
if ((result - yIter).Length < Engine.Epsilon)
break;
}
yield return yIter;
y = yIter;
x += step;
}
}
private static IEnumerable<Vector> SolveInternal(DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod starter, MultiStepMethod predictor,
MultiStepMethod corrector,
int starterIterations, int iterations)
{
throw new NotImplementedException();
}
private static IEnumerable<Vector> SolveInternal(Integrator integrator, DifferentialFunction function, double x0,
Vector y0, double step)
{
while (true)
{
yield return y0;
y0 = integrator(function, x0, y0, step);
x0 += step;
}
}
public static DifferentialSolution Solve(this DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod method)
{
return new DifferentialSolution(SolveInternal(function, x, y, step, method));
}
public static DifferentialSolution Solve(this DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod starter, MultiStepMethod method, int iterations)
{
return new DifferentialSolution(SolveInternal(function, x, y, step, starter, method, iterations));
}
public static DifferentialSolution Solve(this DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod predictor, SingleStepCorrector corrector,
int iterations)
{
return new DifferentialSolution(SolveInternal(function, x, y, step, predictor, corrector, iterations));
}
public static DifferentialSolution Solve(this DifferentialFunction function, double x, Vector y, double step,
SingleStepMethod starter, MultiStepMethod predictor,
MultiStepMethod corrector,
int starterIterations, int iterations)
{
return
new DifferentialSolution(SolveInternal(function, x, y, step, starter, predictor, corrector,
starterIterations, iterations));
}
public static DifferentialSolution Solve(this Integrator integrator, DifferentialFunction function, double x,
Vector y, double step)
{
return new DifferentialSolution(SolveInternal(integrator, function, x, y, step));
}
}
}
|
4c1085cdbdf98d858ef566e583d1b1dd626e2a32
|
C#
|
rogeralexandre/visconde-de-sabugosa
|
/EFCore_LogSQL/EFCore_LogSQL/AppDBContext.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using EFCore_LogSQL.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace EFCore_LogSQL
{
public class AppDBContext : DbContext
{
public DbSet<Autor> Autores { get; set; }
public DbSet<Livro> Livros { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//"Data Source = MACORATTI; " + "Initial Catalog=DemoDB;Integrated Security=True"
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Macoratti;Trusted_Connection=True;MultipleActiveResultSets=true");
optionsBuilder.UseLoggerFactory(new LoggerFactory().AddConsole((category, level) => level == LogLevel.Information &&
category == DbLoggerCategory.Database.Command.Name, true));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//------entidade Autor--------------------
modelBuilder.Entity<Autor>().HasKey(a => a.AutorId);
modelBuilder.Entity<Autor>()
.Property(p => p.Nome)
.HasMaxLength(100)
.IsRequired();
modelBuilder.Entity<Autor>()
.Property(p => p.Email)
.HasMaxLength(200)
.IsRequired();
//------entidade Livro--------------------
modelBuilder.Entity<Livro>().HasKey(a => a.LivroId);
modelBuilder.Entity<Livro>()
.Property(p => p.Titulo)
.HasMaxLength(200)
.IsRequired();
//um-para-muitos : Livros - Autor
modelBuilder.Entity<Livro>()
.HasOne<Autor>(s => s.Autor)
.WithMany(g => g.Livros)
.HasForeignKey(s => s.AutorId);
}
}
}
|
ec78f286f8d1a2879c28836759e78da86de68a17
|
C#
|
IT-rolling-out/IRO
|
/src/Storage/IRO.Storage/DefaultStorages/BaseStorage.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using IRO.Storage.Data;
using IRO.Storage.Exceptions;
using NeoSmart.AsyncLock;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace IRO.Storage.DefaultStorages
{
/// <summary>
/// Base class for all <see cref="IKeyValueStorage"/> implementions.
/// </summary>
public abstract class BaseStorage : IKeyValueStorage
{
public const char ScopeSplitter = '.';
readonly AsyncLock _lock = new AsyncLock();
public async Task Clear()
{
await UsingLock(async () =>
{
await InnerClear();
});
}
public async Task<bool> ContainsKey(string key)
{
ThrowIfBadKey(key);
return await UsingLock(async () =>
{
var str = await InnerGet(key);
return str != null;
});
}
public async Task<object> Get(Type type, string key)
{
var jToken = await Get(key);
return jToken?.ToObject(type);
}
public async Task<JToken> Get(string key)
{
return await GetWithoutLock(key);
}
public async Task Set(string key, object value)
{
await Remove(key);
ThrowIfBadKey(key);
await UsingLock(async () =>
{
var isScope = key.Contains(ScopeSplitter);
if (isScope)
{
var keyValuesToSave = new Dictionary<string, object>();
var scopesHierarchy = key.Split(ScopeSplitter);
var toNum = scopesHierarchy.Length - 1;
var scopeName = "";
for (var i = 0; i < toNum; i++)
{
try
{
scopeName += scopesHierarchy[i];
var scope = await GetScopeFromStorageOrCreate(scopeName);
scope.AddKey(scopesHierarchy[i + 1]);
keyValuesToSave[scopeName] = scope;
scopeName += ScopeSplitter;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
//Save all.
foreach (var item in keyValuesToSave)
{
await SetObject(item.Key, item.Value);
}
}
await SetObject(key, value);
});
}
public async Task Remove(string key)
{
ThrowIfBadKey(key);
await UsingLock(async () =>
{
var keyValuesToSave = new Dictionary<string, object>();
await RemoveScopeChildren(key, keyValuesToSave);
await RemoveObjectFromParentScopes(key, keyValuesToSave);
//Remove upper scopes if empty and value at this point.
foreach (var item in keyValuesToSave)
{
if (item.Value == null)
{
await InnerRemove(item.Key);
}
else
{
await SetObject(item.Key, item.Value);
}
}
await InnerRemove(key);
});
}
#region Protected abstract.
/// <summary>
/// Return string value or null if not contains (or removed).
/// </summary>
protected abstract Task<string> InnerGet(string key);
protected abstract Task InnerSet(string key, string strValue);
/// <summary>
/// Removed keys return null, just like undefined keys do.
/// </summary>
protected abstract Task InnerRemove(string key);
protected abstract Task InnerClear();
#endregion
#region Private.
/// <summary>
/// Not directly apply changes, just save them to buffer dict.
/// </summary>
async Task RemoveScopeChildren(string key, IDictionary<string, object> keyValuesToSave)
{
var jToken = await GetAndParseToJToken(key);
if (IsScopeModel(jToken))
{
var scopeCasted = jToken.ToObject<StorageScopeModel>();
foreach (var innerKey in scopeCasted.ScopeKeys)
{
var fullInnerKey = $"{key}{ScopeSplitter}{innerKey}";
keyValuesToSave[fullInnerKey] = null;
await RemoveScopeChildren(fullInnerKey, keyValuesToSave);
}
}
}
/// <summary>
/// Not directly apply changes, just save them to buffer dict.
/// </summary>
async Task RemoveObjectFromParentScopes(string key, IDictionary<string, object> keyValuesToSave)
{
var (scopeFullName, innerKeyName) = RemoveLastScope(key);
bool removeFromParentScope = true;
while (scopeFullName != null)
{
try
{
var scope = await GetScopeFromStorageOrCreate(scopeFullName);
if (removeFromParentScope)
{
scope.RemoveKey(innerKeyName);
removeFromParentScope = !scope.ScopeKeys.Any();
}
//Remove scope if null.
keyValuesToSave[scopeFullName] = scope.ScopeKeys.Any() ? scope : null;
(scopeFullName, innerKeyName) = RemoveLastScope(scopeFullName);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
public async Task<JToken> GetWithoutLock(string key)
{
ThrowIfBadKey(key);
if (!await ContainsKey(key))
{
throw new Exception($"Storage not contains key '{key}'");
}
var jToken = await GetAndParseToJToken(key);
if (IsScopeModel(jToken))
{
var scopeCasted = jToken.ToObject<StorageScopeModel>();
var scopeWithValues = new JObject();
foreach (var innerKey in scopeCasted.ScopeKeys)
{
var fullInnerKey = $"{key}{ScopeSplitter}{innerKey}";
var val = await GetWithoutLock(fullInnerKey);
scopeWithValues[innerKey] = val;
}
return scopeWithValues;
}
else
{
return jToken;
}
}
(string ScopeFullName, string InnerKeyName) RemoveLastScope(string key)
{
var index = key.LastIndexOf(ScopeSplitter);
if (index <= 0)
return (null, key);
var scopeFullName = key.Remove(index);
var innerKeyName = key.Substring(index + 1);
return (scopeFullName, innerKeyName);
}
void ThrowIfBadKey(string key)
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Bad key.", nameof(key));
}
}
bool IsScopeModel(JToken jToken)
{
try
{
if (jToken == null)
return false;
return jToken[nameof(StorageScopeModel.IsStorageScopeModel)].ToObject<bool>();
}
catch
{
return false;
}
}
async Task<T> UsingLock<T>(Func<Task<T>> func)
{
using (await _lock.LockAsync())
{
try
{
return await func();
}
catch (Exception ex)
{
throw new StorageException("", ex);
}
}
}
async Task UsingLock(Func<Task> func)
{
using (await _lock.LockAsync())
{
try
{
await func();
}
catch (Exception ex)
{
throw new StorageException("", ex);
}
}
}
async Task<JToken> GetAndParseToJToken(string key)
{
var jsonStr = await InnerGet(key);
//When not contains.
if (jsonStr == null)
{
return null;
}
//When was set value 'null'.
if (jsonStr.Trim() == "null")
{
return null;
}
return JToken.Parse(jsonStr);
}
async Task SetObject(string key, object value)
{
var jsonStr = JsonConvert.SerializeObject(value);
await InnerSet(key, jsonStr);
}
async Task<StorageScopeModel> GetScopeFromStorageOrCreate(string scopeName)
{
var jToken = await GetAndParseToJToken(scopeName);
if (IsScopeModel(jToken))
{
return jToken.ToObject<StorageScopeModel>();
}
return new StorageScopeModel();
}
#endregion
}
}
|
9dc0abcd0d5e21bddf05e4343dc37a6bc4847ca7
|
C#
|
xy19xiaoyu/TG
|
/Cpic.Demo/ParseXml/CnIndexExtract.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace ParseXml
{
public class CnIndexExtract
{
//获得专利文献申请号
public String getApplyNo(XDocument xRoot)
{
String value = String.Empty;
try
{
if (xRoot.Root.Name == "Patent")
{
var nodes =
from el in xRoot.Descendants("APNNO")
select el;
value = nodes.First().Value.Trim();
}
else
{
var nodes =
from el in xRoot.Descendants("doc-filing_no")
select el;
value = nodes.First().Value.Trim().Substring(0, 12);
}
if (value == String.Empty)
{
throw new Exception("获得专利文献申请号出错");
}
}
catch (Exception e)
{
throw new Exception("获得专利文献申请号出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献申请日
public String getApplyDate(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("APD")
select el;
foreach (var node in nodes)
{
String ApplyDate = node.Value.Trim();
if (ApplyDate != "")
{
value = value + ";" + ApplyDate;
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("获得专利文献申请日出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献联系地址
public String getAddress(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("ADDRESS")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献联系地址出错:" + e.Message);
}
return value.Trim();
}
////获得专利文献公开公告号
//public String getPublicAnnouncementNo(XDocument xRoot)
//{
// String value = String.Empty;
// try
// {
// var PUBNR =
// from el in xRoot.Descendants("PUBNR")//公开号
// select el;
// var APPNR =
// from el in xRoot.Descendants("APPNR")//公告号
// select el;
// if (PUBNR.Count() > 0)
// {
// String pubno = PUBNR.First().Value.Trim();
// if (pubno!="0000000")
// {
// value = pubno;
// }
// }
// if (APPNR.Count() > 0)
// {
// String appno = APPNR.First().Value.Trim();
// if (appno != "0000000")
// {
// if (value == String.Empty)
// {
// value = appno;
// }
// else
// {
// value = value + ";" + appno;
// }
// }
// }
// }
// catch (Exception e)
// {
// throw new Exception("获得专利文献公开号出错:" + e.Message);
// }
// return value.Trim();
//}
//获得专利文献公开号
public String getPublicNo(XDocument xRoot)
{
String value = String.Empty;
try
{
var PUBNR =
from el in xRoot.Descendants("PUBNR")//公开号
select el;
if (PUBNR.Count() > 0)
{
String pubno = PUBNR.First().Value.Trim();
if (!Regex.IsMatch(pubno, @"^0{1,}$"))
{
value = pubno;
}
}
}
catch (Exception e)
{
throw new Exception("获得专利文献公开号出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献公告号
public String getAnnouncementNo(XDocument xRoot)
{
String value = String.Empty;
try
{
var APPNR =
from el in xRoot.Descendants("APPNR")//公告号
select el;
if (APPNR.Count() > 0)
{
String ann = APPNR.First().Value.Trim();
if (!Regex.IsMatch(ann, @"^0{1,}$"))
{
value = ann;
}
}
}
catch (Exception e)
{
throw new Exception("获得专利文献公告号出错:" + e.Message);
}
return value.Trim();
}
////获得专利文献公开公告日
//public String getPublicAnnouncementDate(XDocument xRoot)
//{
// String value = String.Empty;
// try
// {
// String publicDate = String.Empty;
// var PUD =
// from el in xRoot.Descendants("PUD")//公开日
// select el;
// var APPD =
// from el in xRoot.Descendants("APPD")//公告日
// select el;
// if (PUD.Count() > 0)
// {
// publicDate = PUD.First().Value.Trim();
// if (publicDate != "")
// {
// publicDate = FormatUtil.FormatDate(publicDate);
// value = publicDate;
// }
// }
// if (APPD.Count() > 0)
// {
// String announceDate = APPD.First().Value.Trim();
// if (announceDate != "")
// {
// announceDate = FormatUtil.FormatDate(announceDate);
// if (value == String.Empty)
// {
// value = announceDate;
// }
// else
// {
// value = value + ";" + announceDate;
// }
// }
// }
// }
// catch (Exception e)
// {
// throw new Exception("获得专利文献公开公告日出错:" + e.Message);
// }
// return value.Trim();
//}
//获得专利文献公开日
public String getPublicDate(XDocument xRoot)
{
String value = String.Empty;
try
{
String publicDate = String.Empty;
var PUD =
from el in xRoot.Descendants("PUD")//公开日
select el;
if (PUD.Count() > 0)
{
publicDate = PUD.First().Value.Trim();
if (publicDate != "")
{
value = publicDate;
}
}
}
catch (Exception e)
{
throw new Exception("获得专利文献公开日出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献公告日
public String getAnnouncementDate(XDocument xRoot)
{
String value = String.Empty;
try
{
String annDate = String.Empty;
var APPD =
from el in xRoot.Descendants("APPD")//公告日
select el;
if (APPD.Count() > 0)
{
annDate = APPD.First().Value.Trim();
if (annDate != "")
{
value = annDate;
}
}
}
catch (Exception e)
{
throw new Exception("获得专利文献公告日出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献优先权号
public String getPriorNo(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PRI")
select el;
foreach (var node in nodes)
{
var country = node.Descendants("CO");
var no = node.Descendants("NR");
if (country.Count() > 0)
{
value = value + ";" + country.First().Value.Trim();
}
if (no.Count() > 0)
{
if (country.Count() == 0)
{
value = value + ";" + no.First().Value.Trim();
}
else
{
value = value + no.First().Value.Trim();
}
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("获得专利文献优先权号出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献优先权号
public String getPriorNo1(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PRI")
select el;
foreach (var node in nodes)
{
var country = node.Descendants("CO");
var no = node.Descendants("NR");
var date = node.Descendants("DATE");
if (country.Count() > 0)
{
value = value + ";" + country.First().Value.Trim();
}
if (date.Count() > 0)
{
if (country.Count() == 0)
{
value = value + ";" + date.First().Value.Trim();
}
else
{
value = value + " " +date.First().Value.Trim();
}
}
if (no.Count() > 0)
{
value = value + " [" + no.First().Value.Trim() + "]";
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("获得专利文献优先权号出错:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// PCT进入国家日期
/// </summary>
/// <param name="xRoot"></param>
/// <returns></returns>
public String getPCT_PstDA(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PCT")
select el;
foreach (var node in nodes)
{
var PSTDA = node.Descendants("PSTDA");
if (PSTDA.Count() > 0)
{
value = PSTDA.First().Value.Trim();
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("PCT进入国家日期:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// PCT国际申请日
/// </summary>
/// <param name="xRoot"></param>
/// <returns></returns>
public String getPCT_PCTDA(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PCT")
select el;
foreach (var node in nodes)
{
var PSTDA = node.Descendants("PCTDA");
if (PSTDA.Count() > 0)
{
value = PSTDA.First().Value.Trim();
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("PCT国际申请日:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// PCT国际申请号
/// </summary>
/// <param name="xRoot"></param>
/// <returns></returns>
public String getPCT_PCTNO(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PCT")
select el;
foreach (var node in nodes)
{
var PSTDA = node.Descendants("PCTNO");
if (PSTDA.Count() > 0)
{
value = PSTDA.First().Value.Trim();
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("PCT国际申请:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// PCT国际公布号
/// </summary>
/// <param name="xRoot"></param>
/// <returns></returns>
public String getPCT_PPBDO(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PCT")
select el;
foreach (var node in nodes)
{
var PSTDA = node.Descendants("PPBDO");
if (PSTDA.Count() > 0)
{
value = PSTDA.First().Value.Trim();
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("PCT国际公布号:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// PCT国际公布日
/// </summary>
/// <param name="xRoot"></param>
/// <returns></returns>
public String getPCT_PPBDA(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PCT")
select el;
foreach (var node in nodes)
{
var PSTDA = node.Descendants("PPBDA");
if (PSTDA.Count() > 0)
{
value = PSTDA.First().Value.Trim();
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("PCT国际公布日:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// PCT公布语言
/// </summary>
/// <param name="xRoot"></param>
/// <returns></returns>
public String getPCT_PLANG(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("PCT")
select el;
foreach (var node in nodes)
{
var PSTDA = node.Descendants("PLANG");
if (PSTDA.Count() > 0)
{
value = PSTDA.First().Value.Trim();
}
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("PCT公布语言:" + e.Message);
}
return value.Trim();
}
//获得专利文献主权利要求
public String getMainClaim(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("CLAIM")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献主权利要求出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献权利要求
public String getClaims(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("claims").Descendants("claim").Descendants("claim-text")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献权利要求出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献说明书
public String getDescription(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("description").Descendants("p")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献说明书出错:" + e.Message);
}
return value.Trim();
}
//获得邮政编码
public String getZip(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("ZIP")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得邮政编码出错:" + e.Message);
}
return value.Trim();
}
//获得授权日
public String getGrantDate(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("GRD")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得授权日出错:" + e.Message);
}
return value.Trim();
}
//获得授权公告日
public String getGrantPubDate(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("GRPD")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得授权公告日出错:" + e.Message);
}
return value.Trim();
}
//获得代理机构代码
public String getAgentCode(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("AGENCY")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得代理机构代码出错:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// 代理人信息
/// </summary>
/// <param name="xRoot"></param>
/// <returns></returns>
public String getAgents(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("AGENT")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得代理人出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献申请人
public String getApply(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("APPL")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献申请人出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献发明人
public String getInventor(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("INVENTOR")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献发明人出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献关键字
public String getKeyWord(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("KEYWORD")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献关键字出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献主IPC
public String getMainIPC(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("IPC")
select el;
if (nodes.Count() > 0)
{
value = nodes.First().Value;
}
}
catch (Exception e)
{
throw new Exception("获得专利文献主IPC出错:" + e.Message);
}
value = value.PadRight(12, ' ');
return value.Trim();
}
//获得专利文献IPC
public String getIPC(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("IPC")
select el;
foreach (var node in nodes)
{
String ipc = node.Value.Trim();
value = value + ";" + ipc;
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("获得专利文献IPC出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献发明名称
public String getTitle(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("TITLE")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献发明名称出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献代理机构代码
public String getAgency(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("AGENCY")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("获得专利文献代理机构代码出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献范畴分类号
public String getField(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("FIELDC")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("获得专利文献范畴分类号出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献省市代码
public String getProvinceCode(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("NC")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
}
catch (Exception e)
{
throw new Exception("获得专利文献省市代码出错:" + e.Message);
}
return value.Trim();
}
//获得专利文献摘要
public String getAbstract(XDocument xRoot)
{
String value = String.Empty;
try
{
var nodes =
from el in xRoot.Descendants("ABSTR")
select el;
foreach (var node in nodes)
{
value = value + ";" + node.Value.Trim();
}
value = RemoveFirstSpliter(value);
value = value.Replace("|", " ");
value = value.Replace("\n", " ");
}
catch (Exception e)
{
throw new Exception("获得专利文献摘要出错:" + e.Message);
}
return value.Trim();
}
/// <summary>
/// 获得中文全文索引信息(nData_Index_Full1_YYMMDD)
/// </summary>
/// <param name="xRoot"></param>
/// <returns>权利要求</returns>
public String getFullIndex_Claim(XDocument xRoot)
{
String value = String.Empty;
try
{
String claim = getClaims(xRoot);
claim = claim.Replace("\r", " ");
claim = claim.Replace("\n", " ");
return claim;
}
catch (Exception e)
{
throw new Exception("获得中文全文索引信息(nData_Index_Full1_YYMMDD)出错:" + e.Message);
}
}
/// <summary>
/// 获得中文全文索引信息(nData_Index_Full2_YYMMDD)
/// </summary>
/// <param name="xRoot"></param>
/// <returns>说明书</returns>
public String getFullIndex_Description(XDocument xRoot)
{
String value = String.Empty;
try
{
String des = getDescription(xRoot);
des = des.Replace("\r", " ");
des = des.Replace("\n", " ");
return des;
}
catch (Exception e)
{
throw new Exception("获得中文全文索引信息(nData_Index_Full2_YYMMDD)出错:" + e.Message);
}
}
//去掉字符串的第一个分隔符
public String RemoveFirstSpliter(String str)
{
if (str.Trim() == "" || str == String.Empty)
{
return str;
}
if (str.StartsWith(";"))
{
return str.Substring(1);
}
else
{
throw new Exception(str + "第一个字符不是分隔符");
}
}
}
}
|
26139067669ce4c5bf960b6c81f0e8d6937c5f75
|
C#
|
kieranajp/scm-simulator-2017
|
/Assets/Scripts/PlayerLevel/CharacterSpawner.cs
| 2.78125
| 3
|
using Player;
using UnityEngine;
namespace PlayerLevel
{
public class CharacterSpawner : MonoBehaviour
{
public Transform[] SpawningPoints;
public GameObject[] Characters;
private int _numberOfPlayers;
private void Start()
{
_numberOfPlayers = FindObjectOfType<Game>().NumberOfPlayers;
for (var i = 1; i <= _numberOfPlayers; i++)
{
var playerCharacter = Game.PlayerCharacters[i.ToPlayer()];
InstantiateCharacter(Characters[playerCharacter - 1], SpawningPoints[i - 1].position, i.ToPlayer());
}
}
private void InstantiateCharacter(GameObject go, Vector3 spawningPoint, Player.Player player)
{
var character = Instantiate(go, spawningPoint, Quaternion.identity);
var playerBehaviour = character.GetComponent<PlayerBehaviour>();
playerBehaviour.Player = player;
}
}
}
|
4d4ba835d20e06a28bd6db6a63089bc4a6ed126a
|
C#
|
769634216/Tomb
|
/tomb/Assets/Ancient Modular Tombs/Scripts/Controller/Other/Move.cs
| 2.671875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public enum MoveType
{
Once,
Loop,
PingPong
}
public enum PositionType
{
World,
Local
}
public class Move : MonoBehaviour
{
public Vector3 startPosition;//开始的位置
public Vector3 endPosition;//结束的位置
public float time = 1;//移动的时间
private float timer; //移动的计时
private float percent;//移动的百分比
private bool isMoving = false;//是否在移动中
public MoveType moveType = MoveType.Once;
public PositionType positionType = PositionType.Local;
public UnityEvent onMoveEnd;
public bool moveOnAwake = false;
public float delayTime = 0;
private float delayTimer = 0;
private void Awake()
{
if (moveOnAwake)
{
StartMove();
}
}
private void Update()
{
if (isMoving)
{
CaculateMove();
}
}
public void StartMove()
{
isMoving = true;
timer = 0;
}
private void CaculateMove()
{
//处于延迟时间内
if(delayTimer < delayTime)
{
delayTimer += Time.deltaTime;
return;
}
timer += Time.deltaTime / time;
//percent = timer / time;
switch (moveType)
{
case MoveType.Once:
percent = Mathf.Clamp01(timer);//百分比限制在0到1之间
break;
case MoveType.Loop:
percent = Mathf.Repeat(timer,1);//timer大于1时从0开始
break;
case MoveType.PingPong:
percent = Mathf.PingPong(timer, 1);//timer大于1时从1返回
break;
}
MoveExcute();
if( timer >= 1 && moveType == MoveType.Once)
{
isMoving = false;
timer = 0;
onMoveEnd?.Invoke();
}
}
private void MoveExcute()
{
switch (positionType)
{
case PositionType.World:
transform.position = Vector3.Lerp(startPosition, endPosition, percent);
break;
case PositionType.Local:
transform.localPosition = Vector3.Lerp(startPosition, endPosition, percent);
break;
}
}
}
|
34b64acc205af525a6da66f6b8452c4b94169248
|
C#
|
andymasteroffish/Deck-Com
|
/deck-com/Assets/scripts/monobehaviors/UnitManager.cs
| 2.609375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System.Xml;
using System.IO;
public class UnitManager : MonoBehaviour {
public static UnitManager instance = null;
//public TextAsset xmlText;
//private XmlDocument fullXML;
[System.NonSerialized]
public XmlNodeList playerNodes, foeNodes;
void Awake(){
if (instance == null) {
instance = this;
} else if (instance != this) {
Destroy (gameObject);
}
XmlDocument foeXML = new XmlDocument ();
foeXML.Load(Application.dataPath + "/external_data/foes/units.xml");
XmlDocument playerXML = new XmlDocument ();
playerXML.Load(Application.dataPath + "/external_data/player/player_info.xml");
foeNodes = foeXML.GetElementsByTagName ("unit");
playerNodes = playerXML.GetElementsByTagName ("unit");
}
public Unit getUnitFromIdName(string idName){
foreach (XmlNode node in foeNodes) {
if (node.Attributes ["idName"].Value == idName) {
return getUnitFromNode (node);
}
}
foreach (XmlNode node in playerNodes) {
if (node.Attributes ["idName"].Value == idName) {
return getUnitFromNode (node);
}
}
Debug.Log ("COULD NOT FIND UNIT ID: " + idName);
return null;
}
public Unit getUnitFromNode(XmlNode node){
Unit unit = new Unit (node);
return unit;
}
public List<Unit> getActivePlayerUnits(){
List<Unit> playerUnits = new List<Unit> ();
foreach (XmlNode node in playerNodes) {
if (bool.Parse(node["currently_active"].InnerText) == true) {
playerUnits.Add( new Unit(node) );
}
}
return playerUnits;
}
}
|
462cfeee8233aac705b6f68c598ee5ac5aae1072
|
C#
|
AronThomasMiller/UnitTests
|
/Task/JsonPersonsWriter.cs
| 3.25
| 3
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task
{
public class JsonPersonsWriter : IPersonWriter
{
public void AddPeople(List<Person> people)
{
string Json = "[{'FirstName': 'Tom' ,'LastName': 'Cruz' },{ 'FirstName': 'Anton' ,'LastName': 'Zill'}]";
List<Person> deserializedProduct = JsonConvert.DeserializeObject<List<Person>>(Json);
foreach (var person in people)
{
deserializedProduct.Add(person);
}
string output = JsonConvert.SerializeObject(deserializedProduct);
}
public List<Person> Delete(string Id)
{
string Json = "[{'FirstName': 'Tom' ,'LastName': 'Cruz' },{ 'FirstName': 'Anton' ,'LastName': 'Zill'}]";
List<Person> deserializedProduct = JsonConvert.DeserializeObject<List<Person>>(Json);
var itemToDelete = deserializedProduct.Where(x => x.Id == Id).Select(x => x).First();
deserializedProduct.Remove(itemToDelete);
string output = JsonConvert.SerializeObject(deserializedProduct);
List<Person> resultProduct = JsonConvert.DeserializeObject<List<Person>>(Json);
return resultProduct;
}
public void Update(string Id, string NewFirstName, string NewLastName)
{
string Json = "[{'FirstName': 'Tom' ,'LastName': 'Cruz' },{ 'FirstName': 'Anton' ,'LastName': 'Zill'}]";
Person p = new Person();
List<Person> deserializedProduct = JsonConvert.DeserializeObject<List<Person>>(Json);
foreach (var person in deserializedProduct)
{
if (person.Id == Id)
{
person.FirstName = NewFirstName;
person.LastName = NewLastName;
p = person;
}
}
string output = JsonConvert.SerializeObject(deserializedProduct);
}
List<Person> IPersonWriter.AddPerson(Person person)
{
string Json = "[{'FirstName': 'Tom' ,'LastName': 'Cruz' },{ 'FirstName': 'Anton' ,'LastName': 'Zill'}]";
List<Person> deserializedProduct = JsonConvert.DeserializeObject<List<Person>>(Json);
deserializedProduct.Add(person);
string output = JsonConvert.SerializeObject(deserializedProduct);
List<Person> resultProduct = JsonConvert.DeserializeObject<List<Person>>(Json);
return resultProduct;
}
}
}
|
92e24c4a7e52f21761db1a95ed98a429284043db
|
C#
|
muzudho/Kifuwarabe_Igo_Unity_Think
|
/Kifuwarabe_Unity/source/n850_print___/n850_500_boardViewImpl.cs
| 2.578125
| 3
|
using Grayscale.Kifuwarabe_Igo_Unity_Think.n190_board___;
namespace Grayscale.Kifuwarabe_Igo_Unity_Think.n850_print___
{
public class BoardViewImpl
{
/// <summary>
///
/// </summary>
/// <param name="pBoard"></param>
public static void PrintBoard(Board board)
{
string[] str = new string[4]{
"・", // 空き
"●", // 黒石
"○", // 白石
"+" // 枠
};
board.ForeachAllXyWithWaku((int x, int y, ref bool isBreak) =>{
int node = AbstractTable<Color>.ConvertToNode(x, y);
System.Console.Write(string.Format("{0}", str[(int)board.ValueOf(node)]));
if (x == board.GetBoardSize() + 1)
{
System.Console.Write(string.Format("\n"));//改行☆
}
});
}
}
}
|
be08dbea1765f4e464809696816f8b40434fafcb
|
C#
|
HexaLopata-T/DandLRemake
|
/DandLRemake/Program.cs
| 3.09375
| 3
|
using DandLRemake.Items;
using System;
namespace DandLRemake
{
class Program
{
public static void Main()
{
GameController controller = new GameController();
controller.Start(controller.GenerateRandomEnemy());
while(true)
{
controller.PlayTurn();
if (controller.player.IsDead)
{
controller.GameOver();
Console.WriteLine("\nПродолжить? д/н");
char answer = Console.ReadKey().KeyChar;
if(answer == 'д' | answer == 'l' | answer == 'Д' | answer == 'L')
{
controller = new GameController();
controller.GenerateRandomAction();
Console.WriteLine("\nНовая игра создана");
Console.ReadKey();
}
else
{
break;
}
}
else
{
controller.GenerateRandomAction();
}
controller.Update();
}
}
}
}
|
95cca9d6229269956a701a2e813ee2cb9a5baec9
|
C#
|
9045857/Academits
|
/OOPTasks/Graph/graph.cs
| 3.546875
| 4
|
using System;
using System.Collections.Generic;
namespace Graph
{
class Graph
{
private int[,] graph;
public Graph(int[,] graph)
{
if (graph.GetLength(0) != graph.GetLength(1))
{
throw new ArgumentException("ОШИБКА: конструктору графа передана не квадратная матрица связнности");
}
Count = graph.GetLength(0);
this.graph = Get2DIntArrayCopy(graph);
}
public int Count { get; private set; }
private int[,] Get2DIntArrayCopy(int[,] sourceArray)
{
int[,] destinationArray = new int[sourceArray.GetLength(0), sourceArray.GetLength(1)];
for (int i = 0; i < destinationArray.GetLength(0); i++)
{
for (int j = 0; j < destinationArray.GetLength(1); j++)
{
destinationArray[i, j] = sourceArray[i, j];
}
}
return destinationArray;
}
public virtual void DepthFirstSearch(int startIndex, Action<int> action)
{
if (startIndex < 0 || startIndex >= Count)
{
throw new IndexOutOfRangeException("ОШИБКА: стартовый индекс ОБХОДА В ГЛУБИНУ вне диапазона индексов графа");
}
bool[] isVisited = new bool[Count];
Stack<int> stackSearch = new Stack<int>();
stackSearch.Push(startIndex);
int startVisitedIndexCheck = 0;
while (stackSearch.Count != 0)
{
int currentIndex = stackSearch.Pop();
if (!isVisited[currentIndex])
{
action(currentIndex);
isVisited[currentIndex] = true;
for (int j = Count - 1; j >= 0; j--)
{
if (graph[currentIndex, j] != 0 && !isVisited[j])
{
stackSearch.Push(j);
}
}
}
if (stackSearch.Count == 0)
{
for (int k = startVisitedIndexCheck; k < Count; k++)
{
if (!isVisited[k])
{
startVisitedIndexCheck = k + 1;
stackSearch.Push(k);
break;
}
}
}
}
}
private void RecursiveVisit(int index, bool[] isVisited, Action<int> action)
{
action(index);
for (int i = 0; i < Count; i++)
{
if (graph[index, i] != 0 && !isVisited[i])
{
isVisited[i] = true;
RecursiveVisit(i, isVisited, action);
}
}
}
public virtual void DepthFirstSearchRecursion(int startIndex, Action<int> action)
{
if (startIndex < 0 || startIndex >= Count)
{
throw new IndexOutOfRangeException("ОШИБКА: стартовый индекс ОБХОДА В ГЛУБИНУ вне диапазона индексов графа");
}
bool[] isVisited = new bool[Count];
int index = startIndex;
int startVisitedIndexCheck = 0;
bool isProcessDoing = true;
while (isProcessDoing)
{
isVisited[index] = true;
RecursiveVisit(index, isVisited, action);
isProcessDoing = false;
for (int i = startVisitedIndexCheck; i < Count; i++)
{
if (!isVisited[i])
{
startVisitedIndexCheck = i + 1;
index = i;
isProcessDoing = true;
break;
}
}
}
}
public virtual void BreadthFirstSearch(int startIndex, Action<int> action)
{
if (startIndex < 0 || startIndex >= Count)
{
throw new IndexOutOfRangeException("ОШИБКА: стартовый индекс ОБХОДА В ШИРИНУ вне диапазона индексов графа");
}
bool[] isVisited = new bool[Count];
Queue<int> queueSearch = new Queue<int>();
queueSearch.Enqueue(startIndex);
isVisited[startIndex] = true;
int startVisitedIndexCheck = 0;
while (queueSearch.Count != 0)
{
int currentIndex = queueSearch.Dequeue();
action(currentIndex);
for (int j = 0; j < Count; j++)
{
if (graph[currentIndex, j] != 0 && !isVisited[j])
{
queueSearch.Enqueue(j);
isVisited[j] = true;
}
}
if (queueSearch.Count == 0)
{
for (int k = startVisitedIndexCheck; k < Count; k++)
{
if (!isVisited[k])
{
queueSearch.Enqueue(k);
isVisited[k] = true;
startVisitedIndexCheck = k + 1;
break;
}
}
}
}
}
}
}
|
47001021449c537063307d423adb5da21745e9f2
|
C#
|
TaniaAAAAAAA/System-Programing
|
/DZ_MAIL____/Had.xaml.cs
| 2.671875
| 3
|
using MailKit;
using MailKit.Net.Imap;
using MimeKit;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace DZ_MAIL____
{
/// <summary>
/// Interaction logic for Had.xaml
/// </summary>
public partial class Had : Window
{
private static ObservableCollection<string> letters = new ObservableCollection<string>();
public Had()
{
InitializeComponent();
lb_Letters.ItemsSource = letters;
DowloadLetters();
}
private async static void DowloadLetters()
{
using (ImapClient imap = new ImapClient())
{
await imap.ConnectAsync("imap.gmail.com", 993, true);
imap.Authenticate("projectsprog1@gmail.com", "qqwwee11!!");
//if (imap.IsAuthenticated)
//{
var inbox = imap.Inbox;
inbox.Open(FolderAccess.ReadOnly);
try
{
for (int i = 0; i <= inbox.Count / 10; i++)
{
MimeMessage message = inbox.GetMessage(i);
letters.Add(i + " " + message.Subject + "-->" + message.From.Mailboxes.First().Name + " | " + message.Date);
}
}
catch { }
//}
}
}
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
letters.Clear();
DowloadLetters();
}
private void btnNewLetter_Click(object sender, RoutedEventArgs e)
{
NewLetter newLetter = new NewLetter();
newLetter.Show();
}
private void lb_Letters_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void lb_Letters_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DowloadONELetter();
}
private async void DowloadONELetter()
{
using (ImapClient imap = new ImapClient())
{
await imap.ConnectAsync("imap.gmail.com", 993, true);
imap.Authenticate("projectsprog1@gmail.com", "qqwwee11!!");
//if (imap.IsAuthenticated)
//{
var inbox = imap.Inbox;
inbox.Open(FolderAccess.ReadOnly);
try
{
for (int i = 0; i <= inbox.Count / 10; i++)
{
if (lb_Letters.SelectedIndex == i)
{
MimeMessage message = inbox.GetMessage(i);
letters.Clear();
ShowLetter showLetter = new ShowLetter();
showLetter.txtFrom2.Text = message.From.Mailboxes.First().Name;
showLetter.txtTitle2.Text = message.Subject;
showLetter.txtDate2.Text = message.Date.ToString();
showLetter.txtPole2.Text = message.Body.ToString();
showLetter.Show();
}
}
}
catch { }
//}
}
}
}
}
|
70e890dda3fb8c2ebd405670ec60a0a74c5f61b9
|
C#
|
jchadwick/sim-stock-market
|
/src/TraderBot/Program.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Events;
using SimStockMarket.Extensions.RabbitMQ;
namespace SimStockMarket.TraderBot
{
class Program
{
static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "QueueHostName", "localhost" },
{ "LogLevel", LogEventLevel.Information.ToString() }
})
.AddEnvironmentVariables()
.Build();
var logLevel = LogEventLevel.Warning;
Enum.TryParse(config["LogLevel"], out logLevel);
var logLevelSwitch = new Serilog.Core.LoggingLevelSwitch(logLevel);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(logLevelSwitch)
.WriteTo.LiterateConsole()
.CreateLogger();
var traderId = Guid.NewGuid().ToString("n").Substring(0, 8);
Log.Information("Starting Trade Bot {traderId}...", traderId);
var queueHost = config["QueueHost"];
Log.Verbose("Connecting to message host {queueHost}...", queueHost);
using (var connection = MessageQueueFactory.Connect(queueHost))
using (var channel = connection.CreateModel())
{
var queue = MessageQueueFactory.CreateMessageQueue(channel, config["QueueName"]);
var trader = new TradeGenerator(traderId);
while (true)
{
var trade = trader.GenerateTrade();
queue.Publish(trade.Type.ToString().ToLower(), trade);
Thread.Sleep(1000);
}
}
}
}
}
|
0d1856a70a84fe9480ad00951c2b6180af10033b
|
C#
|
lammichael/EnvCrypt.Core
|
/src/console/EnvCrypt.Console/GenerateKey/GenerateKeyVerbOptions.cs
| 2.984375
| 3
|
using System;
using CommandLine;
using EnvCrypt.Core.EncryptionAlgo;
namespace EnvCrypt.Console.GenerateKey
{
[Verb("GenerateKey", HelpText = "Generates a new key for encryption & decryption.")]
class GenerateKeyVerbOptions //: VerbOptionsBase
{
/// <summary>
/// String is used here instead of EnvCryptAlgorithmEnum enum because
/// CommandLineParser throws an ArgumentException if the user text
/// does not exactly match any of the enum's values.
/// </summary>
[Option('a', "Algorithm", HelpText = "Algorithm to use - RSA or AES.", Required = true)]
public string AlgorithmToUse { get; set; }
[Option('n', "Name", HelpText = "The new key's name.", Required = true)]
public string KeyName { get; set; }
[Option('d', "Directory", HelpText = "Directory to output the key file(s).", Required = true)]
public string OutputDirectory { get; set; }
[Option('c', "WriteToConsole", HelpText = "Write resulting key XML to console.", Required = false, DefaultValue = false)]
public bool OutputKeyToConsole { get; set; }
[Option('v', "Verbose", HelpText = "Verbosity of logging output.", Required = false, DefaultValue = false)]
public bool Verbose { get; set; }
public EnvCryptAlgoEnum? GetAlgorithm()
{
EnvCryptAlgoEnum ret;
if (Enum.TryParse(AlgorithmToUse, true, out ret))
{
return ret;
}
return null;
}
}
}
|
219c02de253dd616fbedb2c3e5b461ab251c923d
|
C#
|
matthewkimber/EmmLabsRemote
|
/src/app/EmmLabs.Remote.Core/Communication/SerialCommunicationChannel.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading.Tasks;
namespace EmmLabs.Remote.Core
{
public class SerialCommunicationChannel : ICommunicationChannel, IDisposable
{
public SerialPort Port { get; private set; }
public SerialCommunicationChannelSettings Settings { get; private set; }
public SerialCommunicationChannel()
: this(new SerialCommunicationChannelSettings())
{}
public SerialCommunicationChannel(SerialCommunicationChannelSettings settings)
{
Settings = settings;
Port = new SerialPort(Settings.PortName,
Settings.BaudRate,
Settings.Parity,
Settings.DataBits,
Settings.StopBits);
Port.Open();
}
public string Read()
{
throw new NotImplementedException();
}
public void Write(IMessage message)
{
var messages = new List<IMessage> { message };
Parallel.ForEach(messages, msg =>
{
Port.Write(message.Value);
#if DEBUG
Debug.WriteLine(String.Format("Message Written. ({0})", message.Value));
#endif
});
}
public void Dispose()
{
if (Port.IsOpen)
{
Port.Close();
}
}
}
}
|
b902ef1b4ea8078de158d9bb73d1bebdaea8c0e4
|
C#
|
caboingua99sn/QuanLyKhachSan
|
/DAL/PhongDAL.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entyti;
namespace DAL
{
public class PhongDAL
{
dbQLKhachSanDataContext db = new dbQLKhachSanDataContext();
public List<ePhong> getallphong()
{
var litsphong = (from x in db.Phongs select x).ToList();
List<ePhong> ls = new List<ePhong>();
foreach (Phong item in litsphong)
{
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
ls.Add(p);
}
return ls;
}
public ePhong gettP_byMa(string ma)
{
ePhong phong_ent = new ePhong();
Phong phong = (from x in db.Phongs where x.maPhong.Equals(ma) select x).SingleOrDefault();
phong_ent.MaPhong = phong.maPhong;
phong_ent.MaLoaiPhong = phong.maLoaiPhong;
phong_ent.TenPhong = phong.tenPhong;
phong_ent.Tang = Convert.ToInt32(phong.tang);
phong_ent.GhiChu = phong.ghiChu;
return phong_ent;
}
public List<ePhong> gettinhtrangphong(bool tinhtrang)
{
var litsphong = (from x in db.Phongs where x.tinhTrang.Equals(tinhtrang) select x).ToList();
List<ePhong> ls = new List<ePhong>();
foreach (Phong item in litsphong)
{
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
ls.Add(p);
}
return ls;
}
public ePhong get_tenP(string tenPhong)
{
Phong item = (from x in db.Phongs where x.tenPhong.Equals(tenPhong) select x).SingleOrDefault();
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
return p;
}
public List<ePhong> getLoaiPhong(string maLoaiPhong)
{
var litsphong = (from x in db.Phongs where x.maLoaiPhong.Equals(maLoaiPhong) select x).ToList();
List<ePhong> ls = new List<ePhong>();
foreach (Phong item in litsphong)
{
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
ls.Add(p);
}
return ls;
}
public List<ePhong> getLoaiPhong_Trong(string maLoaiPhong, bool tinhTrang)
{
var litsphong = (from x in db.Phongs where x.maLoaiPhong.Equals(maLoaiPhong) && x.tinhTrang == tinhTrang select x).ToList();
List<ePhong> ls = new List<ePhong>();
foreach (Phong item in litsphong)
{
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
ls.Add(p);
}
return ls;
}
public List<ePhong> getLoaiPhong_Trong_soLuong(string maLoaiPhong, bool tinhTrang, int n)
{
var litsphong = (from x in db.Phongs where x.maLoaiPhong.Equals(maLoaiPhong) && x.tinhTrang == tinhTrang select x).ToList().Take(n);
List<ePhong> ls = new List<ePhong>();
foreach (Phong item in litsphong)
{
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
ls.Add(p);
}
return ls;
}
public ePhong getEPhong_byID(string ma)
{
ePhong p = new ePhong();
Phong ph = db.Phongs.Where(n => n.maPhong.Trim().Equals(ma)).SingleOrDefault();
p.MaPhong = ph.maPhong;
p.TenPhong = ph.tenPhong;
p.Tang = Convert.ToInt32(ph.tang);
p.GhiChu = ph.ghiChu;
p.MaLoaiPhong = ph.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(ph.tinhTrang);
p.SoNgHienTai = Convert.ToInt32(ph.soNguoiHienTai);
return p;
}
public string maPhong_byTen(string tenPhong)
{
Phong p = db.Phongs.Where(n => n.tenPhong.Trim().Equals(tenPhong)).SingleOrDefault();
return p.maPhong;
}
public void updateTinhTrangPhong(ePhong pupdate)
{
IQueryable<Phong> p = db.Phongs.Where(x => x.maPhong.Equals(pupdate.MaPhong));
p.First().tinhTrang = Convert.ToBoolean(pupdate.TinhTrang);
p.First().soNguoiHienTai = pupdate.SoNgHienTai;
db.SubmitChanges();
}
public string getLoaiPhong_ByID(string id)
{
Phong p = db.Phongs.Where(n => n.maPhong.Trim().Equals(id)).SingleOrDefault();
return p.maLoaiPhong.Trim();
}
public string getTenPhong_ByID(string id)
{
Phong p = db.Phongs.Where(n => n.maPhong.Trim().Equals(id)).SingleOrDefault();
return p.tenPhong.Trim();
}
ArrayList tang = new ArrayList();
public ArrayList Tang()
{
var phong = (from x in db.Phongs select x.tang).Distinct();
foreach (var item in phong)
{
tang.Add(item);
}
return tang;
}
public List<ePhong> getTang(string tang)
{
var litsphong = (from x in db.Phongs where x.tang.Equals(tang) select x).ToList();
List<ePhong> ls = new List<ePhong>();
foreach (Phong item in litsphong)
{
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
ls.Add(p);
}
return ls;
}
public List<ePhong> getTang_PhongTrong(string tang, bool tinhtrang)
{
var litsphong = (from x in db.Phongs where x.tang.Equals(tang) && x.tinhTrang == tinhtrang select x).ToList();
List<ePhong> ls = new List<ePhong>();
foreach (Phong item in litsphong)
{
ePhong p = new ePhong();
p.MaPhong = item.maPhong;
p.TenPhong = item.tenPhong;
p.Tang = Convert.ToInt32(item.tang);
p.GhiChu = item.ghiChu;
p.MaLoaiPhong = item.maLoaiPhong;
p.TinhTrang = Convert.ToBoolean(item.tinhTrang);
ls.Add(p);
}
return ls;
}
public bool deletePhong(string map)
{
Phong ptemp = db.Phongs.Where(x => x.maPhong == map).FirstOrDefault();
if (ptemp != null)
{
db.Phongs.DeleteOnSubmit(ptemp);
db.SubmitChanges(); //cập nhật việc xóa vào CSDL
return true; //xóa thành công
}
return false;
}
public int updatePhong(ePhong pupdate)
{
IQueryable<Phong> p = db.Phongs.Where(x => x.maPhong.Equals(pupdate.MaPhong));
p.First().maLoaiPhong = pupdate.MaLoaiPhong;
p.First().ghiChu = pupdate.GhiChu;
p.First().tang = pupdate.Tang;
db.SubmitChanges();
return 1;
}
public int insertPhong(ePhong pnew)
{
Phong ptemp = new Phong();
ptemp.maPhong = "";
ptemp.tenPhong = "";
ptemp.ghiChu = pnew.GhiChu;
ptemp.maLoaiPhong = pnew.MaLoaiPhong;
ptemp.tang = (pnew.Tang);
ptemp.tinhTrang = pnew.TinhTrang;
db.Phongs.InsertOnSubmit(ptemp);
db.SubmitChanges();
return 1;
}
}
}
|
5e1a36aa64b3bbbf6d0445e7f48a00525bddab4f
|
C#
|
consolelogreece/game-hub
|
/GameHub.Web/Services/Games/Common/GamePlayerGetter.cs
| 2.59375
| 3
|
using GameHub.Games.BoardGames.Common;
public class GamePlayerGetter<T> where T : GamePlayer
{
private IGamePlayerGetter<T> _game;
public GamePlayerGetter(IGamePlayerGetter<T> game)
{
_game = game;
}
public T Get(string playerId)
{
lock(_game)
{
return _game.GetPlayer(playerId);
}
}
}
|
399ff89f7db84a416e7a33eceaebe0bf3d959417
|
C#
|
lkogan/HelloWorldAPIProject
|
/HelloWorldAPI/Services/SaveRepository.cs
| 2.71875
| 3
|
using HelloWorldAPI.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace HelloWorldAPI.Services
{
public interface IRepository<T> where T : DataObject
{
bool Save(T entity);
}
public class DatabaseRepository : IRepository<DataObject>
{
public bool Save(DataObject entity)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//TO do: add functionality for saving to database
return true;
}
catch
{
return false;
}
}
}
public class TextRepository : IRepository<DataObject>
{
public bool Save(DataObject entity)
{
try
{
string saveTextDirectory = ConfigurationManager.AppSettings["SaveTextDirectory"];
//TO DO: add functionality for saving to text file
return true;
}
catch
{
return false;
}
}
}
public class XmlRepository : IRepository<DataObject>
{
public bool Save(DataObject entity)
{
try
{
string saveXMLDirectory = ConfigurationManager.AppSettings["SaveXMLDirectory"];
//TO DO: add functionality for serializing object to XML, and saving to xml file
return true;
}
catch
{
return false;
}
}
}
}
|
a31c8a8343bcfb57dc9b6c2b100f0a22900a5641
|
C#
|
Crampers/Raunstrup
|
/RaunstrupERP/Program.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace RaunstrupERP
{
class Program
{
static void Main(string[] args)
{
/*
UNCOMMENT THIS PART OF THE CODE TO CREATE THE XML FILE THAT IS USED TO STORE DATABASE CONNECTION INFO:
THIS FILE IS FOUND IN YOUR DEBUG FOLDER!
THANK YOU!
PROGRAM IS SET TO CLOSE DOWN UNTIL THE LINE(s) BELOW IS COMMENTED OUT
*/
//DBInit CREATEXMLDATA = new DBInit();
/*
MAKE SURE YOU COMMENT OUT THE PART ABOVE AFTER YOU HAVE USED IT TO CREATE THE DOCUMENT,
OTHERTWISE IT WILL RESET THE DOCUMENT!
*/
//THIS PART BELOW IS THE REGULAR PROGRAM!
ControllerCatalog cc = new ControllerCatalog();
cc.LoadItems();
/*FORMS!*/
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form_Main_1());
Console.ReadKey();
}
}
}
|
4f355a329b8682623f96db3f8885c433615803b6
|
C#
|
fasteddys/ZemberekDotNet
|
/ZemberekDotNet.Tokenization.Tests/TurkishTokenizerTest.cs
| 3
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using ZemberekDotNet.Core.Logging;
namespace ZemberekDotNet.Tokenization.Tests
{
[TestClass]
public class TurkishTokenizerTest
{
private void MatchToken(
TurkishTokenizer tokenizer,
String input,
Token.Type? tokenType,
params string[] expectedTokens)
{
List<Token> tokens = tokenizer.Tokenize(input);
Assert.IsNotNull(tokens, "Token list is null.");
Assert.IsTrue(tokens.Count > 0);
Assert.AreEqual(expectedTokens.Length, tokens.Count, "Token count is not equal to expected Token count for input " + input);
int i = 0;
foreach (string expectedToken in expectedTokens)
{
Token token = tokens[i];
Assert.AreEqual(expectedToken, token.GetText(), expectedToken + " is not equal to " + token.GetText());
if (tokenType != null)
{
Assert.AreEqual(tokenType, token.GetTokenType());
}
i++;
}
}
private string GetTokensAsString(TurkishTokenizer tokenizer, String input)
{
List<string> elements = tokenizer.TokenizeToStrings(input);
return string.Join(" ", elements);
}
private void MatchToken(TurkishTokenizer tokenizer, string input, params string[] expectedTokens)
{
MatchToken(tokenizer, input, null, expectedTokens);
}
private void MatchSentences(
TurkishTokenizer tokenizer,
string input,
string expectedJoinedTokens)
{
string actual = GetTokensAsString(tokenizer, input);
Assert.AreEqual(expectedJoinedTokens, actual);
}
[TestMethod]
public void TestInstances()
{
// default ignores white spaces and new lines.
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "a b \t c \n \r", "a", "b", "c");
// ALL tokenizer catches all tokens.
t = TurkishTokenizer.All;
MatchToken(t, " a b\t\n\rc", " ", "a", " ", "b", "\t", "\n", "\r", "c");
// A tokenizer only catches Number type (not date or times).
t = TurkishTokenizer.Builder().IgnoreAll().AcceptTypes(Token.Type.Number).Build();
MatchToken(t, "www.foo.bar 12,4'ü a@a.v ; ^% 2 adf 12 \r \n ", "12,4'ü", "2", "12");
}
[TestMethod]
public void TestNumbers()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "1", Token.Type.Number, "1");
MatchToken(t, "12", Token.Type.Number, "12");
MatchToken(t, "3.14", Token.Type.Number, "3.14");
MatchToken(t, "-1", Token.Type.Number, "-1");
MatchToken(t, "-1.34", Token.Type.Number, "-1.34");
MatchToken(t, "-3,14", Token.Type.Number, "-3,14");
MatchToken(t, "100'e", Token.Type.Number, "100'e");
MatchToken(t, "3.14'ten", Token.Type.Number, "3.14'ten");
MatchToken(t, "%2.5'ten", Token.Type.PercentNumeral, "%2.5'ten");
MatchToken(t, "%2", Token.Type.PercentNumeral, "%2");
MatchToken(t, "2.5'a", Token.Type.Number, "2.5'a");
MatchToken(t, "2.5’a", Token.Type.Number, "2.5’a");
}
[TestMethod]
public void TestWords()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "kedi", Token.Type.Word, "kedi");
MatchToken(t, "Kedi", "Kedi");
MatchToken(t, "Ahmet'e", "Ahmet'e");
}
[TestMethod]
public void TestTags()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "<kedi>", Token.Type.MetaTag, "<kedi>");
MatchToken(
t,
"<kedi><eti><7>",
Token.Type.MetaTag,
"<kedi>", "<eti>", "<7>");
}
[TestMethod]
public void TestAlphaNumerical()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t,
"F-16'yı, (H1N1) H1N1'den.",
"F-16'yı , ( H1N1 ) H1N1'den .");
}
[TestMethod]
public void TestCapitalWords()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "TCDD", "TCDD");
MatchToken(t, "I.B.M.", "I.B.M.");
MatchToken(t, "TCDD'ye", "TCDD'ye");
MatchToken(t, "I.B.M.'nin", "I.B.M.'nin");
MatchToken(t, "I.B.M'nin", "I.B.M'nin");
MatchSentences(t, "İ.Ö,Ğ.Ş", "İ.Ö , Ğ.Ş");
MatchSentences(t, "İ.Ö,", "İ.Ö ,");
MatchSentences(t, "İ.Ö.,Ğ.Ş.", "İ.Ö. , Ğ.Ş.");
}
[TestMethod]
public void TestAbbreviations()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "Prof.", "Prof.");
MatchToken(t, "yy.", "yy.");
MatchSentences(t, "kedi.", "kedi .");
}
[TestMethod]
public void TestApostrophes()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "foo'f", "foo'f");
MatchToken(t, "foo’f", "foo’f");
MatchSentences(t, "’foo", "’ foo");
MatchSentences(t, "’’foo’", "’ ’ foo ’");
MatchSentences(t, "'foo'", "' foo '");
MatchSentences(t, "'foo'fo", "' foo'fo");
MatchSentences(t, "‘foo'fo’", "‘ foo'fo ’");
}
[TestMethod]
public void TestTokenBoundaries()
{
TurkishTokenizer t = TurkishTokenizer.All;
List<Token> tokens = t.Tokenize("bir av. geldi.");
Token t0 = tokens[0];
Assert.AreEqual("bir", t0.GetText());
Assert.AreEqual(0, t0.GetStart());
Assert.AreEqual(2, t0.GetEnd());
Token t1 = tokens[1];
Assert.AreEqual(" ", t1.GetText());
Assert.AreEqual(3, t1.GetStart());
Assert.AreEqual(3, t1.GetEnd());
Token t2 = tokens[2];
Assert.AreEqual("av.", t2.GetText());
Assert.AreEqual(4, t2.GetStart());
Assert.AreEqual(6, t2.GetEnd());
Token t3 = tokens[3];
Assert.AreEqual(" ", t3.GetText());
Assert.AreEqual(7, t3.GetStart());
Assert.AreEqual(7, t3.GetEnd());
Token t4 = tokens[4];
Assert.AreEqual("geldi", t4.GetText());
Assert.AreEqual(8, t4.GetStart());
Assert.AreEqual(12, t4.GetEnd());
Token t5 = tokens[5];
Assert.AreEqual(".", t5.GetText());
Assert.AreEqual(13, t5.GetStart());
Assert.AreEqual(13, t5.GetEnd());
}
[TestMethod]
public void TestAbbreviations2()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t,
"Prof. Dr. Ahmet'e git! dedi Av. Mehmet.",
"Prof. Dr. Ahmet'e git ! dedi Av. Mehmet .");
}
[TestMethod]
public void TestCapitalLettersAfterQuotesIssue64()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t, "Ankaraya.", "Ankaraya .");
MatchSentences(t, "Ankara'ya.", "Ankara'ya .");
MatchSentences(t, "ANKARA'ya.", "ANKARA'ya .");
MatchSentences(t, "ANKARA'YA.", "ANKARA'YA .");
MatchSentences(t, "Ankara'YA.", "Ankara'YA .");
MatchSentences(t, "Ankara'Ya.", "Ankara'Ya .");
}
[TestMethod]
public void TestUnknownWord1()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t, "زنبورك", "زنبورك");
}
[TestMethod]
public void TestUnderscoreWords()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t, "__he_llo__", "__he_llo__");
}
[TestMethod]
public void TestDotInMiddle()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t, "Ali.gel.", "Ali . gel .");
}
[TestMethod]
public void TestPunctuation()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t,
".,!:;$%\"\'()[]{}&@®™©℠",
". , ! : ; $ % \" \' ( ) [ ] { } & @ ® ™ © ℠");
MatchToken(t, "...", "...");
MatchToken(t, "(!)", "(!)");
}
[TestMethod]
public void TestTokenizeSentence()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t, "Ali gel.", "Ali gel .");
MatchSentences(t, "(Ali gel.)", "( Ali gel . )");
MatchSentences(t, "Ali'ye, gel...", "Ali'ye , gel ...");
MatchSentences(t, "\"Ali'ye\", gel!...", "\" Ali'ye \" , gel ! ...");
MatchSentences(t, "[Ali]{gel}", "[ Ali ] { gel }");
}
[TestMethod]
public void TestTokenizeDoubleQuote()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t, "\"Soner\"'e boyle dedi", "\" Soner \" ' e boyle dedi");
MatchSentences(t, "Hey \"Ali\" gel.", "Hey \" Ali \" gel .");
MatchSentences(t, "\"Soner boyle dedi\"", "\" Soner boyle dedi \"");
}
[TestMethod]
public void TestNewline()
{
TurkishTokenizer tokenizer = TurkishTokenizer.All;
MatchToken(tokenizer, "Hey \nAli naber\n", "Hey", " ", "\n", "Ali", " ", "naber", "\n");
MatchToken(tokenizer, "Hey\n\r \n\rAli\n \n\n \n naber\n",
"Hey", "\n", "\r", " ", "\n", "\r", "Ali", "\n", " ", "\n", "\n", " ", "\n", " ", "naber",
"\n");
}
//TODO: failing.
[TestMethod]
[Ignore]
public void TestUnknownWord()
{
TurkishTokenizer tokenizer = TurkishTokenizer.Default;
MatchSentences(tokenizer, "L'Oréal", "L'Oréal");
}
[TestMethod]
public void TestUnknownWord2()
{
TurkishTokenizer tokenizer = TurkishTokenizer.Default;
MatchSentences(tokenizer, "Bjørn", "Bjørn");
}
[TestMethod]
public void TestTimeToken()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t,
"Saat, 10:20 ile 00:59 arasinda.",
"Saat , 10:20 ile 00:59 arasinda .");
MatchToken(t, "10:20", Token.Type.Time, "10:20");
}
[TestMethod]
public void TestTimeTokenSeconds()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchToken(t, "10:20:53", Token.Type.Time, "10:20:53");
MatchToken(t, "10.20.00'da", Token.Type.Time, "10.20.00'da");
}
[TestMethod]
public void testDateToken()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t,
"1/1/2011 02.12.1998'de.",
"1/1/2011 02.12.1998'de .");
MatchToken(t, "1/1/2011", Token.Type.Date, "1/1/2011");
MatchToken(t, "02.12.1998'de", Token.Type.Date, "02.12.1998'de");
}
[TestMethod]
public void TestEmoticonToken()
{
TurkishTokenizer t = TurkishTokenizer.Default;
string[] emoticons = {
":)", ":-)", ":-]", ":D", ":-D", "8-)", ";)", ";‑)", ":(", ":-(",
":'(", ":‑/", ":/", ":^)", "¯\\_(ツ)_/¯", "O_o", "o_O", "O_O", "\\o/"
};
foreach (string s in emoticons)
{
MatchToken(t, s, Token.Type.Emoticon, s);
}
}
[TestMethod]
public void TestUrl()
{
TurkishTokenizer t = TurkishTokenizer.Default;
string[] urls = {
"http://t.co/gn32szS9",
"http://foo.im/lrıvn",
"http://www.fo.bar",
"http://www.fo.bar'da",
"https://www.fo.baz.zip",
"www.fo.tar.kar",
"www.fo.bar",
"fo.com",
"fo.com.tr",
"fo.com.tr/index.html",
"fo.com.tr/index.html?",
"foo.net",
"foo.net'e",
"www.foo.net'te",
"http://www.foo.net/showthread.php?134628-ucreti",
"http://www.foo.net/showthread.php?1-34--628-ucreti+",
"https://www.hepsiburada.com'dan",
};
foreach (string s in urls)
{
MatchToken(t, s, Token.Type.URL, s);
}
}
[TestMethod]
public void TestUrl2()
{
TurkishTokenizer t = TurkishTokenizer.Default;
string[] urls = {
"https://www.google.com.tr/search?q=bla+foo&oq=blah+net&aqs=chrome.0.0l6",
"https://www.google.com.tr/search?q=bla+foo&oq=blah+net&aqs=chrome.0.0l6.5486j0j4&sourceid=chrome&ie=UTF-8"
};
foreach (string s in urls)
{
MatchToken(t, s, Token.Type.URL, s);
}
}
[TestMethod]
public void TestEmail()
{
TurkishTokenizer t = TurkishTokenizer.Default;
string[] emails = {
"fo@bar.baz",
"fo.bar@bar.baz",
"fo_.bar@bar.baz",
"ali@gmail.com'u"
};
foreach (string s in emails)
{
MatchToken(t, s, Token.Type.Email, s);
}
}
[TestMethod]
public void MentionTest()
{
TurkishTokenizer t = TurkishTokenizer.Default;
string[] ss = {
"@bar",
"@foo_bar",
"@kemal'in"
};
foreach (string s in ss)
{
MatchToken(t, s, Token.Type.Mention, s);
}
}
[TestMethod]
public void HashTagTest()
{
TurkishTokenizer t = TurkishTokenizer.Default;
String[] ss = {
"#foo",
"#foo_bar",
"#foo_bar'a"
};
foreach (string s in ss)
{
MatchToken(t, s, Token.Type.HashTag, s);
}
}
[TestMethod]
public void TestEllipsis()
{
TurkishTokenizer t = TurkishTokenizer.Default;
MatchSentences(t, "Merhaba, Kaya Ivır ve Tunç Zıvır…", "Merhaba , Kaya Ivır ve Tunç Zıvır …");
}
[TestMethod]
[Ignore("Not an actual test. Requires external data.")]
public void Performance()
{
TurkishTokenizer tokenizer = TurkishTokenizer.Default;
// load a hundred thousand lines.
for (int it = 0; it < 5; it++)
{
string[] lines = File.ReadAllLines("/media/aaa/Data/aaa/corpora/dunya.100k");
Stopwatch clock = Stopwatch.StartNew();
long tokenCount = 0;
foreach (string line in lines)
{
List<Token> tokens = tokenizer.Tokenize(line);
tokenCount += tokens.Count;
}
long elapsed = clock.ElapsedMilliseconds;
Log.Info("Token count = {0} ", tokenCount);
Log.Info("Speed (tps) = {0:F1}", tokenCount * 1000d / elapsed);
}
}
}
}
|
5e9d64030045140953550cf8a922e93df785e8bd
|
C#
|
seriousdave42/cSharp-ninjasInSpace
|
/Models/RayGun.cs
| 3.015625
| 3
|
using NinjasInSpace.Interfaces;
namespace NinjasInSpace.Models
{
public class RayGun : Equipment, IEquipable
{
public int StrengthBonus;
public RayGun(string name, int str) : base(name)
{
StrengthBonus = str;
Desc = $"This increases a character's strength by {str}.";
}
public void Equip(Hero target)
{
target.Strength += StrengthBonus;
}
}
}
|
fea077cc25e66311d74479271b90f7c7d9f35307
|
C#
|
woshihuo12/LearnWPF
|
/src/11/mumu_SliderDemo/mumu_SliderDemo/DoubleConverter.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace mumu_SliderDemo
{
public class DoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Byte rgbValue = System.Convert.ToByte(value) ;
string txtRGBValue = rgbValue.ToString();
return txtRGBValue;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
string str = (string)value;
double dbValue = double.Parse(str);
return dbValue;
}
}
}
|
239b4c7008990d56acb04bc73fd299c97d9ea010
|
C#
|
s16944/cw3
|
/cw3/DAL/EfDbService.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using cw3.Models;
using System.Data.SqlClient;
using Castle.Core.Internal;
using Microsoft.EntityFrameworkCore;
namespace cw3.DAL
{
public class EfDbService : ITransactionalDbService
{
private readonly StudiesDbContext _dbContext;
public EfDbService(StudiesDbContext dbContext)
{
_dbContext = dbContext;
}
public Student GetStudentByIndexNumber(string indexNumber) => _dbContext.Student
.SingleOrDefault(s => s.IndexNumber == indexNumber);
public IEnumerable<Student> GetStudents() => _dbContext.Student.ToList();
public Student AddStudent(Student student)
{
_dbContext.Student.Add(student);
_dbContext.SaveChanges();
return student;
}
public Student UpdateStudent(Student student)
{
var dbStudent = _dbContext.Student.Single(s => s.IndexNumber == student.IndexNumber);
dbStudent.FirstName = student.FirstName;
dbStudent.LastName = student.LastName;
dbStudent.BirthDate = student.BirthDate;
_dbContext.SaveChanges();
return dbStudent;
}
public Student RemoveStudent(string indexNumber)
{
var dbStudent = _dbContext.Student.Single(s => s.IndexNumber == indexNumber);
_dbContext.Student.Remove(dbStudent);
_dbContext.SaveChanges();
return dbStudent;
}
public IEnumerable<Enrollment> GetStudentEnrollments(string indexNumber)
{
var student = _dbContext.Student
.Where(s => s.IndexNumber == indexNumber)
.Include(s => s.IdEnrollmentNavigation)
.First();
return new[] {student.IdEnrollmentNavigation};
}
public IEnumerable<Role> GetStudentRoles(Student student)
{
var dbStudent = _dbContext.Student
.Where(s => s.IndexNumber == student.IndexNumber)
.Include(s => s.StudentRoles)
.ThenInclude(sr => sr.Role)
.First();
return dbStudent.StudentRoles.Select(sr => sr.Role)
.ToList();
}
public void AddStudentRefreshToken(Student student, string refreshToken, DateTime validity)
{
var dbStudent = _dbContext.Student
.Where(s => s.IndexNumber == student.IndexNumber)
.Include(s => s.RefreshTokens)
.First();
dbStudent.RefreshTokens.Add(new RefreshTokens {Token = refreshToken, Validity = validity});
_dbContext.SaveChanges();
}
public bool IsRefreshTokenPresent(string refreshToken) =>
_dbContext.RefreshTokens.Any(r => r.Token == refreshToken);
public Student GetStudentByRefreshToken(string refreshToken)
{
var token = _dbContext.RefreshTokens
.Where(r => r.Token == refreshToken)
.Include(r => r.IndexNumberNavigation)
.First();
return token.IndexNumberNavigation;
}
public void ReplaceRefreshToken(string oldToken, string newToken, DateTime validity)
{
var token = _dbContext.RefreshTokens
.First(r => r.Token == oldToken);
token.Token = newToken;
token.Validity = validity;
_dbContext.SaveChanges();
}
public Studies GetStudiesByName(string name) => _dbContext.Studies.SingleOrDefault(s => s.Name == name);
public Enrollment GetEnrollmentByStudiesIdAndSemester(int studiesId, int semester) =>
_dbContext.Enrollment
.SingleOrDefault(e => e.IdStudy == studiesId && e.Semester == semester);
public Enrollment AddEnrollment(Enrollment enrollment)
{
var id = _dbContext.Enrollment.Max(e => e.IdEnrollment) + 1;
enrollment.IdEnrollment = id;
_dbContext.Enrollment.Add(enrollment);
_dbContext.SaveChanges();
return enrollment;
}
public void EnrollStudent(Student student, Enrollment enrollment)
{
student.IdEnrollment = enrollment.IdEnrollment;
_dbContext.Student.Add(student);
_dbContext.SaveChanges();
}
public Enrollment PromoteStudents(string studiesName, int semester)
{
_dbContext.Database.BeginTransaction();
var studies = _dbContext.Studies
.Include(s => s.Enrollment)
.SingleOrDefault(s => s.Name == studiesName);
if (studies == default) throw new NoSuchStudiesException();
var currentEnrollment = studies.Enrollment.FirstOrDefault(e => e.Semester == semester);
if (currentEnrollment == default) throw new NoSuchEnrollmentException();
var newEnrollment = studies.Enrollment.FirstOrDefault(e => e.Semester == semester + 1);
if (newEnrollment == default)
{
var id = _dbContext.Enrollment.Max(e => e.IdEnrollment) + 1;
newEnrollment = new Enrollment {IdEnrollment = id, Semester = semester + 1, StartDate = DateTime.Now};
studies.Enrollment.Add(newEnrollment);
_dbContext.SaveChanges();
}
_dbContext.Entry(currentEnrollment).Collection(e => e.Student).Load();
foreach (var student in currentEnrollment.Student.ToList())
{
student.IdEnrollmentNavigation = newEnrollment;
}
_dbContext.SaveChanges();
_dbContext.Database.CommitTransaction();
return newEnrollment;
}
public T InTransaction<T>(Func<IDbService, Tuple<bool, T>> operations, Func<T> onError)
{
try
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
var (isSuccessful, result) = operations.Invoke(this);
if (isSuccessful) transaction.Commit();
else transaction.Rollback();
return result;
}
}
catch (SqlException exception)
{
Console.WriteLine(exception);
return onError.Invoke();
}
}
}
}
|
bfbb2a95fabf1048d538b24c497cd23aee725bef
|
C#
|
Steven0709/ConsoleAppES
|
/Program.cs
| 3.40625
| 3
|
using System;
namespace semana3_estructuras_de_control
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Black;
menu();
}
static void menu()
{
int repetir_menu;
Console.BackgroundColor = ConsoleColor.Blue;
System.Console.WriteLine("Estructuras de control en Visual C#");
System.Console.WriteLine("1. Menú de opciones");
System.Console.WriteLine("2. Salir");
System.Console.WriteLine("Ingrese 1 para mostrar menú o 2 para salir. ");
repetir_menu = Int32.Parse(Console.ReadLine());
switch (repetir_menu)
{
case 1:
opciones();
break;
case 2:
Environment.Exit(0);
System.Console.WriteLine("Usted ha seleccionado salir!");
break;
default:
System.Console.WriteLine("Opción equivocada");
break;
}
opciones();
}
static void opciones()
{
int opcion;
Console.Clear();
Console.BackgroundColor = ConsoleColor.Red;
System.Console.WriteLine("Ejemplos de estructuras de control");
System.Console.WriteLine("1. USO DEL IF");
System.Console.WriteLine("2. USO DEL WHILE");
System.Console.WriteLine("3. USO DEL DOWHILE");
System.Console.WriteLine("4. USO DEL FOR ");
System.Console.WriteLine("Ingrese la opción: ");
opcion = Int32.Parse(Console.ReadLine());
switch (opcion)
{
case 1:
ejemplo_if();
break;
case 2:
ejemplo_while();
break;
case 3:
ejemplo_doWhile();
break;
case 4:
ejemplo_for();
break;
default:
System.Console.WriteLine("Opción equivocada");
break;
}
System.Console.ReadKey();
//principal();
}
static void ejemplo_if()
{
System.Console.WriteLine("Ejemplo de IF");
Console.WriteLine("ingrese un numero entre 1 y 3");
int num = int.Parse(Console.ReadLine());
if (num == 1)
{
Console.WriteLine("valor es 1");
}
else
if (num == 2)
{
Console.WriteLine("valor es 2");
}
else
if (num == 3)
{
Console.WriteLine("valor es 3");
}
else
{
Console.WriteLine("no se encontro el valor");
}
Console.ReadKey();
}
static void ejemplo_while()
{
System.Console.WriteLine("Ejemplo de while");
Console.WriteLine("ingrese un numero");
int numero1 = int.Parse(Console.ReadLine());
Console.WriteLine("ingrese un numero mayor que el anterior");
int numero2 = int.Parse(Console.ReadLine());
while (numero1 < numero2)
{
Console.WriteLine("valores:" + numero1);
numero1++;
}
Console.ReadKey();
}
static void ejemplo_doWhile()
{
System.Console.WriteLine("Ejemplo de doWhile");
string secret;
string palabra;
Console.WriteLine("ingrese la palabra secreta");
secret = Console.ReadLine();
do
{
Console.WriteLine("vuelva a introducir la palabra secreta");
palabra = Console.ReadLine();
if (palabra != secret)
Console.WriteLine("palabra incorrecta");
} while (palabra != secret);
Console.WriteLine("Palabra Correcta");
Console.ReadKey();
}
static void ejemplo_for()
{
System.Console.WriteLine("Ejemplo de for");
{
System.Console.WriteLine("Contador iniciado");
for (int num = 1; num <= 10; num++)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
}
|
e9ffb91a46cac0f5a6519e2fb5e9f8f7df9c209d
|
C#
|
wesenu/CSharp-Fundamentals-3
|
/C# OOP Basics/06Polymorphism/Exercise/03WildFarm/Cat.cs
| 3.546875
| 4
|
using System;
using System.Linq;
public class Cat : Feline
{
private string[] eatableFood = new string[] { "Vegetable", "Meat" };
public Cat(string name, double weight, string region, string breed)
: base(name, weight, region, breed)
{
this.Breed = breed;
}
public override void AskForFood()
{
Console.WriteLine("Meow");
}
public override void EatFood(Food food)
{
if (!eatableFood.Contains(food.GetType().Name))
{
throw new ArgumentException($"{this.GetType().Name} does not eat {food.GetType().Name}!");
}
this.FoodEaten += food.Quantity;
}
public override string ToString()
{
double initialWeiht = this.Weight;
double gainedWeight = this.FoodEaten * 0.30;
double totalWeight = initialWeiht + gainedWeight;
return $"{this.GetType().Name} [{this.Name}, {this.Breed}, {totalWeight}, {this.Region}, {FoodEaten}]";
}
}
|
2833eed3202e4069dbcd52af1069477cdedbf691
|
C#
|
abedirhan/Pati
|
/Pati/Repository/BasketRepository.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Pati.Models;
using Pati.Services;
namespace Pati.Repository
{
public class BasketRepository:IBasket
{
private DB_Context db;
public BasketRepository(DB_Context _db)
{
db = _db;
}
public IEnumerable<Basket> GetBaskets => db.Baskets;
public Basket GetBasket(int? id)
{
Basket dbEntity = db.Baskets.Find(id);
return dbEntity;
}
public void Add(Basket basket)
{
db.Baskets.Add(basket);
db.SaveChanges();
}
public void Remove(int? id)
{
Basket dbEntity = db.Baskets.Find(id);
db.Baskets.Remove(dbEntity);
db.SaveChanges();
}
}
}
|
cdc0fbeec31c07a9b7853377bf019b736442e0a3
|
C#
|
meselgroth/websockets-sandbox
|
/server/Startup.cs
| 2.640625
| 3
|
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseWebSockets();
var socketManager = new SocketManager();
app.Use(async (context, next) =>
{
Console.WriteLine($"IsWebSocketRequest: {context.WebSockets.IsWebSocketRequest}");
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
socketManager.AddSocket(webSocket);
var buffer = new byte[1024 * 4];
WebSocketReceiveResult receivedMsg;
do
{
receivedMsg = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var msgText = Encoding.UTF8.GetString(buffer, 0, receivedMsg.Count);
Console.WriteLine($"Received message: {msgText}");
var state = socketManager.ProcessCommand(msgText);
} while (receivedMsg.CloseStatus == null);
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "ok", CancellationToken.None);
});
}
}
}
|
e828b9d143f43914fd16f45a347d91d30cbf8239
|
C#
|
Gnutz/uni
|
/semester4/SWD/week 5.2 Factories/Factory Example (WeighingSystem)/WeighingSystem.Application/Program.cs
| 2.65625
| 3
|
using WeighingSystem.Factories;
namespace WeighingSystem.Application
{
class Program
{
static void Main(string[] args)
{
// Create two different weighing systems. Not that they ONLY differ in the kind of factory used.
var nettoWeighingSystem = new WeightControl(new NettoWeighingSystemFactory());
var irmaWeighingSystem = new WeightControl(new IrmaWeighingSystemFactory());
nettoWeighingSystem.ItemPlacedOnWeight();
irmaWeighingSystem.ItemPlacedOnWeight();
}
}
}
|
2dbdd3e9d0fd33244b116e4499dae13589fafa49
|
C#
|
MichaelMladenow/XML-Generator
|
/SOC-Generator/Generators/ClassModels/xmlModels/Row.cs
| 3.078125
| 3
|
namespace SOC_Generator.Generators.ClassModels.xmlModels
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Class representing a question row in XML format
/// </summary>
public class Row : Tag
{
private const string RowTagName = "row";
private const string RowLabelFormat = "r{0}";
/// <summary>
/// Row Constructor
/// </summary>
/// <param name="index">The index we use for labeling.</param>
/// <param name="attributes">List of KV string string pairs.</param>
public Row(int index, Dictionary<string, string> attributes)
: base(RowTagName, attributes)
{
this.Attributes["label"] = string.Format(RowLabelFormat, index);
this.Attributes.OrderBy(entry => entry.Key == "label");
}
}
}
|
6226d8b74a541627178ada094282e658bb0afabc
|
C#
|
will-bei/UART-8051-demo
|
/8051 Control GUI/Desktop Code/8051 Control GUI/8051 Control GUI/Form1.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
//Author: William Bei
//Published: October 15, 2016 Saturday
//
//Created with Microsoft Visual Studio 2015
namespace _8051_Control_GUI
{
public partial class Form1 : Form
{
//Graphics variables
private Graphics g;
private Pen p;
private Rectangle r;
//Display, serial port variables
private Line[][] pages;
private Boolean[][] isShaded;
//mouse position
private int MouseX;
private int MouseY;
public Form1()
{
/*
*
*
* LCD pixel organization: LCD is 64 by 128 pixels
* Every 8 rows is divided into one page
* Each page is divided into columns, each column containing a byte
* with each bit as one pixel
* Writing LCD data must be done a byte at a time.
*
*/
//initialize each pixel in the GUI
pages = new Line[64][];
for (int i = 0; i < pages.Length; i++)
{
pages[i] = new Line[128];
}
for (int i = 0; i < pages.Length; i++)
{
for (int j = 0; j < pages[i].Length; j++)
{
pages[i][j] = new Line(i, j);
}
}
InitializeComponent();
//disable altering windows form size
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
//add mouse listener
this.MouseClick += mouseClick;
}
//Clear button: clears all pixels in LCD display
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Clearing...";
pages = new Line[64][];
//Clear Laptop/Desktop Variables
for (int i = 0; i < pages.Length; i++)
{
pages[i] = new Line[128];
}
for (int i = 0; i < pages.Length; i++)
{
for (int j = 0; j < pages[i].Length; j++)
{
pages[i][j] = new Line(i, j);
}
}
isShaded = new Boolean[64][];
for (int i = 0; i < isShaded.Length; i++)
{
isShaded[i] = new Boolean[128];
for (int j = 0; j < isShaded[i].Length; j++)
{
isShaded[i][j] = false;
}
}
drawMethod();
//Instruct 8051 to clear
clearAll();
textBox1.Text = "Cleared.";
}
//Open Serial Port for UART communication
private void Initialize_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
serialPort1.PortName = "COM3";
serialPort1.Open();
drawMethod();
isShaded = new Boolean[64][];
for (int i = 0; i < isShaded.Length; i++)
{
isShaded[i] = new Boolean[128];
for (int j = 0; j < isShaded[i].Length; j++)
{
isShaded[i][j] = false;
}
}
clearAll();
}
}
//creating the 64 x 128 LCD Display GUI
private void drawMethod()
{
g = CreateGraphics();
p = new Pen(Brushes.Black);
for (int i = 0; i < 128; i++)
{
for (int j = 0; j < 64; j++)
{
r = new Rectangle(i * 5, j * 5, 5, 5);
g.FillRectangle(Brushes.White, r);
g.DrawRectangle(p, r);
}
}
}
//instructs 8051 to clear display
private void clearAll()
{
//because 8051 organizes LCD in bytes (i.e. 8 pixels at a time)
//essentially only 8 rows need to be cleared
for (int i = 0; i < 64; i += 8)
{
for (int j = 0; j < 128; j++)
{
Line temp = new Line(i, j);
byte[] toSend = temp.sendData();
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
}
}
}
//sync all pixels in the same column of the same page
//this prevents the turning on/off of one pixel to turn on/off other pixels in
//the same page and column
private void syncpixels(int y, int x)
{
int bitnumber = y % 8;
for (int i = 0; i <= 7; i++)
{
if (isShaded[(y - bitnumber) + i][x] && i != bitnumber)
{
if (i == 0)
{
pages[y][x].select0();
}
if (i == 1)
{
pages[y][x].select1();
}
if (i == 2)
{
pages[y][x].select2();
}
if (i == 3)
{
pages[y][x].select3();
}
if (i == 4)
{
pages[y][x].select4();
}
if (i == 5)
{
pages[y][x].select5();
}
if (i == 6)
{
pages[y][x].select6();
}
if (i == 7)
{
pages[y][x].select7();
}
}
}
}
//when mouse is pressed, tests if it clicks a pixel on the GUI
//if yes, see which pixel clicked
//and send appropriate pixel data to 8051
private void mouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && serialPort1.IsOpen)
{
MouseX = Cursor.Position.X;
MouseY = Cursor.Position.Y;
int windowTop = this.Top;
int windowLeft = this.Left;
//get the pixel that mouse is on
int pixelX = 0;
int pixelY = 0;
int temp_X = 0;
int temp_Y = 0;
for (int i = 0; i < 128; i++)
{
for (int j = 0; j < 64; j++)
{
Rectangle temp = new Rectangle(i * 5, j * 5, 5, 5);
temp_X = windowLeft + i * 5 + 7;
temp_Y = windowTop + j * 5 + 30;
if ((MouseX - temp_X) <= 5 && (MouseY - temp_Y) <= 5)
{
pixelX = i;
pixelY = j;
isShaded[pixelY][pixelX] = (!isShaded[pixelY][pixelX]);
//indicate on GUI that pixel is on/off
if (isShaded[pixelY][pixelX])
{
g.FillRectangle(Brushes.Blue, temp);
g.DrawRectangle(p, temp);
}
else
{
g.FillRectangle(Brushes.White, pixelX * 5, pixelY * 5, 5, 5);
g.DrawRectangle(p, pixelX * 5, pixelY * 5, 5, 5);
}
byte[] toSend = pages[pixelY][pixelX].sendData();
byte page = toSend[0];
byte col_h = toSend[1];
byte col_l = toSend[2];
byte data = toSend[3];
syncpixels(pixelY, pixelX);
toSend = pages[pixelY][pixelX].sendData();
page = toSend[0];
col_h = toSend[1];
col_l = toSend[2];
data = toSend[3];
//send data to serial port
int bitnumber = pixelY % 8;
if (bitnumber == 0)
{
pages[pixelY][pixelX].select0();
}
if (bitnumber == 1)
{
pages[pixelY][pixelX].select1();
}
if (bitnumber == 2)
{
pages[pixelY][pixelX].select2();
}
if (bitnumber == 3)
{
pages[pixelY][pixelX].select3();
}
if (bitnumber == 4)
{
pages[pixelY][pixelX].select4();
}
if (bitnumber == 5)
{
pages[pixelY][pixelX].select5();
}
if (bitnumber == 6)
{
pages[pixelY][pixelX].select6();
}
if (bitnumber == 7)
{
pages[pixelY][pixelX].select7();
}
toSend = pages[pixelY][pixelX].sendData();
page = toSend[0];
col_h = toSend[1];
col_l = toSend[2];
data = toSend[3];
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
serialPort1.Write(toSend, 0, 4);
textBox1.Text = "X: " + pixelX + " Y: " + pixelY;
return;
}
}
}
}
}
//Column Byte Class
//A Line Object focuses on a certain pixel, but contains information of all pixels in the column
//With Bitwise operators, syncs with other pixels and flips its own state when clicked
public class Line
{
private int column;
private byte page;
private byte column_h;
private byte column_l;
private byte data;
public const byte PAGESTARTER = 176;
public const byte COL_H_STARTER = 16;
public const byte COL_L_STARTER = 0;
public Line(int point_Y, int col)
{
int page_number = point_Y / 8;
//set page byte
page = Convert.ToByte(page_number);
page = Convert.ToByte(page | PAGESTARTER);
byte ch = 0;
byte cl = 0;
string hexVal = col.ToString("X");
if (hexVal.Length == 1)
{
cl = Convert.ToByte(int.Parse(hexVal, System.Globalization.NumberStyles.HexNumber));
}
else
{
char[] digits = hexVal.ToCharArray();
ch = Convert.ToByte(int.Parse(digits[0].ToString(), System.Globalization.NumberStyles.HexNumber));
cl = Convert.ToByte(int.Parse(digits[1].ToString(), System.Globalization.NumberStyles.HexNumber));
}
//set column high
column = col;
column_h = Convert.ToByte(ch);
column_h = Convert.ToByte(column_h | COL_H_STARTER);
//set column low
column_l = Convert.ToByte(cl);
column_l = Convert.ToByte(column_l | COL_L_STARTER);
//initialize data byte
data = 0;
}
public void select0()
{
byte j = 1;
data = Convert.ToByte(data ^ j);
}
public void select1()
{
byte j = 2;
data = Convert.ToByte(data ^ j);
}
public void select2()
{
byte j = 4;
data = Convert.ToByte(data ^ j);
}
public void select3()
{
byte j = 8;
data = Convert.ToByte(data ^ j);
}
public void select4()
{
byte j = 16;
data = Convert.ToByte(data ^ j);
}
public void select5()
{
byte j = 32;
data = Convert.ToByte(data ^ j);
}
public void select6()
{
byte j = 64;
data = Convert.ToByte(data ^ j);
}
public void select7()
{
byte j = 128;
data = Convert.ToByte(data ^ j);
}
public byte[] sendData()
{
byte[] bytes = new byte[4];
bytes[0] = page;
bytes[1] = column_h;
bytes[2] = column_l;
bytes[3] = data;
return bytes;
}
}
}
}
|
6fc3f52266fc2bca301b0e36c051c21a8dc662f0
|
C#
|
barneayoav/BasicMemoryGame
|
/GameUI/GameSlot.cs
| 2.625
| 3
|
using System.Windows.Forms;
namespace GameUI
{
internal class GameSlot : Button
{
private readonly GameLogic.Point r_Point;
public GameSlot(int i_RowIndex, int i_ColumnIndex)
{
r_Point = new GameLogic.Point(i_RowIndex, i_ColumnIndex);
}
public GameLogic.Point SlotPoint
{
get
{
return r_Point;
}
}
}
}
|
96750df45b62ffdc2948505e3b890439c72f531e
|
C#
|
AzureDay/2017-WebSite
|
/TeamSpark.AzureDay.WebSite.App/Service/LanguageService.cs
| 2.765625
| 3
|
using System.Collections.Generic;
using System.Linq;
using TeamSpark.AzureDay.WebSite.App.Entity;
namespace TeamSpark.AzureDay.WebSite.App.Service
{
public sealed class LanguageService
{
private readonly List<Language> _languages = new List<Language>
{
new Language {Id = 1, Title = Localization.App.Service.Language.Ukrainian},
new Language {Id = 2, Title = Localization.App.Service.Language.Russian},
new Language {Id = 3, Title = Localization.App.Service.Language.English}
};
public IEnumerable<Language> GetLanguages()
{
return _languages.OrderBy(x => x.Title);
}
public Language Ukrainian { get { return _languages.Single(x => x.Id == 1); } }
public Language Russian { get { return _languages.Single(x => x.Id == 2); } }
public Language English { get { return _languages.Single(x => x.Id == 3); } }
}
}
|
265aaea40fd417774183dee311a9670082ae3223
|
C#
|
federicoangeloni/univaqSmartReminder
|
/Login.aspx.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Login : System.Web.UI.Page
{
private string encrypted_ticket;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string email = TextBoxLoginName.Text;
string password = TextBoxLoginPassword.Text;
bool persist = chkRememberMe.Checked;
DatabaseService dbService = new DatabaseService();
string sqlString = "SELECT * FROM Utenti WHERE email='" + email + "' AND password='" + password + "'";
SqlDataReader queryResult = dbService.Reader(sqlString);
if (queryResult.Read())
{
string user_data = queryResult[1].ToString() + " " + queryResult[2].ToString() + " " + queryResult[3].ToString() + " " + queryResult[6];
// Se le credenziali sono corrette ed è stato selezionato il checkbox per restare loggati creo cookie permanente
if (persist)
{
FormsAuthentication.SetAuthCookie(this.TextBoxLoginName.Text.Trim(), true);
FormsAuthenticationTicket ticket1 = new FormsAuthenticationTicket(
1, // Versione
this.TextBoxLoginName.Text.Trim(), // Nome del cookie (Username dalla form)
DateTime.Now, // Ora Attuale
DateTime.Now.AddMinutes(15), // Scadenza dopo 15 minuti
true, // Cookie Persistente
user_data // User data
);
encrypted_ticket = FormsAuthentication.Encrypt(ticket1);
}
// Altrimenti creo cookie non permanente
else
{
FormsAuthentication.SetAuthCookie(this.TextBoxLoginName.Text.Trim(), false);
FormsAuthenticationTicket ticket1 = new FormsAuthenticationTicket(
1, // Versione
this.TextBoxLoginName.Text.Trim(), // Nome del cookie (Username dalla form)
DateTime.Now, // Ora Attuale
DateTime.Now.AddMinutes(15), // Scadenza dopo 15 minuti
false, // Cookie NON Persistente
user_data // User data
);
encrypted_ticket = FormsAuthentication.Encrypt(ticket1);
}
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted_ticket);
Response.Cookies.Add(cookie1);
// Salvataggio data e ora dell'ultimo login dell'utente nel DB
DateTime actual_datetime = DateTime.Now;
string actual_dt = string.Format("{0:dd/MM/yyyy HH:mm:ss}", actual_datetime);
string sqlString_datasave = "UPDATE Utenti SET LastLoginDate = @data_ora WHERE Id = @id";
Tuple<string, Object, SqlDbType>[] sqlParams =
{
Tuple.Create<string, Object, SqlDbType>("@data_ora", actual_dt, SqlDbType.DateTime),
Tuple.Create<string, Object, SqlDbType>("@id", queryResult[0].ToString(), SqlDbType.Int),
};
dbService.ExecuteNonQuery(sqlString_datasave, sqlParams);
// Effettuo il redirect a seconda dell'esito del login
String returnUrl1;
// Se il login ha avuto successo
if (Request.QueryString["ReturnUrl"] == null)
{
returnUrl1 = "Pages_OnlyLoggedUser/Home.aspx";
}
// Altrimenti se il login non ha avuto successo
else
{
returnUrl1 = Request.QueryString["ReturnUrl"];
}
Response.Redirect(returnUrl1);
}
}
}
|
1f0dd6c741f67284ed5022443797d91b75408c91
|
C#
|
dvkudr/SampleCalculator
|
/CalculatorV2/BusinessLogic/Calculator.cs
| 3.1875
| 3
|
using System;
using CalculatorV2.Interfaces;
namespace CalculatorV2.BusinessLogic
{
public class Calculator : ICalculator
{
private readonly int _result;
private readonly IAdder _adder;
private readonly ISubstractor _substractor;
private readonly ISignReverter _signReverter;
public Calculator(IAdder adder, ISubstractor substractor, ISignReverter signReverter)
{
_result = 0;
_adder = adder;
_substractor = substractor;
_signReverter = signReverter;
}
private Calculator(int initValue, IAdder adder, ISubstractor substractor, ISignReverter signReverter)
{
_result = initValue;
_adder = adder;
_substractor = substractor;
_signReverter = signReverter;
}
public ICalculator Add(int value)
{
return new Calculator(_adder.Add(_result,value), _adder, _substractor, _signReverter);
}
public ICalculator Sub(int value)
{
return new Calculator(_substractor.Sub(_result, value), _adder, _substractor, _signReverter);
}
public ICalculator SignRevert()
{
return new Calculator(_signReverter.SignRevert(_result), _adder, _substractor, _signReverter);
}
public int Result => _result;
}
}
|
4a5476ca5c32048f9902c20c21533ca96a753373
|
C#
|
Minami83/KPLDrawing
|
/DrawingApp/Shapes/Line.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DrawingApp.Shapes
{
public class Line : DrawingObject
{
public Point startPoint { get; set; }
public Point endPoint { get; set; }
public List<List<DrawingObject>> observersList;
private Pen pen;
public Line()
{
this.object_type = "Line";
this.pen = new Pen(Color.Black);
pen.Width = 1.5f;
this.memento = new DrawingObjectMemento();
List<DrawingObject> empty_list = new List<DrawingObject>();
List<DrawingObject> empty_list2 = new List<DrawingObject>();
this.observersList = new List<List<DrawingObject>>();
this.observersList.Add(empty_list);
this.observersList.Add(empty_list2);
}
public Line(Point startPoint) : this()
{
this.startPoint = startPoint;
}
public Line(Point startPoint, Point endPoint) : this(startPoint)
{
this.endPoint = endPoint;
}
/*public override void draw()
{
this.Graphics.DrawLine(this.pen, startPoint, endPoint);
}*/
public override void translate(int xTrans, int yTrans)
{
this.startPoint = new Point(this.startPoint.X + xTrans, this.startPoint.Y + yTrans);
this.endPoint = new Point(this.endPoint.X + xTrans, this.endPoint.Y + yTrans);
this.onChange(xTrans, yTrans);
this.addMemento();
}
private float Distance(Point a, Point b)
{
return (float)Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
}
public override bool intersect(int x, int y)
{
Point clickedPoint = new Point(x, y);
float distToStart = Distance(startPoint, clickedPoint);
float distToEnd = Distance(clickedPoint, endPoint);
float distStartToEnd = Distance(startPoint, endPoint);
return (Math.Abs(distToStart + distToEnd - distStartToEnd) < 3.0);
}
public override void StaticView()
{
this.pen.Color = Color.Black;
this.Graphics.DrawLine(this.pen, startPoint, endPoint);
}
public override void EditView()
{
this.pen.Color = Color.Red;
this.Graphics.DrawLine(this.pen, startPoint, endPoint);
}
public override void onChange(int dx, int dy)
{
int i = 0;
foreach (List<DrawingObject> observers in observersList)
{
foreach (DrawingObject observer in observers)
{
observer.Update(i, dx, dy);
}
i++;
}
}
public override void addObserver(int type, DrawingObject observer)
{
this.observersList[type].Add(observer);
}
public override void removeObserver(int type, DrawingObject observer)
{
this.observersList[type].Remove(observer);
}
public override void addMemento()
{
Dictionary<string, Point> currentState = new Dictionary<string, Point>();
currentState.Add("start", this.startPoint);
currentState.Add("end", this.endPoint);
this.memento.saveUndoMemento(currentState);
}
public override bool removeMemento()
{
Dictionary<string, Point> lastState = this.memento.retriveUndoMemento();
if (lastState == null)
{
return false;
}
this.memento.saveRedoMemento(lastState);
int dx = lastState["start"].X - this.startPoint.X;
int dy = lastState["start"].Y - this.startPoint.Y;
this.startPoint = lastState["start"];
this.endPoint = lastState["end"];
onChange(dx, dy);
return true;
}
public override bool restoreMemento()
{
Dictionary<string, Point> lastState = this.memento.retriveRedoMemento();
if (lastState == null)
{
return false;
}
int dx = lastState["start"].X - this.startPoint.X;
int dy = lastState["start"].Y - this.startPoint.Y;
this.startPoint = lastState["start"];
this.endPoint = lastState["end"];
onChange(dx, dy);
return true;
}
public int getYinLine(int x)
{
double m = getSlope();
double closestYinLine = m * (x - startPoint.X) + startPoint.Y;
return (int)closestYinLine;
}
public double getSlope()
{
double m = (endPoint.Y - startPoint.Y) / (endPoint.X - startPoint.X);
return m;
}
public override void Update(int type, int dx, int dy)
{
if (type == 0) startPoint = new Point(startPoint.X + dx, startPoint.Y + dy);
else if (type == 1) endPoint = new Point(endPoint.X + dx, endPoint.Y + dy);
}
}
}
|
bc383f6daf7db0187ef4a02a327bb7497ef78095
|
C#
|
kyulee2/Algorithm
|
/SwapAdjacentInLRString/t1.cs
| 3.421875
| 3
|
/*
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.
Example:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: True
Explanation:
We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Note:
1 <= len(start) = len(end) <= 10000.
Both start and end will only consist of characters in {'L', 'R', 'X'}.
*/
// Comment: Initially just move pointer by 1 and try match even with swap.
// This failed with the following case (should return true) where the continuous X followed by L.
// As below, finding the first matching pair
//"XXXXXLXXXX"
//"LXXXXXXXXX"
public class Solution {
void Swap()
{
if (i+1 >=len) return;
char c1 = t[i];
if (c1=='X') {
// Try find the first L after X
int j = i + 1;
while(j<len && t[j] =='X') j++;
if (j<len && t[j] == 'L') {
t[i] = 'L';
t[j]= 'X';
}
}
else if (c1=='R') {
// Try find the first X after R
int j= i+1;
while(j<len && t[j] == 'R') j++;
if (j<len && t[j] == 'X') {
t[i] = 'X';
t[j] = 'R';
}
}
}
int len;
char[] t;
int i; // current index
public bool CanTransform(string start, string end) {
// Init data
len = start.Length;
if (len != end.Length) return false;
return Perform(start, end);
}
bool Perform(string start, string end) {
t = start.ToCharArray();
for(i =0; i<len; i++) {
char c = t[i];
char d = end[i];
if (c==d) continue;
Swap();
if (t[i] != end[i])
return false;
}
return true;
}
}
|
b527a7f79b72d8ab413a0a545bbcb4fd986f936d
|
C#
|
KevinRecuerda/Contest
|
/BattleDev/BattleDev.March18.Tests/Ex5.Tests.cs
| 3.015625
| 3
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BattleDev.March18.Ex5.Tests
{
[TestFixture]
public class ProgramTest
{
[TestCase(@"
4
0 2 6 1
2 0 8 9
6 8 0 3
1 9 3 0", @"
9")]
[TestCase(@"
8
0 61 81 26 95 80 27 90
61 0 36 23 26 13 63 51
81 36 0 24 29 86 68 24
26 23 24 0 73 72 14 41
95 26 29 73 0 17 47 71
80 13 86 72 17 0 44 28
27 63 68 14 47 44 0 35
90 51 24 41 71 28 35 0", @"
312")]
public void Test(string input, string output)
{
var consoleHelperForTests = new ConsoleHelperForTests(input);
Program.ConsoleHelper = consoleHelperForTests;
Program.Solve();
Assert.AreEqual(output.Trim(), consoleHelperForTests.Output.First());
}
public class ConsoleHelperForTests : ConsoleHelper
{
private readonly string[] input;
private int readIndex;
public readonly List<string> Output;
public ConsoleHelperForTests(string input)
: this(input.Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries))
{
}
public ConsoleHelperForTests(string[] input)
{
this.input = input;
this.readIndex = 0;
this.Output = new List<string>();
}
public override string ReadLine()
{
if (this.readIndex < this.input.Length)
return this.input[this.readIndex++];
return string.Empty;
}
public override void WriteLine(object obj)
{
this.Output.Add(obj.ToString());
}
}
}
}
|
da2bb35fd7a07eedf8ee52bab4d4a85d835f46de
|
C#
|
Gilmardealcantara/IntegrationTestsApi
|
/Api/Data/User.cs
| 2.53125
| 3
|
using FluentValidation;
namespace Api.Data
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string GitUserName { get; set; }
}
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(x => x.Id).NotNull().NotEmpty();
RuleFor(x => x.Name).NotNull().NotEmpty();
}
}
}
|
c178befd09c87c17b4bff6d5b078074f673bfa2a
|
C#
|
Dochko/SoftUni
|
/ProgrammingBasicsCourse/Operatiors And Expressions/08.Expressions/Expressions.cs
| 3.859375
| 4
|
using System;
class Expressions
{
static void Main()
{
int r = (150 - 20) / 2 + 5; // r = 70
//Expression for calculating a circle area
double surface = Math.PI * r * r;
//Expression for calculating a circle perimeter
double perimeter = 2 * Math.PI * r;
int a = 2 + 3; // a = 5
int b = (a + 3) * (a - 4) + (2 * a + 7) / 4; //b = 12
bool greater = (a > b) || ((a == 0) && (b == 0));
Console.WriteLine(greater);
}
}
|
9428712a338c4a8cd6838f53dbbf15a5fc44eb47
|
C#
|
paulpjryan/Sudoku
|
/SudokuGraphics/GameOverWindow.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
namespace SudokuGraphics
{
public class GameOverWindow : Form
{
int hours;
int minutes;
int seconds;
Button buttonQuit;
Button buttonNG;
public GameOverWindow( int hrs, int mins, int secs )
{
this.seconds = secs;
this.hours = hrs;
this.minutes = mins;
this.Size = new Size(250, 350);
this.Text = "Game Over.";
this.buttonQuit = new Button();
buttonQuit.Size = new Size(100, 20);
buttonQuit.Name = "buttonQuit";
buttonQuit.Text = "Quit";
this.buttonNG = new Button();
buttonNG.Size = new Size(100, 20);
buttonNG.Name = "buttonNG";
buttonNG.Text = "New Game";
buttonQuit.Location = new Point(ClientRectangle.Width / 2 - buttonQuit.Width / 2 - buttonNG.Width / 2 - 5, ClientRectangle.Height - 40);
buttonNG.Location = new Point( ClientRectangle.Width / 2 - buttonQuit.Width / 2 + buttonNG.Width / 2 + 5, ClientRectangle.Height - 40 );
this.Controls.AddRange(new Control[] { buttonQuit, buttonNG });
buttonQuit.Show();
buttonNG.Show();
buttonQuit.Click += new EventHandler(buttonQuit_Click);
buttonNG.Click += new EventHandler(buttonNG_Click);
this.FormClosed += new FormClosedEventHandler(GameOverWindow_FormClosed);
this.Paint += new PaintEventHandler(GameOverWindow_Paint);
}
void buttonNG_Click(object sender, EventArgs e)
{
this.Hide();
Sudoku s = new Sudoku();
s.Show();
}
void buttonQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
void GameOverWindow_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
string results = string.Format("You did it!\nTime: {0:00}:{1:00}:{2:00}\nPress \"New Game\" to start again.\nPress \"Quit\" to quit.", hours, minutes, seconds);
g.DrawString(results, new Font("Arial", 10), Brushes.Black, new RectangleF(0, 0, ClientRectangle.Width, ClientRectangle.Height), sf);
}
void GameOverWindow_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
|
77bec49b1841941f21b1a596d4612c1b55ed6026
|
C#
|
WickedFlame/RubberStamp
|
/src/RubberStamp.UnitTest/Conditions/CustomPropertyConditionTests.cs
| 2.671875
| 3
|
using RubberStamp.Conditions;
using NUnit.Framework;
namespace RubberStamp.UnitTest.Conditions
{
[TestFixture]
public class CustomPropertyConditionTests
{
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_String_Valid_Test()
{
var condition = new CustomPropertyCondition<TestClass, string>(c => c.Name, (c, p) => p != null);
Assert.IsTrue(condition.IsValid(new TestClass { Name = "TEST" }));
}
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_String_Invalid_Test()
{
var condition = new CustomPropertyCondition<TestClass, string>(c => c.Name, (c, p) => p != null);
Assert.IsFalse(condition.IsValid(new TestClass { Name = null }));
}
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_Int_Valid_Test()
{
var condition = new CustomPropertyCondition<TestClass, int>(c => c.Index, (c, p) => p > 0);
Assert.IsTrue(condition.IsValid(new TestClass { Index = 1 }));
}
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_Int_Invalid_Test()
{
var condition = new CustomPropertyCondition<TestClass, int>(c => c.Index, (c, p) => p > 0);
Assert.IsFalse(condition.IsValid(new TestClass { Index = 0 }));
}
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_ValidateUnequalType_Valid_Test()
{
var condition = new CustomPropertyCondition<TestClass, string>(c => c.Name, (c, p) => p != null) as IValidationCondition<TestClass>;
Assert.IsTrue(condition.IsValid(new TestClass { Name = "TEST" }));
}
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_Int_Message_Test()
{
var condition = new CustomPropertyCondition<TestClass, string>(c => c.Name, (c, p) => p != null);
Assert.AreEqual("The Property Name caused a validation error", condition.Message);
}
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_String_Message_Test()
{
var condition = new CustomPropertyCondition<TestClass, int>(c => c.Index, (c, p) => p > 0);
Assert.AreEqual("The Property Index caused a validation error", condition.Message);
}
[Test]
public void RubberStamp_Conditions_CustomPropertyCondition_SetMessage_Test()
{
var condition = new CustomPropertyCondition<TestClass, int>(c => c.Index, (c, p) => p > 0)
.SetMessage("Error message");
Assert.AreEqual("Error message", condition.Message);
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestClass
{
// ReSharper disable once UnusedAutoPropertyAccessor.Local
public string Name { get; set; }
// ReSharper disable once UnusedAutoPropertyAccessor.Local
public int Index { get; set; }
}
}
}
|
640c41e3d4e3b0acb96a982bc0f6a710daddd5d2
|
C#
|
JingChao94/WatermarkGenerator
|
/WatermarkGenerator/WaterMarkGenerator.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WatermarkGenerator
{
public partial class WaterMarkGenerator : Form
{
private string strSavePath = string.Empty, strExt = ".jpg";
private Image img;
private Bitmap bitmap;
private FileInfo[] fileInfo;
public WaterMarkGenerator()
{
InitializeComponent();
img = pbImgView.Image;
tbConstructionArea.SelectAll();
tbEndFloor.LostFocus += TextLostFocus;
tbHomeNumber.LostFocus += TextLostFocus;
tbWorkArea.LostFocus += TextLostFocus;
}
private void TextLostFocus(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Name.Equals("tbEndFloor"))
{
if (!(int.Parse(tb.Text.Trim()) >= int.Parse(tbStartFloor.Text.Trim())))
{
tb.Text = tbStartFloor.Text.Trim();
}
}
if (tb.Name.Equals("tbHomeNumber"))
{
if (string.IsNullOrWhiteSpace(tb.Text.Trim()))
{
tb.Text = "01";
}
}
if (tb.Name.Equals("tbWorkArea"))
{
if (string.IsNullOrWhiteSpace(tb.Text.Trim()))
{
tb.Text = "公卫";
}
strSavePath = string.Format("{0}\\PIC\\{1}\\", Application.StartupPath, tbWorkArea.Text);
if (!Directory.Exists(strSavePath))
{
MessageBox.Show(string.Format("{0}目录未创建.", tbWorkArea.Text));
tbWorkArea.Focus();
}
}
}
private new void TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (!int.TryParse(tb.Text.Trim(), out int floorNumber))
{
tb.Text = "1";
}
}
private void btnLoadImg_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == DialogResult.OK)
{
strSavePath = openFile.FileName.Replace(openFile.SafeFileName, string.Format(""));
strExt = openFile.SafeFileName.Substring(openFile.SafeFileName.LastIndexOf('.'));
DirectoryInfo directoryInfo = Directory.CreateDirectory(strSavePath);
fileInfo = directoryInfo.GetFiles();
pbImgView.Load(openFile.FileName);
img = pbImgView.Image;
btnView.Enabled = true;
btnSave.Enabled = true;
}
}
private void btnView_Click(object sender, EventArgs e)
{
bitmap = DrawWaterMark(tbStartFloor.Text.Trim());
pbImgView.Image = bitmap;
}
private void WaterMarkGenerator_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private Bitmap DrawWaterMark(string floorNumber)
{
Bitmap bitmap = new Bitmap(img);
Graphics g = Graphics.FromImage(bitmap);
//设置质量
g.SmoothingMode = SmoothingMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
//InterpolationMode不能使用High或者HighQualityBicubic,如果是灰色或者部分浅色的图像是会在边缘处出一白色透明的线
//用HighQualityBilinear却会使图片比其他两种模式模糊(需要肉眼仔细对比才可以看出)
g.InterpolationMode = InterpolationMode.Default;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
int imgWidth = img.Width;
int imgHeight = img.Height;
//蓝色区域
int blueRectX = imgWidth / 19;
int blueRectY = imgHeight - imgHeight / 4 - imgHeight / 20;
int blueRectWidth = imgWidth / 2;
int blueRectHeight = (imgHeight / 5 / 4) * 1;
if (imgWidth > imgHeight)
{
blueRectWidth = imgHeight / 2;
blueRectHeight = (imgWidth / 2 / 9) * 1;
}
Rectangle blueRect = new Rectangle(blueRectX, blueRectY, blueRectWidth, blueRectHeight);
FillRoundRectangle(g, new SolidBrush(Color.FromArgb(176, 0, 0, 255)), blueRect, blueRectWidth / 14, true);
g.DrawString("工程记录", new Font("黑体", blueRect.Width / 15), Brushes.White, (float)(blueRect.Width / 2.5), blueRect.Y + blueRect.Height / 5);
//白色区域
int whiteRectY = blueRectY + (imgHeight / 5 / 4) * 1;
int whiteRectHeight = (imgHeight / 5 / 4) * 3;
if (imgWidth > imgHeight)
{
whiteRectY = blueRectY + (imgWidth / 2 / 9) * 1;
whiteRectHeight = (imgHeight / 2 / 9) * 4;
}
Rectangle whiteRect = new Rectangle(blueRectX, whiteRectY, blueRectWidth, whiteRectHeight);
FillRoundRectangle(g, new SolidBrush(Color.FromArgb(176, Color.GhostWhite)), whiteRect, blueRectWidth / 14, false);
int coefficient = 0;
string viewStr = string.Format("{0}{1}{2}", lblConstructionArea.Text, tbConstructionArea.Text.Trim() + floorNumber + tbHomeNumber.Text.Trim() + tbWorkArea.Text, Environment.NewLine);
viewStr = viewStr.Length > 18 ? viewStr.Insert(17, "\r\n ") : viewStr;
g.DrawString(viewStr, new Font("黑体", whiteRect.Width / 21), Brushes.Black, blueRect.Width / 7, whiteRect.Y + blueRect.Height / 4);
if (viewStr.Length > 18)
{
coefficient++;
}
viewStr = string.Format("{0}{1}{2}", lblLocation.Text, tbLocation.Text.Trim(), Environment.NewLine);
viewStr = viewStr.Length > 18 ? viewStr.Insert(17, "\r\n ") : viewStr;
g.DrawString(viewStr, new Font("黑体", whiteRect.Width / 21), Brushes.Black, blueRect.Width / 7, whiteRect.Y + blueRect.Height / 4 + ((whiteRect.Width / 21) * (2 + coefficient)));
if (viewStr.Length > 18)
{
coefficient++;
}
viewStr = string.Format("{0}{1}{2}", lblRemarks.Text, tbRemarks.Text.Trim(), Environment.NewLine);
viewStr = viewStr.Length > 18 ? viewStr.Insert(17, "\r\n ") : viewStr;
g.DrawString(viewStr, new Font("黑体", whiteRect.Width / 21), Brushes.Black, blueRect.Width / 7, whiteRect.Y + blueRect.Height / 4 + ((whiteRect.Width / 21) * (4 + coefficient)));
//黄色圆点
g.FillEllipse(Brushes.Yellow, new Rectangle(blueRectX + blueRectWidth / 13, blueRectY + (blueRectHeight/ 4), blueRectWidth / 25, blueRectWidth / 25));
g.Dispose();
return bitmap;
}
private void btnSave_Click(object sender, EventArgs e)
{
btnSave.Enabled = false;
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
//按下确定选择的按钮
if (folderDialog.ShowDialog() == DialogResult.OK)
{
InitFileList();
//记录选中的目录
strSavePath = folderDialog.SelectedPath + "\\";
}
else
{
btnSave.Enabled = true;
return;
}
frmProgress progress = new frmProgress();
progress.Show();
int startFloor = int.Parse(tbStartFloor.Text.Trim());
int endFloor = int.Parse(tbEndFloor.Text.Trim());
int floorCount = endFloor - startFloor;
Random random = new Random();
string homeNumber = tbHomeNumber.Text.Trim();
for (int i = 0; i <= floorCount; i++)
{
try
{
int currentFloorNumber = startFloor;
string savePath = strSavePath + "Mark\\";
int fileNumber = random.Next(0, fileInfo.Length - 1);
img = Image.FromFile(fileInfo[fileNumber].FullName);
Application.DoEvents();
bitmap = DrawWaterMark(currentFloorNumber.ToString());
if (File.Exists(savePath))
{
File.Delete(savePath);
}
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
savePath += startFloor + homeNumber + strExt;
SaveImage2File(savePath, bitmap, 50);
//bitmap.Save(savePath);
progress.Invoke(new Action(delegate
{
progress.RefreshView(i + 1, floorCount + 1, this.Bounds.X, this.Bounds.Y, this.Bounds.Width, this.Bounds.Height);
}));
startFloor++;
}
catch
{
int fileNumber = random.Next(0, fileInfo.Length - 1);
img = Image.FromFile(fileInfo[fileNumber].FullName);
}
}
progress.Close();
btnSave.Enabled = true;
//pbImgView.Image.Save(strSavePath);
}
private void SaveImage2File(string path, Image destImage, int quality, string mimeType = "image/jpeg")
{
if (quality <= 0 || quality > 100) quality = 95;
//创建保存的文件夹
FileInfo fileInfo = new FileInfo(path);
if (!Directory.Exists(fileInfo.DirectoryName))
{
Directory.CreateDirectory(fileInfo.DirectoryName);
}
EncoderParameters ep = new EncoderParameters(2);
long[] qy = new long[1];
qy[0] = 90;//设置压缩的比例1-100
EncoderParameter eParam1 = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
EncoderParameter eParam2 = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 5);
ep.Param[0] = eParam1;
ep.Param[1] = eParam2;
ImageCodecInfo myImageCodecInfo = GetEncoderInfo(mimeType);
CompressImage(destImage, path);
//destImage.Save(path, myImageCodecInfo, ep);
}
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片地址</param>
/// <param name="dFile">压缩后保存图片地址</param>
/// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
/// <param name="size">压缩后图片的最大大小</param>
/// <param name="sfsc">是否是第一次调用</param>
/// <returns></returns>
public bool CompressImage(Image sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
{
////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
//FileInfo firstFileInfo = new FileInfo(sFile);
//if (sfsc == true && firstFileInfo.Length < size * 1024)
//{
// firstFileInfo.CopyTo(dFile);
// return true;
//}
Image iSource = sFile;
ImageFormat tFormat = iSource.RawFormat;
int dHeight = iSource.Height / 2;
int dWidth = iSource.Width / 2;
int sW = 0, sH = 0;
//按比例缩放
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Width > dHeight || tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
FileInfo fi = new FileInfo(dFile);
if (fi.Length > 1024 * size)
{
flag = flag - 10;
CompressImage(sFile, dFile, flag, size, false);
}
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
private ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
private void InitFileList()
{
strSavePath = string.Format("{0}\\PIC\\{1}\\", Application.StartupPath, tbWorkArea.Text);
DirectoryInfo directoryInfo = Directory.CreateDirectory(strSavePath);
fileInfo = directoryInfo.GetFiles();
}
private void FillRoundRectangle(Graphics g, Brush brush, Rectangle rect, int cornerRadius, bool radiusIsTop)
{
using (GraphicsPath path = CreateRoundedRectanglePath(rect, cornerRadius, radiusIsTop))
{
g.FillPath(brush, path);
}
}
private GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int cornerRadius, bool radiusIsTop)
{
GraphicsPath roundedRect = new GraphicsPath();
if (radiusIsTop)
{
roundedRect.AddArc(rect.X, rect.Y, cornerRadius * 2, cornerRadius * 2, 180, 90);
roundedRect.AddLine(rect.X, rect.Y, rect.Right, rect.Y);
}
else
{
roundedRect.AddLine(rect.X + cornerRadius, rect.Y, rect.Right - cornerRadius * 2, rect.Y);
}
if (radiusIsTop)
{
roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y, cornerRadius * 2, cornerRadius * 2, 270, 90);
roundedRect.AddLine(rect.Right, rect.Y, rect.Right, rect.Y + rect.Height);
}
else
{
roundedRect.AddLine(rect.Right, rect.Y, rect.Right, rect.Y + rect.Height);
}
if (!radiusIsTop)
{
roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y + rect.Height - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);
roundedRect.AddLine(rect.Right, rect.Bottom, rect.X, rect.Bottom);
}
else
{
roundedRect.AddLine(rect.Right - cornerRadius * 2, rect.Bottom, rect.X + cornerRadius * 2, rect.Bottom);
roundedRect.AddLine(rect.X, rect.Y + rect.Height, rect.X, rect.Y + rect.Height);//顶部左下角补齐
}
if (!radiusIsTop)
{
roundedRect.AddArc(rect.X, rect.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);
roundedRect.AddLine(rect.X, rect.Bottom, rect.X, rect.Y);
}
else
{
roundedRect.AddLine(rect.X, rect.Bottom - cornerRadius * 2, rect.X, rect.Y + cornerRadius * 2);
}
roundedRect.CloseFigure();
return roundedRect;
}
}
}
|
5521ae738df6ecc314048f10d94b061b613df1c0
|
C#
|
krso92/horrorclimatechange
|
/HorrorClimateChange/Assets/Sisus/Power Inspector/Code/Drawers/Interfaces/IUnityObjectDrawer.cs
| 2.515625
| 3
|
using System;
namespace Sisus
{
/// <summary>
/// Interface implemented by drawer representing UnityEngine.Objects other than GameObjects.
/// This includes Components, ScriptableObjects and assets.
///
/// NOTE: Not implemented by ObjectReferenceDrawer, which only represents a *reference* to an
/// UnityEngine.Object.
/// </summary>
public interface IUnityObjectDrawer : IParentDrawer
{
/// <summary>
/// Gets the minimum width for the prefix label column.
/// Some Editors might need this to be larger than the default value.
/// </summary>
/// <value> The minimum width for prefix label column. </value>
float MinPrefixLabelWidth { get; }
/// <summary>
/// Gets the maximum width for the prefix label column.
/// Some Editors might need this to be larger than the default value.
/// </summary>
/// <value> The maximum width for prefix label column. </value>
float MaxPrefixLabelWidth { get; }
/// <summary> Gets a value indicating whether the prefix resizer control is currently mouseovered. </summary>
/// <value> True if prefix resizer is mouseovered, false if not. </value>
bool PrefixResizerMouseovered { get; }
/// <summary>
/// Gets a value indicating whether the header has currently keyboard focus.
/// This is true if any part of the header has keyboard focus, not just the base.
/// </summary>
/// <value> True if header is selected, false if not. </value>
bool HeaderIsSelected { get; }
/// <summary> Delegate callback invoked every time that Inspector width or prefix width has changed. </summary>
/// <value> The on widths changed. </value>
Action OnWidthsChanged { get; set; }
/// <summary> Gets or sets the width of the prefix label. </summary>
/// <value> The width of the prefix label. </value>
float PrefixLabelWidth { get; set; }
/// <summary> Gets the prefix resizer type to use for the drawer. </summary>
/// <value> The prefix resizer type. </value>
PrefixResizer PrefixResizer { get; }
/// <summary> Enables Debug Mode+ for the drawer. </summary>
void EnableDebugMode();
/// <summary> Disables Debug Mode+ for the drawer. </summary>
void DisableDebugMode();
/// <summary> Visually pings the drawer in the inspector. </summary>
void Ping();
}
}
|
2521fa9ffc8c365dbc0d86d112409061b6f10a3a
|
C#
|
Alain-es/Routing
|
/Routing/App_Code/Helpers/EncryptionHelper.cs
| 2.6875
| 3
|
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Umbraco.Core.Logging;
namespace Routing.Helpers
{
public class EncryptionHelper
{
private static byte[] salt = Encoding.ASCII.GetBytes(@"%rtal/Z_2kd*1s$(/_ªkdl¨Ñña4y9iue");
private static string keyPadding = @"ªQa7_!1·Z$0mVt%z&S_r/5ke*b2(3)y4u=8?¿9;";
public static string EncryptAES(string text, string key)
{
string result = text;
if (!string.IsNullOrWhiteSpace(text))
{
Rfc2898DeriveBytes saltKey = new Rfc2898DeriveBytes(key + keyPadding, salt);
using (MemoryStream memoryStream = new MemoryStream())
{
using (StreamWriter streamWriter = new StreamWriter(new CryptoStream(memoryStream, new RijndaelManaged().CreateEncryptor(saltKey.GetBytes(32), saltKey.GetBytes(16)), CryptoStreamMode.Write)))
{
streamWriter.Write(text);
streamWriter.Close();
}
memoryStream.Close();
result = Convert.ToBase64String(memoryStream.ToArray());
}
}
return result;
}
public static string DecryptAES(string text, string key)
{
string result = text;
if (!string.IsNullOrWhiteSpace(text))
{
try
{
Rfc2898DeriveBytes saltKey = new Rfc2898DeriveBytes(key + keyPadding, salt);
using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(text)))
{
using (StreamReader streamReader = new StreamReader(new CryptoStream(memoryStream, new RijndaelManaged().CreateDecryptor(saltKey.GetBytes(32), saltKey.GetBytes(16)), CryptoStreamMode.Read)))
{
result = streamReader.ReadToEnd();
}
}
}
catch (Exception ex)
{
result = string.Empty;
LogHelper.Error<EncryptionHelper>("Error in the method DecryptAES(). Wrong key.", ex);
}
}
return result;
}
}
}
|
9be44c9bb3a591990aabf4f6030c1a11be72b178
|
C#
|
MarcalMontserrat/code-challenge-5
|
/TrainReservation/TrainReservation/Seat.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrainReservation
{
public class Seat
{
public string Coach { get; set; }
public string Seat_Number { get; set; }
public string booking_reference { get; set; }
public string GetName()
{
return this.Seat_Number + this.Coach;
}
//public Seat(string coach, int seatNumber)
//{
// this.Coach = coach;
// this.SeatNumber = seatNumber;
//}
//public override int GetHashCode()
//{
// return base.GetHashCode();
//}
//public override bool Equals(object obj)
//{
// Seat seat = obj as Seat;
// if (this.Coach == seat.Coach)
// return this.SeatNumber == seat.SeatNumber;
// else
// return false;
//}
}
}
|
2d5bb948b97f0eb8f73c812192ea424aa908591d
|
C#
|
robrecht-scheepers/media-center
|
/MediaCenter/MediaCenter/Helpers/SerializationHelper.cs
| 2.984375
| 3
|
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace MediaCenter.Helpers
{
public class SerializationHelper
{
public static T Deserialize<T>(string jsonString)
{
T obj = default(T);
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof (T));
obj = (T) ser.ReadObject(stream);
}
return obj;
}
public static string Serialize<T>(T t)
{
string jsonString;
using (MemoryStream stream = new MemoryStream())
{
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings();
ds.WriteObject(stream, t);
jsonString = Encoding.UTF8.GetString(stream.ToArray());
}
return jsonString;
}
}
}
|
a27255e739a61c77a9a81199c9a9ae78e4c1bd6d
|
C#
|
juszi28/school_works
|
/C#/EVA-2.ZH/zh_winform/zh_i7p4uq/zh_i7p4uq/Model/GameModel.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using zh_i7p4uq.Persistence;
namespace zh_i7p4uq.Model
{
class GameModel
{
private IPersistence dataAccess;
private int[,] map;
private int castleHP;
private Random random;
private int enemyHitCount;
private int soldierCount;
private int elapsedTime;
private List<(int, int)> enemies;
private bool timerState;
public int Size { get; set; }
public int Soldier { get { return soldierCount; } }
public event EventHandler<RefreshArgs> Refresh;
public event EventHandler GameOver;
public GameModel(IPersistence persistence)
{
dataAccess = persistence;
random = new Random();
enemies = new List<(int, int)>();
}
public void NewGame()
{
enemies.Clear();
Size = 10;
map = new int[Size,Size];
soldierCount = 2;
enemyHitCount = 0;
castleHP = 3;
elapsedTime = 0;
for(int i = 0; i < Size; ++i)
{
for (int j = 0; j < Size; j++)
{
map[i, j] = 0;
}
}
timerState = true;
}
public void Step() //a játék folytatása
{
//eddigi ellenfelek mozgatása
for (int i = 0; i < enemies.Count; i++)
{
int prevEnemiesCount = enemies.Count;
map[enemies[i].Item1, enemies[i].Item2] = 0;
int x = enemies[i].Item1; x--;
if (x == -1)
{
castleHP--;
enemies.Remove(enemies[i]);
}
else
{
(int, int) newCoords = (x, enemies[i].Item2);
enemies.Remove(enemies[i]);
enemies.Insert(i, (newCoords));
//csekkolni az ütközéseket
if (map[enemies[i].Item1, enemies[i].Item2] == 1)
{
map[enemies[i].Item1, enemies[i].Item2] = 0;
++enemyHitCount;
enemies.Remove(enemies[i]);
}
else if (inMap(enemies[i].Item1, enemies[i].Item2 - 1) && map[enemies[i].Item1, enemies[i].Item2 - 1] == 1)
{
map[enemies[i].Item1, enemies[i].Item2] = 0;
++enemyHitCount;
enemies.Remove(enemies[i]);
}
else if (inMap(enemies[i].Item1, enemies[i].Item2 + 1) && map[enemies[i].Item1 + 1, enemies[i].Item2 + 1] == 1)
{
map[enemies[i].Item1, enemies[i].Item2] = 0;
++enemyHitCount;
enemies.Remove(enemies[i]);
}
else
map[enemies[i].Item1, enemies[i].Item2] = 2;
}
if (prevEnemiesCount > enemies.Count)
{
i = i - (prevEnemiesCount - enemies.Count);
}
if (enemyHitCount >= 3)
{
++soldierCount;
enemyHitCount -= 3;
}
}
//új ellenfelek spawnolása
int enemyCount = random.Next(0, 3);
for (int i = 0; i < enemyCount; ++i)
{
(int, int) enemyCoord = GenerateEnemy();
map[enemyCoord.Item1, enemyCoord.Item2] = 2;
enemies.Add(enemyCoord);
}
++elapsedTime;
OnRefresh();
if (castleHP <= 0)
OnGameOver();
}
public void PauseNPlay()
{
timerState = timerState ? false : true;
}
private void OnGameOver()
{
GameOver?.Invoke(this, new EventArgs());
}
public void PlaceSoldier(int x, int y)
{
if (timerState)
{
if (soldierCount > 0 && map[x, y] == 0)
{
--soldierCount;
map[x, y] = 1; // 1 a katona, 2 az ellenség
OnRefresh();
}
else
return;
}
}
public async Task LoadGameAsync(string path)
{
if (dataAccess == null)
throw new InvalidOperationException("No data access is provided!");
//betöltés
State table = await dataAccess.LoadAsync(path);
castleHP = table.CastleHP;
elapsedTime = table.ElapsedTime;
enemyHitCount = table.EnemyHitCount;
soldierCount = table.SoldierCount;
enemies = table.Enemies;
map = table.Map;
OnRefresh();
}
public async Task SaveGameAsync(string path)
{
if (dataAccess == null)
throw new InvalidOperationException("No data access is provided.");
State table = new State(castleHP, elapsedTime, enemyHitCount, soldierCount, enemies, map);
await dataAccess.SaveAsync(path, table);
}
private (int, int) GenerateEnemy()
{
int y = random.Next(0, Size);
while (map[Size-1, y] != 0)
{
y = random.Next(0, Size);
}
return (Size-1, y);
}
private bool inMap(int x, int y)
{
return x >= 0 && x < Size && y >= 0 && y < Size;
}
private void OnRefresh()
{
Refresh?.Invoke(this, new RefreshArgs(castleHP, soldierCount, map, elapsedTime));
}
}
}
|
f5b74d11815950dd6082e89939bf4d0d4b2cc2c5
|
C#
|
hse-programming-CSharp2020-2021/207ShulminPavel
|
/Module 4/Sem 6/CW/Task 2/Program.cs
| 3.703125
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Task_2
{
interface IVocal
{
void DoSound();
}
public abstract class Animal : IVocal
{
static int id = 1;
public abstract void DoSound();
public int Id { get; set; }
public string Name { get; set; }
public bool IsTakenCare { get; set; }
public override string ToString()
{
return $"{Id} {Name} {IsTakenCare}";
}
public Animal (string name, bool isTakenCare)
{
Name = name;
IsTakenCare = isTakenCare;
Id = id;
id++;
}
}
class Mammal : Animal
{
public int Paws { get; set; }
public Mammal(string name, bool isTakenCare, int paws) : base(name, isTakenCare)
{
Paws = paws;
}
public override void DoSound()
{
Console.WriteLine("я млекопитающие, би-би-би");
}
public override string ToString()
{
return base.ToString() + " " + Paws.ToString();
}
}
class Bird : Animal
{
public int Speed { get; set; }
public Bird(string name, bool isTakenCare, int speed) : base(name, isTakenCare)
{
Speed = speed;
}
public override void DoSound()
{
Console.WriteLine("я птичка, пип-пип-пип");
}
public override string ToString()
{
return base.ToString() + " " + Speed.ToString();
}
}
class Zoo : IEnumerable
{
public Animal[] Animals { get; set; }
public Zoo(Animal[] animals)
{
Animals = animals;
}
public IEnumerator GetEnumerator()
{
return Animals.GetEnumerator();
}
}
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int n = int.Parse(Console.ReadLine());
Animal[] animals = new Animal[n];
for (int i = 0; i < n; i++)
{
int type = rand.Next(2);
bool isTakenCare = false;
switch (rand.Next(2))
{
case 0:
isTakenCare = false;
break;
case 1:
isTakenCare = true;
break;
}
switch (type)
{
case 0:
animals[i] = new Mammal(rand.Next().ToString(), isTakenCare, rand.Next(1, 21));
break;
case 1:
animals[i] = new Bird(rand.Next().ToString(), isTakenCare, rand.Next(1, 101));
break;
}
}
Zoo zoo = new Zoo(animals);
Console.WriteLine("Перекличка");
foreach (Animal a in zoo)
a.DoSound();
var birds = zoo.Animals.Where(a => a is Bird && a.IsTakenCare).ToList();
Console.WriteLine("Птицы с опекуном");
foreach (Bird a in birds)
Console.WriteLine(a);
var mammals = zoo.Animals.Where(a => a is Mammal && !a.IsTakenCare).ToList();
Console.WriteLine("Млекопитающие без опекуна");
foreach (Mammal a in mammals)
Console.WriteLine(a);
}
}
}
|
1630d229cd37ba724de59bd6b9d0b5a8c7358fee
|
C#
|
Nemoom/FestoCubeExplorer
|
/Festo Rubik‘s Cube Explorer/UserLogin.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Festo_Rubik_s_Cube_Explorer
{
public static class UserLogin
{
private static bool _isLoggedIn = false;
private static string iniPath = "config.ini";
public static bool IsLoggedIn
{
get
{
return _isLoggedIn;
}
set
{
_isLoggedIn = value;
}
}
public static string Hash(string input)
{
// http://stackoverflow.com/questions/17292366/hashing-with-sha1-algorithm-in-c-sharp
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
[Obsolete("this decode method is not use any more.")]
private static string decodePassword(string s)
{
var bytes = Convert.FromBase64String(new string(s.Replace("$", "=").Reverse().ToArray()));
return Encoding.UTF8.GetString(bytes);
}
private static string encodePassword(string s)
{
return Hash(s);
//var b64string = Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
//return new string(b64string.Replace("=", "$").Reverse().ToArray());
}
public static string Password
{
get
{
if (File.Exists(iniPath))
{
IniFile ini = new IniFile(iniPath);
if (!ini.KeyExists("password", "authorization"))
{
return null;
}
string pwd = ini.Read("password", "authorization");
try
{
//return decodePassword(pwd);
return pwd;
}
catch (Exception)
{
return null;
}
}
return null;
}
set
{
if (value.Length > 100) // too long
{
return;
}
else
{
var encodedPwd = encodePassword(value);
if (File.Exists(iniPath))
{
IniFile ini = new IniFile(iniPath);
ini.Write("password", encodedPwd, "authorization");
}
}
}
}
}
}
|
391aea46228854c96b587b8049684a3fbc75e4d1
|
C#
|
dlampa/ProjectEulerSolutions
|
/ProjectEulerProblems/Solutions/Problem7.cs
| 3.875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEulerSolutions.Solutions
{
public static class Problem7
{
/*
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
*/
public static long Solve(bool output = false)
{
int primeCount = 6;
int lastPrime = 13;
while (primeCount < 10001)
{
// Prime numbers will be odd
lastPrime += 2;
bool isPrime(int n)
{
// If n is between 1(exclusive) and 3(inclusive) it's a prime number
if ((n > 1) && (n <= 3)) return true;
// If n is divisible by 2 or 3, n is not a prime number
if ((n % 2 == 0) || (n % 3 == 0)) return false;
// Primality test: https://en.wikipedia.org/wiki/Primality_test
for (int k = 1; k <= ((Math.Sqrt(n)+1)/6); k++)
{
// If n is divisible by a number (6k+-1) <= sqrt(n), it's not a prime number.
if ((n % (6 * k + 1) == 0) || (n % (6 * k - 1) == 0)) return false;
}
return true;
}
if (isPrime(lastPrime))
{
primeCount += 1;
if (output) Console.WriteLine($"{primeCount}:{lastPrime}");
}
}
return lastPrime;
}
}
}
|
7f49fda311d009f1407df107cd37d8cf52e1fe88
|
C#
|
Praetox/Tools
|
/pImgDB_v0,0,6,6/pImgDB/fBitmap.cs
| 2.78125
| 3
|
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace pImgDB
{
public unsafe class fBitmap
{
public struct pixData
{
public byte a;
public byte b;
public byte g;
public byte r;
public pixData(byte bA, byte bR, byte bG, byte bB)
{
a = bA; r = bR; g = bG; b = bB;
}
}
Bitmap bPic;
int iPicW;
BitmapData bData = null;
Byte* pBase = null;
public fBitmap(Bitmap b, bool bConv)
{
Init(b, bConv);
}
public fBitmap(Bitmap b)
{
Init(b, true);
}
public void Init(Bitmap b, bool bConv)
{
if (bConv)
{
System.IO.MemoryStream ms =
new System.IO.MemoryStream();
b.Save(ms, ImageFormat.Bmp);
b = new Bitmap(ms);
}
this.bPic = b;
try { LockBM(); }
catch (Exception ex)
{
throw ex;
}
}
public void Flush()
{
try { UnlockBM(); }
catch (Exception ex)
{
throw ex;
}
}
public Bitmap Bitmap
{
get { return bPic; }
}
public void pixSet(int x, int y, pixData col)
{
try
{
pixData* p = pixAt(x, y);
p->a = col.a;
p->r = col.r;
p->g = col.g;
p->b = col.b;
}
catch (AccessViolationException ave) { throw (ave); }
catch (Exception ex) { throw ex; }
}
public pixData pixGet(int x, int y)
{
try
{
pixData* p = pixAt(x, y);
return new pixData(p->a, p->r, p->g, p->b); //(int)
}
catch (AccessViolationException ave) { throw (ave); }
catch (Exception ex) { throw ex; }
}
public void LockBM()
{
GraphicsUnit unit = GraphicsUnit.Pixel;
RectangleF boundsF = bPic.GetBounds(ref unit);
Rectangle bounds = new Rectangle(
(int)boundsF.X,
(int)boundsF.Y,
(int)boundsF.Width,
(int)boundsF.Height);
iPicW = (int)boundsF.Width * sizeof(pixData);
if (iPicW % 4 != 0)
iPicW = 4 * (iPicW / 4 + 1);
bData = bPic.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
pBase = (Byte*)bData.Scan0.ToPointer();
}
private pixData* pixAt(int x, int y)
{
return (pixData*)(pBase + y * iPicW + x * sizeof(pixData));
}
private void UnlockBM()
{
bPic.UnlockBits(bData);
bData = null; pBase = null;
}
}
}
|
1cc66b7af010f28b2580c82ddbd8961e337be6a9
|
C#
|
Bullsized/Assignments-Fundamentals-Normal
|
/10 - 12 Data Types and Var/2017-06-03/15 Balanced Brackets/15 Balanced Brackets.cs
| 3.546875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _15_Balanced_Brackets
{
class Program
{
static void Main(string[] args)
{
int rotation = int.Parse(Console.ReadLine());
int countOpen = 0;
int countClose = 0;
string doubleOpening = string.Empty;
bool lamp = false;
for (int cycle = 0; cycle < rotation; cycle++)
{
string bracketsOrNot = Console.ReadLine();
if (bracketsOrNot == "(")
{
countOpen++;
if (bracketsOrNot == doubleOpening && doubleOpening == "(")
{
Console.WriteLine("UNBALANCED");
lamp = true;
break;
}
}
else if (bracketsOrNot == ")")
{
countClose++;
}
doubleOpening = bracketsOrNot;
}
if (countOpen == countClose && lamp == false)
{
Console.WriteLine("BALANCED");
}
else if (countOpen != countClose && lamp == false)
{
Console.WriteLine("UNBALANCED");
}
}
}
}
|
e13775ba2d4d595ef2bca58fdef6ff9f7b050cee
|
C#
|
StockSharp/StockSharp
|
/Messages/IComplexIdMessage.cs
| 2.515625
| 3
|
namespace StockSharp.Messages;
/// <summary>
/// The interface describing an message with <see cref="Id"/> property.
/// </summary>
public interface IComplexIdMessage
{
/// <summary>
/// ID.
/// </summary>
long? Id { get; }
/// <summary>
/// ID (as string, if electronic board does not use numeric ID representation).
/// </summary>
string StringId { get; }
}
|
ecb000665c50ce0adaaf9eedb4f64eb778fec298
|
C#
|
iensenfirippu/stalkr
|
/Visual Studio/StalkrAdmin/StalkrAdmin/Form1.cs
| 2.59375
| 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 MySql.Data.MySqlClient;
namespace StalkrAdmin
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String server = "10.139.109.96:8080";
String database = "stalkr";
String uid = "root";
String password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
MySqlConnection connection = new MySqlConnection(connectionString);
textBox1.Text = connection.ConnectionString;
//connection.Open();
//string query = "SELECT username FROM user WHERE id = 1";
//MySqlCommand cmd = new MySqlCommand(query, connection);
//MySqlDataReader dataReader = cmd.ExecuteReader();
//while (dataReader.Read())
//{
// textBox1.Text = dataReader["username"] + "";
//}
}
}
}
|