Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
61576e8adae4949608a968b6e951b7f79830c8dc
C#
sunxiaotianmg/FCS
/src/FCS/CRC16CCITT_Implementation.cs
3.234375
3
using System; using System.IO; namespace FCS { public static class CRC16CCITT_Implementation { /// <summary> /// The initial CRC remainder as specified by the CRC-CCITT (Kermit) protocol. /// </summary> public const ushort InitialCrcRemainder = 0x0; /// <summary> /// The generator polynomial defined for the CRC-CCITT (Kermit) algorithm. /// </summary> /// <remarks> /// The polynomial x16 + x12 + x5 + 1 is represented as /// 1 0001 0000 0010 0001 /// The high order bit (x^16) is always on, so don't need to store it (it is implied by the algorithm). /// => 0001 0000 0010 0001 /// Invert the order because this implementation works on the bits in reverse order (LSB to MSB) /// => 1000 0100 0000 1000 => 0x8408 /// </remarks> private const int KermitGeneratorPolynomial = 0x8408; /// <summary> /// The size of the precalculated byte CRC table (256 possible values for an 8 bit byte); /// </summary> private const int ByteTableSize = 256; /// <summary> /// Precalculated table of byte CRC's /// </summary> static readonly ushort[] ByteCrcTable = new ushort[ByteTableSize]; static CRC16CCITT_Implementation() { for (int i = 0; i < ByteTableSize; ++i) { ushort crc = InitialCrcRemainder; ushort data = (ushort)i; for (int j = 0; j < 8; ++j) { if (((crc ^ data) & 0x0001) != 0) { crc = (ushort)((crc >> 1) ^ KermitGeneratorPolynomial); } else { crc >>= 1; } data >>= 1; } ByteCrcTable[i] = crc; } } /// <summary> /// Computes the CRC for the given byte array /// </summary> /// <param name="bytes"></param> /// <returns>the computed CRC value as an unsigned short</returns> public static ushort ComputeCrc(byte[] bytes) { return ComputeCrc(bytes, InitialCrcRemainder, 0, bytes.LongLength); } public static ushort ComputeCrc(Stream stream) { return ComputeCrc(stream, InitialCrcRemainder, 0, stream.Length); } public static ushort ComputeCrc(byte[] bytes, ushort initial) { return ComputeCrc(bytes, initial, 0, bytes.LongLength); } public static ushort ComputeCrc(Stream stream, ushort initial) { return ComputeCrc(stream, initial, 0, stream.Length); } /// <summary> /// Computes the checkSum for the given byte array with offset and count based on initial crc. /// </summary> /// <param name="initial">The initial value of crc</param> /// <param name="bytes">byte array to compute crc of</param> /// <param name="offset">the offset at which to start computing</param> /// <param name="count">the number of bytes to compute</param> /// <returns>the computed CRC value as an unsigned short</returns> /// <remarks>Used for iterating over a byte stream so doesn't have to be all loaded into memory at once.</remarks> public static ushort ComputeCrc(byte[] bytes, ushort initial, long offset, long count) { ushort crc = initial; long end = offset + count; // Divide the message by the polynomial, a byte at a time. for (long j = offset; j < end; j++) { byte data = (byte)((crc & 0xff) ^ bytes[j]); crc = (ushort)(ByteCrcTable[data] ^ (crc >> 8)); } return crc; } public static ushort ComputeCrc(Stream stream, ushort initial, long offset, long count) { if (count <= int.MaxValue) { stream.Seek(offset, SeekOrigin.Begin); byte[] bytes = new byte[count]; stream.Read(bytes, 0, Convert.ToInt32(count)); return ComputeCrc(bytes, initial, 0, count); } else { long readCount = 0; while (readCount < count) { int read = (count - readCount) >= int.MaxValue ? int.MaxValue : Convert.ToInt32(count - readCount); initial = ComputeCrc(stream, initial, offset + readCount, read); readCount += read; } return initial; } } } }
d024325184e6d494a698127e64c2a8b6329bab6d
C#
fishonline/API-1
/Youffer.API/Youffer.API/Youffer.Resources/Enum/Industry.cs
2.578125
3
// --------------------------------------------------------------------------------------------------- // <copyright file="Industry.cs" company="Youffer"> // Copyright (c) 2014 All Right Reserved // </copyright> // <author>Akanksha Vats</author> // <date>2014-11-19</date> // <summary> // The Industry class // </summary> // --------------------------------------------------------------------------------------------------- namespace Youffer.Resources.Enum { /// <summary> /// Enum Industry /// </summary> public enum Industry { /// <summary> /// The none /// </summary> None = 0, /// <summary> /// The apparel /// </summary> Apparel = 1, /// <summary> /// The banking /// </summary> Banking = 2, /// <summary> /// The biotechnology /// </summary> Biotechnology = 3, /// <summary> /// The chemicals /// </summary> Chemicals = 4, /// <summary> /// The communications /// </summary> Communications = 5, /// <summary> /// The construction /// </summary> Construction = 6, /// <summary> /// The consulting /// </summary> Consulting = 7, /// <summary> /// The education /// </summary> Education = 8, /// <summary> /// The electronics /// </summary> Electronics = 9, /// <summary> /// The energy /// </summary> Energy = 10, /// <summary> /// The engineering /// </summary> Engineering = 11, /// <summary> /// The entertainment /// </summary> Entertainment = 12, /// <summary> /// The environmental /// </summary> Environmental = 13, /// <summary> /// The finance /// </summary> Finance = 14, /// <summary> /// The food_ beverage /// </summary> Food_Beverage = 15, /// <summary> /// The government /// </summary> Government = 16, /// <summary> /// The health care /// </summary> HealthCare = 17, /// <summary> /// The hospitality /// </summary> Hospitality = 18, /// <summary> /// The insurance /// </summary> Insurance = 19, /// <summary> /// The machinery /// </summary> Machinery = 20, /// <summary> /// The manufacturing /// </summary> Manufacturing = 21, /// <summary> /// The media /// </summary> Media = 22, /// <summary> /// The not_ for_ profit /// </summary> Not_For_Profit = 23, /// <summary> /// The recreation /// </summary> Recreation = 24, /// <summary> /// The retail /// </summary> Retail = 25, /// <summary> /// The shipping /// </summary> Shipping = 26, /// <summary> /// The technology /// </summary> Technology = 27, /// <summary> /// The telecommunications /// </summary> Telecommunications = 28, /// <summary> /// The transportation /// </summary> Transportation = 29, /// <summary> /// The utilities /// </summary> Utilities = 30, /// <summary> /// The other /// </summary> Other = 31 } }
f7e72bb6413d650c27d4ae69245ede0fe9d81ec2
C#
lsantoss/WCF
/Passagens/Hosting/Program.cs
2.8125
3
using Passagens; using System; using System.ServiceModel; using System.ServiceModel.Description; namespace Hosting { class Program { static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(ClienteService)); Uri endereco = new Uri("http://localhost:3030/clientes"); host.AddServiceEndpoint(typeof(IClienteService), new BasicHttpBinding(), endereco); try { host.Open(); ExibeInformacoesServico(host); Console.ReadLine(); host.Close(); } catch (Exception ex) { host.Abort(); Console.WriteLine(ex.Message); Console.ReadLine(); } } public static void ExibeInformacoesServico(ServiceHost sh) { Console.WriteLine($"{sh.Description.ServiceType} online"); foreach(ServiceEndpoint se in sh.Description.Endpoints) { Console.WriteLine(se.Address); } } } }
7ae9eafacd6bbc5db7f684de162478cd886ac6c4
C#
AaronAmberman/SNORM
/SNORM/SNORM/SqlInformationService.cs
2.734375
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; namespace SNORM { /// <summary>Helps retrieve information about tables from the database.</summary> public static class SqlInformationService { private static Dictionary<string, List<SqlColumnInfo>> tableColumns = new Dictionary<string, List<SqlColumnInfo>>(); private static bool GetAutoIncrementStatus(SqlConnection connection, string tableName, Action<string> log, List<SqlColumnInfo> columns, SqlTransaction sqlTransaction = null) { // next get the auto increment step (increment in database) and seed string query = "SELECT [column].name, [column].is_identity, ident_incr([table].name) as identity_increment, ident_seed([table].name) as identity_seed " + "FROM sys.tables[table] " + "INNER JOIN sys.columns[column] ON[table].object_id = [column].object_id " + "WHERE[table].name = @tableName AND [column].is_identity = 1"; SqlParameter tableNameParameter = new SqlParameter("@tableName", tableName); object[][] results = SimpleSqlService.ExecuteQuery(connection, false, log, query, CommandType.Text, sqlTransaction, tableNameParameter); if (results == null) { log("Unable get auto increment (identity) information from the table. Failure."); return false; } foreach (object[] row in results) { SqlColumnInfo matchingColumn = columns.FirstOrDefault(col => col.Name.Equals(row[0].ToString(), StringComparison.OrdinalIgnoreCase)); if (matchingColumn != null) { matchingColumn.AutoIncrement = true; matchingColumn.AutoIncrementStep = int.Parse(row[2].ToString(), CultureInfo.CurrentCulture); matchingColumn.AutoIncrementSeed = int.Parse(row[3].ToString(), CultureInfo.CurrentCulture); } } return true; } private static List<SqlColumnInfo> GetBasicColumnInformation(SqlConnection connection, string tableName, Action<string> log, SqlTransaction sqlTransaction = null) { List<SqlColumnInfo> columns = new List<SqlColumnInfo>(); string query = "SELECT COLUMN_NAME, ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName"; SqlParameter tableNameParameter = new SqlParameter("@tableName", tableName); object[][] results = SimpleSqlService.ExecuteQuery(connection, false, log, query, CommandType.Text, sqlTransaction, tableNameParameter); if (results == null) { log("Unable get basic column information from the table. Failure."); return null; } foreach (object[] row in results) { SqlColumnInfo column = new SqlColumnInfo { Name = row[0].ToString(), OrdinalPosition = int.Parse(row[1].ToString(), CultureInfo.CurrentCulture), DefaultValue = row[2], IsNullable = row[3].ToString().Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false, Type = GetSqlDbTypeFromString(row[4].ToString()) }; // only if we have a length do we want to set one otherwise leave it -1 if (row[5] != null) { column.Length = int.Parse(row[5].ToString(), CultureInfo.CurrentCulture); } columns.Add(column); } return columns; } private static List<ForeignKey> GetForeignKeysForTable(SqlConnection connection, string tableSchema, string tableName, Action<string> log, SqlTransaction sqlTransaction = null) { string query = "SELECT KCU1.CONSTRAINT_SCHEMA AS FK_CONSTRAINT_SCHEMA, " + "KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME, " + "KCU1.TABLE_SCHEMA AS FK_TABLE_SCHEMA, " + "KCU1.TABLE_NAME AS FK_TABLE_NAME, " + "KCU1.COLUMN_NAME AS FK_COLUMN_NAME, " + "KCU1.ORDINAL_POSITION AS FK_ORDINAL_POSITION, " + "KCU2.CONSTRAINT_SCHEMA AS REFERENCED_CONSTRAINT_SCHEMA, " + "KCU2.CONSTRAINT_NAME AS REFERENCED_CONSTRAINT_NAME, " + "KCU2.TABLE_SCHEMA AS REFERENCED_TABLE_SCHEMA, " + "KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME, " + "KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME, " + "KCU2.ORDINAL_POSITION AS REFERENCED_ORDINAL_POSITION " + "FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC " + "INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 " + "ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG " + "AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA " + "AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME " + "INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 " + "ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG " + "AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA " + "AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME " + "AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION " + "WHERE (KCU1.TABLE_SCHEMA = @tableSchema AND KCU1.TABLE_NAME = @tableName) " + "OR (KCU2.TABLE_SCHEMA = @tableSchema AND KCU2.TABLE_NAME = @tableName)" + "AND RC.CONSTRAINT_CATALOG = @databaseName"; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connection.ConnectionString); SqlParameter databaseNameParameter = new SqlParameter("@databaseName", builder.InitialCatalog); SqlParameter tableSchemaParameter = new SqlParameter("@tableSchema", tableSchema); SqlParameter tableNameParameter = new SqlParameter("@tableName", tableName); object[][] results = SimpleSqlService.ExecuteQuery(connection, false, log, query, CommandType.Text, sqlTransaction, databaseNameParameter, tableSchemaParameter, tableNameParameter); if (results == null) { log($"Unable to retrieve the foreign key information for the table {tableSchema}.{tableName}"); return null; } List<ForeignKey> foreignKeys = new List<ForeignKey>(); foreach (object[] row in results) { ForeignKey fk = new ForeignKey { Name = row[1].ToString(), ChildTableSchema = row[2].ToString(), ChildTableName = row[3].ToString(), ChildColumnName = row[4].ToString(), ParentTableSchema = row[8].ToString(), ParentTableName = row[9].ToString(), ParentColumnName = row[10].ToString() }; foreignKeys.Add(fk); } return foreignKeys; } private static bool GetPrimaryKeyStatus(SqlConnection connection, string tableSchema, string tableName, Action<string> log, List<SqlColumnInfo> columns, SqlTransaction sqlTransaction = null) { // next get if column is primary key (or part of multi-column primary key) string query = "SELECT kcu.COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu " + "INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON kcu.CONSTRAINT_CATALOG = tc.CONSTRAINT_CATALOG AND kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA AND kcu.TABLE_NAME = tc.TABLE_NAME " + "WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = @tableSchema AND tc.TABLE_NAME = @tableName"; SqlParameter tableNameParameter = new SqlParameter("@tableName", tableName); SqlParameter tableSchemaParameter = new SqlParameter("@tableSchema", tableSchema); object[][] results = SimpleSqlService.ExecuteQuery(connection, false, log, query, CommandType.Text, sqlTransaction, tableSchemaParameter, tableNameParameter); if (results == null) { log("Unable get primary key information from the table. Failure."); return false; } foreach (object[] row in results) { SqlColumnInfo matchingColumn = columns.FirstOrDefault(col => col.Name.Equals(row[0].ToString(), StringComparison.OrdinalIgnoreCase)); if (matchingColumn != null) { matchingColumn.IsPrimaryKey = true; } } return true; } // list of type names from: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings private static SqlDbType GetSqlDbTypeFromString(string value) { if (value.Equals("bigint", StringComparison.OrdinalIgnoreCase)) return SqlDbType.BigInt; else if (value.Equals("binary", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Binary; else if (value.Equals("bit", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Bit; else if (value.Equals("char", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Char; else if (value.Equals("date", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Date; else if (value.Equals("datetime", StringComparison.OrdinalIgnoreCase)) return SqlDbType.DateTime; else if (value.Equals("datetime2", StringComparison.OrdinalIgnoreCase)) return SqlDbType.DateTime2; else if (value.Equals("datetimeoffset", StringComparison.OrdinalIgnoreCase)) return SqlDbType.DateTimeOffset; else if (value.Equals("decimal", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Decimal; else if (value.Equals("float", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Float; else if (value.Equals("image", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Image; else if (value.Equals("int", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Int; else if (value.Equals("money", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Money; else if (value.Equals("nchar", StringComparison.OrdinalIgnoreCase)) return SqlDbType.NChar; else if (value.Equals("ntext", StringComparison.OrdinalIgnoreCase)) return SqlDbType.NText; else if (value.Equals("nvarchar", StringComparison.OrdinalIgnoreCase)) return SqlDbType.NVarChar; else if (value.Equals("real", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Real; else if (value.Equals("smalldatetime", StringComparison.OrdinalIgnoreCase)) return SqlDbType.SmallDateTime; else if (value.Equals("smallint", StringComparison.OrdinalIgnoreCase)) return SqlDbType.SmallInt; else if (value.Equals("smallmoney", StringComparison.OrdinalIgnoreCase)) return SqlDbType.SmallMoney; else if (value.Equals("text", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Text; else if (value.Equals("time", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Time; else if (value.Equals("timestamp", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Timestamp; else if (value.Equals("tinyint", StringComparison.OrdinalIgnoreCase)) return SqlDbType.TinyInt; else if (value.Equals("uniqueidentifier", StringComparison.OrdinalIgnoreCase)) return SqlDbType.UniqueIdentifier; else if (value.Equals("varbinary", StringComparison.OrdinalIgnoreCase)) return SqlDbType.VarBinary; else if (value.Equals("varchar", StringComparison.OrdinalIgnoreCase)) return SqlDbType.VarChar; else if (value.Equals("xml", StringComparison.OrdinalIgnoreCase)) return SqlDbType.Xml; else throw new NotSupportedException("The value could parsed into SqlDbType."); } /// <summary>Gets the column information for the table.</summary> /// <param name="connection">The connection to the database.</param> /// <param name="tableSchema">The schema that owns the table.</param> /// <param name="tableName">The table name to get column information about.</param> /// <param name="log">The method to call to write log messages to (only errors are logged).</param> /// <param name="sqlTransaction">The transaction to assign to the command. Default is null.</param> /// <returns>A list of columns containing metadata about each column or null if an error occurred.</returns> public static List<SqlColumnInfo> GetTableInformation(SqlConnection connection, string tableSchema, string tableName, Action<string> log, SqlTransaction sqlTransaction = null) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connection.ConnectionString); // we'll check to see if our dictionary contains our collection of columns already if (tableColumns.ContainsKey($"{builder.InitialCatalog}.{tableSchema}.{tableName}")) { return tableColumns[$"{builder.InitialCatalog}.{tableSchema}.{tableName}"]; } try { List<SqlColumnInfo> columns = GetBasicColumnInformation(connection, tableName, log, sqlTransaction); if (!GetAutoIncrementStatus(connection, tableName, log, columns, sqlTransaction)) { return null; } if (!GetPrimaryKeyStatus(connection, tableSchema, tableName, log, columns, sqlTransaction)) { return null; } // finally get foreign key information about the column List<ForeignKey> foreignKeys = GetForeignKeysForTable(connection, tableSchema, tableName, log, sqlTransaction); if (foreignKeys != null) { // first check child name for match List<ForeignKey> childForeignKeys = foreignKeys.Where(fk => fk.ChildTableSchema == tableSchema && fk.ChildTableName == tableName).ToList(); foreach (ForeignKey childFk in childForeignKeys) { SqlColumnInfo matchingColumn = columns.FirstOrDefault(col => col.Name.Equals(childFk.ChildColumnName, StringComparison.OrdinalIgnoreCase)); matchingColumn?.ForeignKeys.Add(childFk); } // second check parent name for match List<ForeignKey> parentForeignKeys = foreignKeys.Where(fk => fk.ParentTableSchema == tableSchema && fk.ParentTableName == tableName).ToList(); foreach (ForeignKey parentFk in parentForeignKeys) { SqlColumnInfo matchingColumn = columns.FirstOrDefault(col => col.Name.Equals(parentFk.ParentColumnName, StringComparison.OrdinalIgnoreCase)); matchingColumn?.ForeignKeys.Add(parentFk); } } tableColumns.Add($"{builder.InitialCatalog}.{tableSchema}.{tableName}", columns); return columns; } catch (Exception ex) { log($"An error occurred during GetTableInformation...{Environment.NewLine}{ex}"); return null; } } } }
37fe062b3e80cd9d6a4e9712e07c81077e8a87ca
C#
jmarolf/EditorConfigLanguage
/src/Schema/SchemaCatalog.cs
2.515625
3
using Microsoft.VisualStudio.Imaging; using System; using System.Collections.Generic; using System.Linq; namespace EditorConfig { public class SchemaCatalog { public const string Root = "root"; public static IEnumerable<Keyword> Properties { get; } = GetProperties(); public static IEnumerable<Severity> Severities { get; } = GetSeverities(); private static IEnumerable<Keyword> GetProperties() { Category category = Category.Standard; yield return new Keyword(Root, Schema.Text.KeywordRoot, category, "true", "false"); yield return new Keyword("charset", Schema.Text.KeywordCharset, category, "latin1", "utf-8", "utf-8-bom", "utf-16be", "utf-16le", "utf-8-bom"); yield return new Keyword("end_of_line", Schema.Text.KeywordEndOfLine, category, "lf", "crlf", "cr"); yield return new Keyword("indent_style", Schema.Text.KeywordIndentStyle, category, "tab", "space"); yield return new Keyword("indent_size", Schema.Text.KeywordIndentSize, category, "tab"); yield return new Keyword("tab_width", Schema.Text.KeywordTabWidth, category); yield return new Keyword("trim_trailing_whitespace", Schema.Text.KeywordTrimTrailingWhitespace, category, "true", "false") { IsSupported = false }; yield return new Keyword("insert_final_newline", Schema.Text.KeywordInsertFinalNewline, category, "true", "false") { IsSupported = false }; category = Category.CSharp; yield return new Keyword("csharp_style_conditional_delegate_call", "Prefer conditional delegate calls.", category, "true", "false"); yield return new Keyword("csharp_style_expression_bodied_accessors", "Prefer expression-bodied members.", category, "true", "false"); yield return new Keyword("csharp_style_expression_bodied_constructors", "Prefer expression-bodied members", category, "true", "false"); yield return new Keyword("csharp_style_expression_bodied_indexers", "Prefer expression-bodied members", category, "true", "false"); yield return new Keyword("csharp_style_expression_bodied_methods", "Prefer expression-bodied members.", category, "true", "false"); yield return new Keyword("csharp_style_expression_bodied_operators", "Prefer expression-bodied members.", category, "true", "false"); yield return new Keyword("csharp_style_expression_bodied_properties", "Prefer expression-bodied members", category, "true", "false"); yield return new Keyword("csharp_style_inlined_variable_declaration", "Prefer to inline variable declaration.", category, "true", "false"); yield return new Keyword("csharp_style_pattern_matching_over_as_with_null_check", "Prefer pattern matching.", category, "true", "false"); yield return new Keyword("csharp_style_pattern_matching_over_is_with_cast_check", "Prefer pattern matching.", category, "true", "false"); yield return new Keyword("csharp_style_throw_expression", "Prefer throw expressions", category, "true", "false"); yield return new Keyword("csharp_style_var_elsewhere", "Prefer var elsewhere.", category, "true", "false"); yield return new Keyword("csharp_style_var_for_built_in_types", "Prefer var for built-in types.", category, "true", "false"); yield return new Keyword("csharp_style_var_for_locals", "Prefer var for locals.", category, "true", "false"); yield return new Keyword("csharp_style_var_when_type_is_apparent", "Prefer var when type is apparent.", category, "true", "false"); category = Category.DotNet; yield return new Keyword("dotnet_style_coalesce_expression", "Prefer null coalescing operator (??).", category, "true", "false"); yield return new Keyword("dotnet_style_collection_initializer", "Prefer collection intiailizers.", category, "true", "false"); yield return new Keyword("dotnet_style_null_propagation", "Prefer null propagation (?.).", category, "true", "false"); yield return new Keyword("dotnet_style_object_initializer", "Prefer object initializers.", category, "true", "false"); yield return new Keyword("dotnet_style_predefined_type_for_locals_parameters_members", "Prefer language types (e.g. int, string, float).", category, "true", "false"); yield return new Keyword("dotnet_style_predefined_type_for_member_access", "Prefer language types (e.g. int, string, float).", category, "true", "false"); yield return new Keyword("dotnet_style_qualification_for_event", "Prefer this for events.", category, "true", "false"); yield return new Keyword("dotnet_style_qualification_for_field", "Prefer this for fields.", category, "true", "false"); yield return new Keyword("dotnet_style_qualification_for_method", "Prefer this for methods.", category, "true", "false"); yield return new Keyword("dotnet_style_qualification_for_property", "Prefer this for properties.", category, "true", "false"); } private static IEnumerable<Severity> GetSeverities() { yield return new Severity("none", Schema.Text.SeverityNone, KnownMonikers.None); yield return new Severity("suggestion", Schema.Text.SeveritySuggestion, KnownMonikers.StatusInformation); yield return new Severity("warning", Schema.Text.SeverityWarning, KnownMonikers.StatusWarning); yield return new Severity("error", Schema.Text.SeverityError, KnownMonikers.StatusError); } public static bool TryGetProperty(string name, out Keyword property) { property = Properties.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); return property != null; } public static bool TryGetSeverity(string name, out Severity severity) { severity = Severities.FirstOrDefault(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); return severity != null; } } }
3f48068292b95fc5f182cd8d52135e95a359a52e
C#
Sequenta/CalculatorOperations
/BaseOperations/BaseOperations.Test/DivideTests.cs
2.65625
3
using System; using Xunit; namespace BaseOperations.Test { public class DivideTests { Divide divide = new Divide(); [Fact] public void Operation_PerformsCorrectly() { var result = divide.Perform(new double[] { 36, 36 }); Assert.Equal(1, result); } [Fact] public void Throws_DivideByZeroException() { Assert.Throws<DivideByZeroException>(() => divide.Perform(new double[] {0, 36})); } } }
ec9e95e2601ad157c50a860288bc4650bd33dc40
C#
marsscotia/TalkAbout
/TalkAbout/Actions/PageScrollAction.cs
2.625
3
using Microsoft.Xaml.Interactivity; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace TalkAbout.Actions { /// <summary> /// Class provides a page scrolling action for a scrollviewer. /// /// Up or Down must be set to true to provide a direction for the /// scroll. /// </summary> class PageScrollAction : DependencyObject, IAction { public static readonly DependencyProperty TargetObjectProperty = DependencyProperty.Register("TargetObject", typeof(object), typeof(PageScrollAction), null); public bool Up { get; set; } = false; public bool Down { get; set; } = false; public object TargetObject { get { return GetValue(TargetObjectProperty); } set { SetValue(TargetObjectProperty, value); } } public object Execute(object sender, object parameter) { bool result = false; object target; if (ReadLocalValue(TargetObjectProperty) != DependencyProperty.UnsetValue) { target = TargetObject; } else { target = sender; } if (target != null) { ListViewBase view = null; ScrollViewer scroll = null; if (target.GetType() == typeof(SemanticZoom)) { SemanticZoom semanticZoom = (SemanticZoom)target; if (semanticZoom.Visibility == Visibility.Visible) { if (semanticZoom.IsZoomedInViewActive) { view = (ListViewBase)semanticZoom.ZoomedInView; } else { view = (ListViewBase)semanticZoom.ZoomedOutView; } } } else if (target.GetType() == typeof(ListView)) { ListView listView = (ListView)target; if (listView.Visibility == Visibility.Visible) { view = listView; } } if(view != null) { scroll = _getScrollViewer(view); if (Up) { if (scroll.VerticalOffset > scroll.ViewportHeight / 2) { scroll.ChangeView(null, scroll.VerticalOffset - (scroll.ViewportHeight / 2), null); } else { scroll.ChangeView(null, 0, null); } result = true; } if (Down) { if (scroll.ScrollableHeight - scroll.VerticalOffset > 0) { if (scroll.ScrollableHeight - scroll.VerticalOffset > scroll.ViewportHeight / 2) { scroll.ChangeView(null, scroll.VerticalOffset + (scroll.ViewportHeight / 2), null); } else { scroll.ChangeView(null, scroll.ScrollableHeight, null); } } result = true; } } } return result; } private ScrollViewer _getScrollViewer(DependencyObject element) { ScrollViewer viewer = null; if (element is ScrollViewer) { viewer = (ScrollViewer)element; } else { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { var child = VisualTreeHelper.GetChild(element, i); var result = _getScrollViewer(child); if (result != null) { viewer = result; } } } return viewer; } } }
b7ba1bce5eef5b08165a94eb553d1e1017a33d6e
C#
Scarnet/Fakka.Pos
/Fakka.Pos/Fakka.Core/Converters/BytesToImageConverter.cs
2.71875
3
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using Xamarin.Forms; namespace Fakka.Core.Converters { public class BytesToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ImageSource source = null; if (value == null) return source; byte[] imageBytes = (byte[])value; source = ImageSource.FromStream(() => new MemoryStream(imageBytes)); return source; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
370cd507ffbe22fd7428cf4cc24fc17570e3136e
C#
Pojemnik/OutOfSpaceUnity
/Assets/scripts/MusicManager.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MusicManager : MonoBehaviour { public List<AudioClip> music; private int currentMusic; private AudioSource audioSource; void Awake() { audioSource = GetComponent<AudioSource>(); audioSource.clip = music[0]; audioSource.Play(); currentMusic = 0; } void Update() { if(!audioSource.isPlaying) { currentMusic++; currentMusic %= music.Count; audioSource.clip = music[currentMusic]; audioSource.Play(); } } }
8dcd9cfacb3685775593c6f07b0a8621a8564557
C#
KristiyanGochev/TelerikHomework
/Programing/C#/C# - Part 2/II - 08 - Текстови файлове/II - 08 - Текстови файлове/Program.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; //Write a program that reads a text file and prints on the console its odd lines. namespace II___08___Текстови_файлове { class Program { static void Main(string[] args) { int n = 1; using (StreamReader file = new StreamReader("../../Program.cs")) { for (string row; (row = file.ReadLine()) != null; n++) { if (n % 2 == 1) { Console.WriteLine(row); } } } } } }
b8e7009d09acfcffa8109386977afc18ffc72d6f
C#
Aandriy/MedicalCard
/MedicalCard/ViewModels/RegisterViewModel.cs
2.578125
3
using MedicalCard.Models; using System; using System.ComponentModel.DataAnnotations; namespace MedicalCard.ViewModels { public class RegisterViewModel { [Required] [MaxLength(256)] public string Email { get; set; } [Required] [DataType(DataType.Date)] //[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")] public DateTime Birthday { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Required] [MaxLength(256)] public string FirstName { get; set; } [MaxLength(256)] public string MiddleName { get; set; } [Required] [MaxLength(256)] public string LastName { get; set; } public GenderEnum Gender { get; set; } } }
01747a9ada7adf604fdaac62408f48e48693a32b
C#
Casper-Nielsen/Symmetrisk_Encryption_Example
/Symmetrisk_Encryption_Example/MainViewModel.cs
2.953125
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Text; using System.Windows.Input; namespace Symmetrisk_Encryption_Example { class MainViewModel : INotifyPropertyChanged { private Encryption encryption; private ObservableCollection<EncryptionType> ecryptionOptions; private EncryptionType selectedEncryptionType; private string planTextUTF8 = ""; private string encryptedBase64 = ""; private string encryptionTime; private string decryptionTime; public ICommand GenerateCommand { get; set; } public ICommand EncryptCommand { get; set; } public ICommand DecryptCommand { get; set; } public string DecryptionTime { get { return "Decryption Time: " + decryptionTime; } set { decryptionTime = value; OnPropertyChanged("DecryptionTime"); } } public string EncryptionTime { get { return "Encryption Time: " + encryptionTime; } set { encryptionTime = value; OnPropertyChanged("EncryptionTime"); } } public string IV { get { return Convert.ToBase64String(encryption.IV); } set { encryption.IV = Convert.FromBase64String(value); } } public string Key { get { return Convert.ToBase64String(encryption.Key); } set { encryption.Key = Convert.FromBase64String(value); } } public string EncryptedHex { get { try { return BitConverter.ToString(Convert.FromBase64String(EncryptedBase64)); } catch { return "invalid input"; } } set { } } public string EncryptedBase64 { get { return encryptedBase64; } set { encryptedBase64 = value; OnPropertyChanged("EncryptedBase64"); OnPropertyChanged("encryptedHex"); } } public string PlanTextHex { get { try { return BitConverter.ToString(Encoding.UTF8.GetBytes(planTextUTF8)); } catch { return "invalid input"; } } set { } } public string PlanTextUTF8 { get { return planTextUTF8; } set { planTextUTF8 = value; OnPropertyChanged("PlanTextUTF8"); OnPropertyChanged("PlanTextHex"); } } public EncryptionType SelectedEncryptionType { get { return selectedEncryptionType; } set { selectedEncryptionType = value; encryption.SelectAlgorithm(selectedEncryptionType.Type); GenerateSet(); DecryptionTime = ""; EncryptionTime = ""; } } public ObservableCollection<EncryptionType> EcryptionOptions { get { return ecryptionOptions; } set { ecryptionOptions = value; } } public MainViewModel() { encryption = new Encryption(); GenerateCommand = new RelayCommand(new Action<object>(GenerateSet)); EncryptCommand = new RelayCommand(new Action<object>(Encrypt)); DecryptCommand = new RelayCommand(new Action<object>(Decrypt)); // Filles the options with the definent supported encryption types EcryptionOptions = new ObservableCollection<EncryptionType>() { new EncryptionType() { KeySize=128, Name = "AES (128bit)", Type = EncryptionTypeEnum.AES }, new EncryptionType() { KeySize=192, Name = "AES (192bit)", Type = EncryptionTypeEnum.AES }, new EncryptionType() { KeySize=256, Name = "AES (256bit)", Type = EncryptionTypeEnum.AES}, new EncryptionType() { KeySize=64, Name = "DES (64bit)" , Type = EncryptionTypeEnum.DES }, new EncryptionType() { KeySize=192, Name = "Triple DES (192bit)", Type = EncryptionTypeEnum.TripleDES }, new EncryptionType() { KeySize=128, Name = "Rijndael (128bit)", Type = EncryptionTypeEnum.Rijndael }, new EncryptionType() { KeySize=256, Name = "Rijndael (256bit)", Type = EncryptionTypeEnum.Rijndael }, }; SelectedEncryptionType = EcryptionOptions[0]; } /// <summary> /// Generates IV & Key in the right lenght /// </summary> public void GenerateSet(object obj = null) { encryption.GenerateSet(SelectedEncryptionType.KeySize); OnPropertyChanged("IV"); OnPropertyChanged("Key"); } /// <summary> /// encrypts the input if it is vaild /// </summary> public void Encrypt(object obj = null) { if (PlanTextUTF8 != "" && PlanTextHex != "invalid input") { byte[] messageBytes = Encoding.UTF8.GetBytes(PlanTextUTF8); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); byte[] encryptedBytes = encryption.Encrypt(messageBytes); stopwatch.Stop(); EncryptionTime = stopwatch.Elapsed.ToString(); EncryptedBase64 = Convert.ToBase64String(encryptedBytes); } } /// <summary> /// Decrypts the input if it is valid /// </summary> public void Decrypt(object obj = null) { if (EncryptedBase64 != "" && EncryptedHex != "invalid input") { byte[] encryptedBytes = Convert.FromBase64String(EncryptedBase64); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); byte[] messageBytes = encryption.Decrypt(encryptedBytes); stopwatch.Stop(); DecryptionTime = stopwatch.Elapsed.ToString(); PlanTextUTF8 = Encoding.UTF8.GetString(messageBytes); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
f06900efca96de00bae8fa33fa8e882a157f3dd9
C#
djserega/ControlModifiedFilesVer2
/src/ControlModifiedFiles/Models/FileSubscriber.cs
2.71875
3
using System; using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; namespace ControlModifiedFiles { public class FileSubscriber : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; #region Private fields private bool _checked; private string _path; private string _fileName; private string _extension; private ulong _size; private string _sizeString; private int _version; private DateTime _dateMaxVersion; #endregion #region Properties [Column("Выбрано", IsOnlyRead = false)] public bool Checked { get { return _checked; } set { if (_checked != value) { _checked = value; NotifyPropertyChanged(); } } } [Column("Путь к файлу", Visible = false)] public string Path { get { return _path; } set { if (_path != value) { _path = value; NotifyPropertyChanged(); } } } [Column("Имя файла", Visible = false)] public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; _extension = DirFile.GetExtension(_fileName); } } } [Column("Расширение", VisibleColumn = false)] public string Extension { get { return _extension; } } [Column("Размер (byte)", Visible = false)] public ulong Size { get { return _size; } set { if (_size != value) { _size = value; NotifyPropertyChanged(); } } } [Column("Размер", SortMemberPath = "Size")] public string SizeString { get { return _sizeString; } set { if (_sizeString != value) { _sizeString = value; NotifyPropertyChanged(); } } } [Column("№ предыдущей версии", VisibleColumn = false)] public int PreviousVersion { get; set; } [Column("№ версии")] public int Version { get { return _version; } set { if (_version != value) { _version = value; NotifyPropertyChanged(); } } } [Column("Дата изменения")] public DateTime DateMaxVersion { get { return _dateMaxVersion; } set { if (_dateMaxVersion != value) { _dateMaxVersion = value; NotifyPropertyChanged(); } } } [Column("Каталог версий", Visible = false)] public string DirectoryVersion { get; set; } [Column("Версии без уведомлений", VisibleColumn = false)] public int CountVersionWithoutNotify { get; set; } #endregion private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } internal void SetCurrentVersion() { using (Versions versions = new Versions() { SubscriberInfo = new FileInfo(Path), Subscriber = this }) { PreviousVersion = _version; Version = versions.GetVersion(); DateMaxVersion = versions.DateVersion; } } internal void SetCurrentSize() { Size = DirFile.GetFileSize(_path); SizeString = DirFile.GetSizeFormat(_size); } } }
0816ccad95b73353cc619d14a9d055108172a51d
C#
rafaelhrasko/cusko-stock
/TCC_EXT/Core/DAO/HistMovimentacaoDAO.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MySql.Data.MySqlClient; using Core.Class; namespace Core.DAO { class HistMovimentacaoDAO { internal static List<Class.HistMovimentacao> ultimasNegociacoes() { List<HistMovimentacao> lstHistMov = new List<HistMovimentacao>(); MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); string sql = "select * from HistoricoMovimentacao hm inner join Acao a on (a.idAcao = hm.Acao_idAcao) "; MySqlCommand msCommand = new MySqlCommand(sql, msc); try { msc.Open(); MySqlDataReader lol = msCommand.ExecuteReader(); HistMovimentacao asd = new HistMovimentacao(); if (lol.HasRows) { while (lol.Read()) { asd = new HistMovimentacao(); asd.Acao.ICodigo = int.Parse(lol["Acao_idAcao"].ToString()); asd.DtNegociada = DateTime.Parse(lol["data"].ToString()); asd.FValorNegociado = float.Parse(lol["valor"].ToString()); asd.Acao.StrSimbolo = lol["symbol"].ToString(); lstHistMov.Add(asd); } } } catch (Exception ex) { throw ex; } finally { MySqlConnection.ClearAllPools(); msc.Close(); } return lstHistMov; } internal static HistMovimentacao listarUltimaNegociacaoAcao(Acao item) { MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); string sql = "select * from HistoricoMovimentacao hm inner join Acao a on (a.idAcao = hm.Acao_idAcao) where Acao_idAcao = " + item.ICodigo + " order by data desc limit 1 "; HistMovimentacao asd = new HistMovimentacao(); MySqlCommand msCommand = new MySqlCommand(sql, msc); try { msc.Open(); MySqlDataReader lol = msCommand.ExecuteReader(); if (lol.HasRows) { while (lol.Read()) { asd = new HistMovimentacao(); asd.Acao.ICodigo = int.Parse(lol["Acao_idAcao"].ToString()); asd.DtNegociada = DateTime.Parse(lol["data"].ToString()); asd.FValorNegociado = float.Parse(lol["valor"].ToString()); asd.Acao.StrSimbolo = lol["symbol"].ToString(); asd.IQuantidadeNegociada = int.Parse(lol["volume"].ToString()); } } } catch (Exception ex) { throw ex; } finally { MySqlConnection.ClearAllPools(); msc.Close(); } return asd; } internal static HistMovimentacao obterHistoricoPorSimbolo(string symbol) { MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); string sql = "select * from HistoricoMovimentacao hm inner join Acao a on (a.idAcao = hm.Acao_idAcao) where UPPER(symbol) = UPPER('" + symbol + "') order by data desc limit 1 "; HistMovimentacao asd = new HistMovimentacao(); MySqlCommand msCommand = new MySqlCommand(sql, msc); try { msc.Open(); MySqlDataReader lol = msCommand.ExecuteReader(); if (lol.HasRows) { while (lol.Read()) { asd = new HistMovimentacao(); asd.Acao.ICodigo = int.Parse(lol["Acao_idAcao"].ToString()); asd.DtNegociada = DateTime.Parse(lol["data"].ToString()); asd.FValorNegociado = float.Parse(lol["valor"].ToString()); asd.Acao.StrSimbolo = lol["symbol"].ToString(); asd.IQuantidadeNegociada = int.Parse(lol["volume"].ToString()); } } } catch (Exception ex) { throw ex; } finally { MySqlConnection.ClearAllPools(); msc.Close(); } return asd; } internal static List<HistMovimentacao> obterHistoricoCompletoPorSimbolo(string symbol) { MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); string sql = "select * from HistoricoMovimentacao hm inner join Acao a on (a.idAcao = hm.Acao_idAcao) where UPPER(symbol) = UPPER('" + symbol + "') order by data desc LIMIT 2000"; HistMovimentacao asd = new HistMovimentacao(); MySqlCommand msCommand = new MySqlCommand(sql, msc); List<HistMovimentacao> lstHistMov = new List<HistMovimentacao>(); try { msc.Open(); MySqlDataReader lol = msCommand.ExecuteReader(); if (lol.HasRows) { while (lol.Read()) { asd = new HistMovimentacao(); asd.Acao.ICodigo = int.Parse(lol["Acao_idAcao"].ToString()); asd.DtNegociada = DateTime.Parse(lol["data"].ToString()); asd.FValorNegociado = float.Parse(lol["valor"].ToString()); asd.Acao.StrSimbolo = lol["symbol"].ToString(); asd.IQuantidadeNegociada = int.Parse(lol["volume"].ToString()); lstHistMov.Add(asd); } } } catch (Exception ex) { throw ex; } finally { MySqlConnection.ClearAllPools(); msc.Close(); } return lstHistMov.OrderBy(a => a.DtNegociada).ToList(); } internal static List<HistMovimentacao> obterHistoricoCompletoPorSimboloDiaAnterior(string symbol) { MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); string sql = "select * from HistoricoMovimentacao hm inner join Acao a on (a.idAcao = hm.Acao_idAcao) where UPPER(symbol) = UPPER('" + symbol + "') AND data > cast( '" + DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd") + "' as date) order by data desc"; HistMovimentacao asd = new HistMovimentacao(); MySqlCommand msCommand = new MySqlCommand(sql, msc); List<HistMovimentacao> lstHistMov = new List<HistMovimentacao>(); try { msc.Open(); MySqlDataReader lol = msCommand.ExecuteReader(); if (lol.HasRows) { while (lol.Read()) { asd = new HistMovimentacao(); asd.Acao.ICodigo = int.Parse(lol["Acao_idAcao"].ToString()); asd.DtNegociada = DateTime.Parse(lol["data"].ToString()); asd.FValorNegociado = float.Parse(lol["valor"].ToString()); asd.Acao.StrSimbolo = lol["symbol"].ToString(); asd.IQuantidadeNegociada = int.Parse(lol["volume"].ToString()); lstHistMov.Add(asd); } } } catch (Exception ex) { throw ex; } finally { MySqlConnection.ClearAllPools(); msc.Close(); } return lstHistMov.OrderBy(a => a.DtNegociada).ToList(); } internal static List<HistMovimentacao> listarUltimaNegociacaoAcao(List<Acao> lstAcoes) { string sql = ""; for (int i = 0; i < lstAcoes.Count; i++) { sql += "select * from HistoricoMovimentacao hm inner join Acao a on (a.idAcao = hm.Acao_idAcao) where Acao_idAcao = " + lstAcoes[i].ICodigo + " LIMIT 1"; if (i + 1 != lstAcoes.Count) sql += " UNION "; } MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); List<HistMovimentacao> asd = new List<HistMovimentacao>(); MySqlCommand msCommand = new MySqlCommand(sql, msc); try { msc.Open(); MySqlDataReader lol = msCommand.ExecuteReader(); if (lol.HasRows) { HistMovimentacao hm = new HistMovimentacao(); while (lol.Read()) { hm = new HistMovimentacao(); hm.Acao.ICodigo = int.Parse(lol["Acao_idAcao"].ToString()); hm.Acao.StrSimbolo = lol["symbol"].ToString(); hm.DtNegociada = DateTime.Parse(lol["data"].ToString()); hm.FValorNegociado = float.Parse(lol["valor"].ToString()); hm.IQuantidadeNegociada = int.Parse(lol["volume"].ToString()); asd.Add(hm); } } } catch (Exception ex) { throw ex; } finally { MySqlConnection.ClearAllPools(); msc.Close(); } return asd; } internal static void inserirNegociacaoInvestidor(HistMovimentacao histMov, Investidor usu) { string sql = @"INSERT INTO `cusko`.`MovimentacaoInvestidor`(`Investidor_idInvestidor`,`Acao_idAcao`,`data`,`quantidade`,`valor`) VALUES (" + usu.ICodigo + "," + histMov.Acao.ICodigo + "," + histMov.DtNegociada + "," + histMov.Acao.INegociacoes + "," + histMov.FValorNegociado + ")"; MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); MySqlCommand msCommand = new MySqlCommand(sql, msc); try { msc.Open(); msCommand.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { msc.Close(); MySqlConnection.ClearAllPools(); } } internal static int obterUltimaNegociacaoInvestidor(int p) { string sql = @"select max(idMovimentacaoInvestidor) from MovimentacaoInvestidor where Investidor_idInvestidor = " + p; MySqlConnection msc = new MySqlConnection("Server=cusko.db.8505846.hostedresource.com;Database=cusko;Uid=cusko;Pwd=Teste1234;"); MySqlCommand msCommand = new MySqlCommand(sql, msc); try { msc.Open(); return int.Parse(msCommand.ExecuteScalar().ToString()); } catch (Exception ex) { throw ex; } finally { msc.Close(); MySqlConnection.ClearAllPools(); } } } }
911cb616b82c1b6a25fdc6b4933927eaf3ee5086
C#
shendongnian/download4
/first_version_download2/400499-34826286-108584767-3.cs
2.578125
3
[TestClass] public class UnitTest1 { Test t; [TestInitialize] public void TestInitialize() { t = new Test(); } [TestMethod] public void TestGetBooksByGenre() { var result = t.Search(new List<int>() { 1 }); Assert.IsTrue(result.Count == 1); Assert.IsTrue(result[0].Id == 1); } }
3e2f1b7dde8e84730758df3d038f893cf1888cf8
C#
devos1/Heig-Vd_LangOOD
/LangOOD.Exercices/CH17_18.GestionEmployees/Program.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CH17_18.GestionEmployees { class Program { static void Main(string[] args) { Random randSalaire = new Random(); Entreprise<Employe> entreprise = new Entreprise<Employe>(); for (int i = 0; i < 10; i++) { Employe e = new Employe(i + "emp"); e.Salaire = randSalaire.Next(2000, 5000); entreprise.add(e, e.NomPrenom); } Console.Write("Entre le nom et prenom tout attaché : "); string line = Console.ReadLine(); Employe emp = entreprise.getEmpoye(line); Console.WriteLine("L'employée {0} gagne {1}", emp.NomPrenom, emp.Salaire ); List<Employe> emps = new List<Employe>(); emps = entreprise.GetEmployeesList(); foreach (var e in emps) { Console.WriteLine("Nom et Prénom : {0} - Salaire : {1} CHF", e.NomPrenom, e.Salaire); } } } }
0b68c6c0fd328c5d97d07a0f5cc91c0bb266800b
C#
shanearsenault97/Strangest-Things
/Source/PorkShopPOS/PorkShopPOS/UserAccessShowAll.cs
2.515625
3
/* User: Jonathan Deschene * Date: 2017-01-20 * Time: 2:45 PM * Purpose: Form that displays all UserAccess data in a datagrid */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PorkShopPOS { public partial class UserAccessShowAll : Form { public UserAccessShowAll() { InitializeComponent(); } /* User: Jonathan Deschene * Date: 2017-01-20 * Time: 2:45 PM * Purpose: display all UserAccess data in a datagrid */ private void UserAccessShowAll_Load(object sender, EventArgs e) { try { UserAccess access = new UserAccess(); DataGridView dgv = userAccessDGV; access.showAllUserAccess(dgv); } catch (InvalidOperationException exc) { MessageBox.Show(exc.ToString()); } catch (Exception exception) { MessageBox.Show(exception.Message); } } } }
974b657db644a04b084d283223341202260e1bc6
C#
demidko/MCS1
/Практикум по алгоритмизации/PascalMini/PascalMini/Lexer.cs
3.359375
3
using System; using System.Text; using System.Collections.Generic; using System.Linq; /// <summary> /// Класс для лексического анализа подготовленных строк с кодом /// </summary> static class Lexer { private static int CharIndex = 0; private static void Error(in string message) => PascalRuntime.Error( "во время разбиения на лексемы, " + $"на символе {CharIndex} {message}"); private static void MoveBuffer( this List<string> list, in StringBuilder buffer) { if (buffer.Length > 0) { list.Add(buffer.ToString()); buffer.Clear(); } } /// <summary> /// Функция разбивает строку на лексемы языка Pascal /// </summary> /// <param name="line">Строка кода</param> /// <returns>Список лексем</returns> public static IEnumerable<string> Split(in string line) { var result = new List<string>(); var buffer = new StringBuilder(); for (var i = 0; i < line.Length; ++i) { CharIndex = i + 1; var ch = line[i]; // := if (ch == ':' && line.ElementAtOrDefault(i + 1) == '=') { result.MoveBuffer(buffer); result.Add(":="); ++i; continue; } // Обработка символов if (ch == '\'') { buffer.Append('\''); buffer.Append(line.ElementAtOrDefault(i + 1)); if (line.ElementAtOrDefault(i + 2) != '\'') { Error("ожидался символ с закрывающей кавычкой '"); } buffer.Append('\''); result.MoveBuffer(buffer); i = i + 2; continue; } // Дробные числа . if (ch == '.' && buffer.Length > 0 && Char.IsDigit(buffer[0]) && Char.IsDigit(line.ElementAtOrDefault(i + 1))) { buffer.Append('.'); for (++i; i < line.Length && Char.IsDigit(line[i]); ++i) { buffer.Append(line[i]); } result.MoveBuffer(buffer); --i; continue; } // == >= <= != if ("=><!".Contains(ch) && line.ElementAtOrDefault(i + 1) == '=') { result.MoveBuffer(buffer); result.Add($"{ch}="); ++i; continue; } // Обработка строк if (ch == '\"') { var nextIndex = line.IndexOf('\"', i + 1); if (nextIndex == -1) { Error("Не найден завершающий символ"); } result.MoveBuffer(buffer); result.Add(line.Substring(i, nextIndex - i + 1)); i = nextIndex; continue; } // Список символов которые нужно добавить // как отдельную лексему if (Char.IsPunctuation(ch) || Char.IsSymbol(ch)) { result.MoveBuffer(buffer); result.Add(ch.ToString()); continue; } // Пробел if (Char.IsWhiteSpace(ch)) { result.MoveBuffer(buffer); continue; } // Всё остальное buffer.Append(ch); } result.MoveBuffer(buffer); return result; } }
0027118b5fd60db02c8eeeb8e110f8bfe84bd8b5
C#
TopchoTeam/OnlineStore
/OnlineStore.Client/Core/Commands/TransferMoneyCommand.cs
3.34375
3
namespace OnlineStore.Client.Core.Commands { using System; using Utilities; using Models; using Data; using System.Linq; public class TransferMoneyCommand { public string Execute() { if (!Authorization.Instance.ValidateIsUserLoggedIn()) { throw new InvalidOperationException("You should log in first for this operation"); } Console.Clear(); string result = string.Empty; Console.Write("Enter transfer type(Withdrawal/Deposit): "); string tran = Console.ReadLine().ToLower(); Console.Clear(); Console.Write("Enter money amount: "); decimal money = decimal.Parse(Console.ReadLine()); using(OnlineStoreContext context = new OnlineStoreContext()) { User user = context.Users.FirstOrDefault(u => u.UserName == Authorization.Instance.CurrentUser.UserName); switch (tran) { case "withdrawal": if (money > user.Account.Balance) { throw new InvalidOperationException("Not enough money in your account!"); } user.Account.Balance -= money; context.SaveChanges(); break; case "deposit": user.Account.Balance += money; context.SaveChanges(); break; default: throw new InvalidOperationException($"{tran} is invalid!"); } result = $"{tran} is successful."; } return result; } } }
8ae165dbe2c06ba57259c1d9d77dad0d201b2db5
C#
VarianAPIs/Varian-Code-Samples
/webinars & workshops/Developer Workshop 2018/DocumenServiceSample/Helpers/TokenValidator.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Helpers { public class TokenValidator : IArgumentValidator { public bool ValidateAuthenticationArgs(ref string validationDetails) { if (string.IsNullOrWhiteSpace(ConnectivitySettings.AccessToken)) { validationDetails = "Please get an access token before invoking API."; return false; } return true; } public bool ValidateTokenArgs(ref string validationDetails) { if (string.IsNullOrWhiteSpace(IdentityProviderSettings.STSURL) || string.IsNullOrWhiteSpace(IdentityProviderSettings.ClientID) || string.IsNullOrWhiteSpace(IdentityProviderSettings.ClientSecret) || string.IsNullOrWhiteSpace(IdentityProviderSettings.Scopes)) { validationDetails = "Please populate the Identity Server URL, client ID, client secret, and scopes prior to requesting an access token."; return false; } return true; } } }
282d8f77c89c65386f6e0487f55c67267c5cbc9b
C#
pCYSl5EDgo/SaveManager
/Assets/Plugins/Yumineko/Fader/Fader.cs
2.609375
3
using System.Collections; using UniRx.Async; using UnityEngine; using UnityEngine.UI; public class Fader : SingletonMonoBehaviour<Fader> { private Canvas faderCanvas = null; private Image blackImage = null; private UniTask fade = default; void Reset () { gameObject.name = "Fader"; gameObject.GetOrAddComponent<CanvasScaler> (); faderCanvas = gameObject.GetOrAddComponent<Canvas> (); faderCanvas.renderMode = RenderMode.ScreenSpaceOverlay; faderCanvas.sortingOrder = 9999; gameObject.GetOrAddComponent<GraphicRaycaster> (); blackImage = gameObject.GetOrAddComponent<Image> (); blackImage.color = Color.black; blackImage.SetAlpha (0.0f); blackImage.enabled = false; } void Start () { Reset (); } public void FadeOut (float time) { Debug.Log(""); if (fade.IsCompleted) { fade = Fade (true, time); } else { Debug.LogWarning ("既に別のフェードを実行中です!"); } } public void FadeIn (float time) { if (fade.IsCompleted) { fade = Fade (false, time); } else { Debug.LogWarning ("既に別のフェードを実行中です!"); } } public async UniTask Fade(bool fadeout, float time){ float alpha = fadeout ? 0.0f : 1.0f; float countTime = 0.0f; blackImage.enabled = true; blackImage.SetAlpha (alpha); await UniTask.DelayFrame(1); while (countTime < time) { countTime += Time.deltaTime; alpha = fadeout ? countTime / time : 1.0f - countTime / time; blackImage.SetAlpha (alpha); await UniTask.DelayFrame(1); } alpha = fadeout ? 1.0f : 0.0f; blackImage.SetAlpha (alpha); blackImage.enabled = fadeout; } }
48431bff23aa13d1c1c04d1458e4ab0628dc400f
C#
agamat/Payroll
/Payroll.Repository/DatabaseProvider.cs
2.875
3
using Payroll.Repository.Entities; using Payroll.Repository.Interface; using System.Configuration; using System.Data; using System.Data.Common; namespace Payroll.Repository { public class DatabaseProvider { private DbConnection _connection = null; private readonly IDatabase _database; public DatabaseProvider() { var databaseType = ConfigurationManager.AppSettings["DatabaseType"]; var connectionString = ConfigurationManager.ConnectionStrings["Payroll.ConnectionString"].ToString(); switch (databaseType) { case "MySql"://DatabaseEnums.MySql: _database = new Entities.MySql(connectionString); break; case "MsSql"://DatabaseEnums.MySql: _database = new MsSql(connectionString); break; } } public virtual DataSet ExecuteDataSet(string query) { return _database.ExecuteDataSet(query); } } }
1f188468c33b94eac9c97705291444b3325ec158
C#
SanyaPacman/CreateRoomVR
/Assets/WithoutWR/Scripts/ChangeChildNumber.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeChildNumber : MonoBehaviour { public int minimumChildCount; public void CloneLastChild() { var clone= transform.GetChild(transform.childCount - 1); Instantiate(clone, clone.position, clone.rotation, transform); } public void DeleteLastChild() { if (transform.childCount<=0|| transform.childCount <=minimumChildCount) { return; } var clone = transform.GetChild(transform.childCount - 1); Destroy(clone.gameObject); } }
4624faeefe2492767b56dc49faaad2e4081821b4
C#
gpdoud/Asset-Management-System
/AssetManagementSystem/Migrations/Configuration.cs
2.703125
3
namespace AssetManagementSystem.Migrations { using AssetManagementSystem.Models; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<AssetManagementSystem.Models.AssetManagementSystemContext> { public Configuration() { AutomaticMigrationsEnabled = false; ContextKey = "AssetManagementSystem.Models.AssetManagementSystemContext"; } protected override void Seed(AssetManagementSystem.Models.AssetManagementSystemContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // context.Users.AddOrUpdate( u => u.Username, new User { Username = "user1", Password = "pw1", FirstName = "fn1", LastName = "ln1", Email = "email1", AdminLevel = 2, IsActive = true }, new User { Username = "user2", Password = "pw2", FirstName = "fn2", LastName = "ln2", Email = "email2", AdminLevel = 1, IsActive = true }, new User { Username = "user3", Password = "pw3", FirstName = "fn3", LastName = "ln3", Email = "email3", AdminLevel = 0, IsActive = true } ); context.Assets.AddOrUpdate( a => a.Name, new Asset { Name = "asset1", Photopath = "", Price = 9.99M, Unit = "Ea.", Vendor = "bob" }, new Asset { Name = "asset2", Photopath = "", Price = 8.99M, Unit = "Ea.", Vendor = "bob" }, new Asset { Name = "asset3", Photopath = "", Price = 7.99M, Unit = "Ea.", Vendor = "bob" }, new Asset { Name = "asset4", Photopath = "", Price = 6.00M, Unit = "Ea.", Vendor = "bob" } ); context.SaveChanges(); context.Vehicles.AddOrUpdate( v => v.VIN, new Vehicle { AssetId = context.Assets.SingleOrDefault(a => a.Name == "asset1").Id, Asset = context.Assets.SingleOrDefault(a => a.Name == "asset1"), VIN = "VIN1", Make = "Make1", Model = "Model1" }, new Vehicle { AssetId = context.Assets.SingleOrDefault(a => a.Name == "asset2").Id, Asset = context.Assets.SingleOrDefault(a => a.Name == "asset2"), VIN = "VIN2", Make = "Make2", Model = "Model2" }, new Vehicle { AssetId = context.Assets.SingleOrDefault(a => a.Name == "asset4").Id, Asset = context.Assets.SingleOrDefault(a => a.Name == "asset4"), VIN = "VIN4", Make = "Make4", Model = "Model4" } ); } } }
62e54016eaa057865b8db12a582b3ef66f07f160
C#
shendongnian/download4
/code4/714634-17270638-42624421-2.cs
2.625
3
public class MyClass: IDisposable { public MyClass() { //Do the work } public void Dispose() { // Clean stuff up. } }
7f4e44225b1954b008b17621b53de0f37df0c24d
C#
evangelism/SillyBlogReader
/SillyBlogReader/Model/Blog.cs
2.734375
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml.Linq; using Windows.Data.Html; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using Windows.Web.Http; namespace SillyBlogReader.Model { public class Blog { public BlogEntry[] Entries { get; private set; } public string Title { get; private set; } public string ShortTitle { get; private set; } public BitmapImage Image { get; private set; } public Symbol Symbol { get; set; } public string ImageUrl { set { Image = new BitmapImage(new Uri(value)); } } public string Url { get; private set; } public Blog(string title, string url, Symbol S) { ShortTitle = title; Url = url; Symbol = S; } public bool IsLoaded { get; private set; } = false; public async Task Load() { var cli = new HttpClient(); // Use the following 2 lines to read blog content live from the Internet //var s = await cli.GetInputStreamAsync(new Uri(Url)); //var xdoc = XDocument.Load(s.AsStreamForRead()); // XDocument.Parse(s); // Use the following 2 lines in order to speed-up startup and read data from local folder var z = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Data"); var xdoc = XDocument.Load(Url); Title = (from x in xdoc.Descendants("title") select x.Value).First(); var res = from x in xdoc.Descendants("item") select new BlogEntry() { Title = x.Element("title").Value, Body = HtmlUtilities.ConvertToText(x.Element("description").Value), ImageUrl = GetImageUrl(x.Element("description").Value) }; Entries = res.ToArray(); IsLoaded = true; } public async Task EnsureLoaded() { if (!IsLoaded) await Load(); } private static string GetImageUrl(string text) { return Regex.Matches(text, @"(?<=<img\s+[^>]*?src=(?<q>['""]))(?<url>.+?)(?=\k<q>)", RegexOptions.IgnoreCase) .Cast<Match>() .Where(m => { Uri url; if (Uri.TryCreate(m.Groups[0].Value, UriKind.Absolute, out url)) { string ext = Path.GetExtension(url.AbsolutePath).ToLower(); if (ext == ".png" || ext == ".jpg" || ext == ".bmp") return true; } return false; }) .Select(m => m.Groups[0].Value) .FirstOrDefault(); } } }
d3b546e871f3b4029c13a2c954d602023227d328
C#
bryant1410/BoC
/Src/Commons/ComponentModel/TypeExtension/ExtendWithTypeAttribute.cs
2.546875
3
using System; namespace BoC.ComponentModel.TypeExtension { public class ExtendWithTypeAttribute : Attribute { private readonly Type with; public ExtendWithTypeAttribute(Type with) { this.with = with; } public Type With { get { return with; } } } }
cc43941651d2e42362ec28bed092cd31600b419f
C#
tamirdresher/DistributedBalancedPartitionQueueAssignment
/Consumer/EventConsumerWorker.cs
2.625
3
using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Consumer { internal class EventConsumerWorker { private readonly string _queue; private readonly IModel _channel; private readonly ILogger _logger; private EventingBasicConsumer _consumer; private Task _executingTask; public EventConsumerWorker(string queue, IModel channel, ILogger logger) { _queue = queue; _channel = channel; _logger = logger; } public Task StartAsync() { _executingTask = Task.Run(() => { try { _channel.QueueDeclare(queue: _queue, durable: true, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object> { { "x-single-active-consumer", true } }); _consumer = new EventingBasicConsumer(_channel); _consumer.Received += (model, ea) => { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); _logger.LogInformation(" [x] Received {0}", message); _channel.BasicAck(ea.DeliveryTag, false); }; _channel.BasicConsume(queue: _queue, autoAck: false, consumer: _consumer); } catch (System.Exception ex) { _logger.LogError(ex, $"Couldnt subscribe to queue {_queue}"); } }); return Task.CompletedTask; } public Task StopAsync() { if (_consumer!=null) { _channel.BasicCancel(_consumer.ConsumerTags[0]); _consumer = null; _executingTask = null; } return Task.CompletedTask; } } }
135558573ebc18e4868777646b1aa374dcada241
C#
String03/LUG-PIM2_Ana-Laura-Moyano
/LUG-PIM2_Ana-Laura-Moyano/LUG_PIM2_Ana-Laura-Moyano.DAL/SqlCommands/PaquetesCanalesSqlCommandBuilder.cs
2.625
3
using LUG_PIM2_Ana_Laura_Moyano.Modelos; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LUG_PIM2_Ana_Laura_Moyano.DAL.SqlCommands { public class PaquetesCanalesSqlCommandBuilder : ISqlCommandBuilder<PaquetesCanales> { public SqlCommand Delete(PaquetesCanales entity) { var command = new SqlCommand("DELETE FROM PaquetesCanales WHERE Id = @Id"); command.Parameters.AddWithValue("Id", entity.Id); return command; } public SqlCommand Insert(PaquetesCanales entity) { var command = new SqlCommand("INSERT INTO [dbo].[PaquetesCanales] ([Canal_Id] ,[Paquete_Id]) VALUES (@Canal_Id, @Paquete_Id)"); command.Parameters.AddWithValue("Canal_Id", entity.Canal_Id); command.Parameters.AddWithValue("Paquete_Id", entity.Paquete_Id); return command; } public SqlCommand Select() { return new SqlCommand("SELECT * FROM PaquetesCanales"); } public SqlCommand Update(PaquetesCanales entity) { var command = new SqlCommand("UPDATE [dbo].[PaquetesCanales] SET [Canal_Id] = @Canal_Id, [Paquete_Id] = @Paquete_Id WHERE Id = @Id"); command.Parameters.AddWithValue("Id", entity.Id); command.Parameters.AddWithValue("Canal_Id", entity.Canal_Id); command.Parameters.AddWithValue("Paquete_Id", entity.Paquete_Id); return command; } } }
3c51cde804e12becf791aa1fdc8b2452e731280a
C#
shendongnian/download4
/code3/478649-10904455-25211395-2.cs
2.828125
3
StringBuilder sb = new StringBuilder(); foreach (DataGridViewCell cell in dgvC.SelectedCells) { sb.AppendLine(cell.Value.ToString()); } MessageBox.Show(sb.ToString());
809fd50328967bc44ff7b48fe2c599225ebf3dd0
C#
rishabhverma123/Save-The-Bunny
/Assets/Scripts/PlayerController.cs
2.671875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; public class PlayerController : MonoBehaviour { Rigidbody2D rd; float xInput; public float moveSpeed; Vector2 newPosition; //variable of type vector2 can store two value x & y. public float xPostionLimit=2.5f; //variable to limit movement of rabbit within game screen /* * Awake() function is called before start() in lifecycle * initialization of variable or taking referrence is better done in Awake() * */ private void Awake() { rd = GetComponent<Rigidbody2D>(); } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } /* * Normal update activity is done under update() function * FixedUpdate() is better to update any Physics property. * Since movement of player is physics hence done in Ficxedupdate() here. * */ private void FixedUpdate() { MovePlayer(); } void MovePlayer() { xInput = CrossPlatformInputManager.GetAxis("Horizontal"); //this give value between -1 and +1 depending upon location of rabbit //take input from keyboard and tell left or right key is pressed newPosition = transform.position; //gives current position newPosition.x = newPosition.x + xInput * moveSpeed; //changes position depending upon input and control its speed //Mathf.clamp() limit movement of newpostion.x variable(rabbit movement) b/w -xPostionLimit and +xPostionLimit newPosition.x = Mathf.Clamp(newPosition.x, -xPostionLimit, xPostionLimit); rd.MovePosition(newPosition); } }
814c4c532e1b68cea4df1b26a696911a097d9193
C#
DanielLatimerUns/Stocky
/StockyManagementSystem/Stocky.Utilitys/Utility/CSVExporter.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Reflection; namespace Stocky.Utility { public class CSVExporter { public List<dynamic> List { get; set; } public string FileName { get; set; } public CSVExporter() { List = new List<dynamic>(); } public void Export() { if (List == null || List.Count == 0) return; //get type from 0th member Type t = List[0].GetType(); string newLine = Environment.NewLine; string filename = FileName + t.Name + ".csv"; if (!File.Exists(filename)) { using (var sw = new StreamWriter(filename)) { //make a new instance of the class name we figured out to get its props object o = Activator.CreateInstance(t); //gets all properties PropertyInfo[] props = o.GetType().GetProperties(); //foreach of the properties in class above, write out properties //this is the header row foreach (PropertyInfo pi in props) { sw.Write(pi.Name.ToUpper() + ","); } sw.Write(newLine); //this acts as datarow foreach (var item in List) { //this acts as datacolumn foreach (PropertyInfo pi in props) { //this is the row+col intersection (the value) string whatToWrite = "" + ','; // Check if the value is null and if so write a blank string. string checkvalue = Convert.ToString(item.GetType().GetProperty(pi.Name).GetValue(item, null)); if(checkvalue != null) { whatToWrite = Convert.ToString(item.GetType().GetProperty(pi.Name).GetValue(item, null)).Replace(',', ' ') + ','; } sw.Write(whatToWrite); } sw.Write(newLine); } } if (File.Exists(filename)) { System.Windows.MessageBoxResult Result = System.Windows.MessageBox.Show (string.Format("File sucsessfully created, Would you like to open the file now?{1}{1}File created: {0} ", filename, Environment.NewLine) , "Export Complete", System.Windows.MessageBoxButton.YesNo); if (Result == System.Windows.MessageBoxResult.Yes) { if (File.Exists(filename)) System.Diagnostics.Process.Start(filename); } } } } } }
d64c86158cf36965ee9d472e0cdc7f6fae81cec9
C#
tankero/Vann-Neumann-Machines
/Assets/Scripts/Base/TargetObjectList.cs
2.625
3
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using System; [Serializable] public class TargetInfo { public Vector3 LastKnownLocation; public bool CurrentlyTracking; [Range(1, 10)] public int Priority; } [Serializable] public class TargetObjectDictionary : SerializableDictionary<GameObject, TargetInfo> { } [Serializable] public class TargetObjectList { [SerializeField] private TargetObjectDictionary targets = new TargetObjectDictionary(); public GameObject GetCurrentTargetObject() { if (targets.Count > 0) { return targets.Last().Key; } else { return null; } } public GameObject[] GetTrackedList() { return targets.Where(o => o.Value.CurrentlyTracking).Select(kvp => kvp.Key).ToArray(); } public GameObject[] GetFullList() { return targets.Select(kvp => kvp.Key).ToArray(); } public Vector3? GetLastKnownPosition(GameObject target) { if (targets.ContainsKey(target)) { return targets[target].LastKnownLocation; } return null; } public bool CurrentlyTracking(GameObject target) { if (targets.ContainsKey(target)) { return targets[target].CurrentlyTracking; } return false; } public void TrackObject(GameObject target) { if (targets.ContainsKey(target)) { targets[target].CurrentlyTracking = true; return; } targets.Add(target, new TargetInfo { CurrentlyTracking = true, LastKnownLocation = target.transform.position, Priority = 1 }); } public void StopTrackingObject(GameObject target) { if (targets.ContainsKey(target) && targets[target].CurrentlyTracking) { targets[target].CurrentlyTracking = false; targets[target].LastKnownLocation = target.transform.position; } } public void SetPriority(GameObject target, int priority) { if (targets.ContainsKey(target)) { targets[target].Priority = priority; } else { TrackObject(target); SetPriority(target, priority); } } public void IncreasePriority(GameObject target) { if (targets.ContainsKey(target)) { if (targets[target].Priority < 10) targets[target].Priority += 1; } else { TrackObject(target); IncreasePriority(target); } } public void DecreasePriority(GameObject target) { if (targets.ContainsKey(target)) { if (targets[target].Priority > 0) targets[target].Priority -= 1; } else { TrackObject(target); DecreasePriority(target); } } public void ListUpdate() { foreach (var item in targets) { if (targets[item.Key].CurrentlyTracking) { targets[item.Key].LastKnownLocation = item.Key.transform.position; } } } public void ClearTargetObjects() { targets.Clear(); } }
bedcd2644f8c3ecb11bbfa0b8a984ffb0a2a58c6
C#
rcruzeiro/CRZ.Orders
/CRZ.Orders.Domain/OrdersAggregate/Address.cs
2.578125
3
using System; namespace CRZ.Orders.Domain.OrdersAggregate { public class Address : BaseValueObject { public string Street { get; private set; } public string Number { get; private set; } public string ZipCode { get; private set; } public string Complement { get; private set; } public string City { get; private set; } public string State { get; private set; } public Address(string street, string number, string zipcode, string complement, string city, string state) { Street = street ?? throw new ArgumentNullException(nameof(street)); Number = number ?? throw new ArgumentNullException(nameof(number)); ZipCode = zipcode ?? throw new ArgumentNullException(nameof(zipcode)); Complement = complement ?? throw new ArgumentNullException(nameof(complement)); City = city ?? throw new ArgumentNullException(nameof(city)); State = state ?? throw new ArgumentNullException(nameof(state)); CreatedAt = DateTimeOffset.Now; } } }
446010a345875c0f742f889542521d91594cbd98
C#
oduma/Sciendo.Common
/Sciendo.IOC.Configuration/IOCConfigurationSection.cs
2.546875
3
using System.Configuration; namespace Sciendo.IOC.Configuration { public class IOCConfigurationSection:ConfigurationSection { [ConfigurationProperty("assemblies")] public IOCAssembliesConfigurationCollection Assemblies { get { return (IOCAssembliesConfigurationCollection)this["assemblies"]; } set { this["assemblies"] = value; } } public override string ToString() { return string.Format("Assemblies: {0}.", Assemblies.ToString()); } } }
b593df100bf76e2025dc51eda28353a1c8aa1ab8
C#
svreinoso/currencies
/Currencies.Data/SeedDatabase.cs
2.640625
3
//using Currencies.Data.Entities; //using Microsoft.Extensions.DependencyInjection; //using Microsoft.Extensions.Logging; //using System; //using System.Collections.Generic; //using System.Linq; //namespace Currencies.Data //{ // public class SeedDatabase // { // public static void Initialize(IServiceProvider serviceProvider) // { // var context = serviceProvider.GetRequiredService<ApplicationDbContext>(); // var logger = serviceProvider.GetRequiredService<ILogger<SeedDatabase>>(); // var defaultCurrencies = new List<string> { "dolar", "model" }; // var hasCurrencies = context.Currencies.Any(x => defaultCurrencies.Contains(x.Name)); // if (!hasCurrencies) // { // context.Currencies.Add(new Currency // { // Name = "dolar", // Source = "http://www.bancoprovincia.com.ar/Principal/Dolar", // MonthlyLimit = 200 // }); // context.Currencies.Add(new Currency // { // Name = "real", // Source = "http://www.bancoprovincia.com.ar/Principal/Dolar", // MultiplyBy = 0.25, // MonthlyLimit = 300 // }); // context.SaveChanges(); // } // } // } //}
7e6ed3c291f9691718477af9eb3e24f3815083c8
C#
o0-RbR-0o/monoKrom
/PartyParser/PartyParser.cs
2.984375
3
using System; using System.Collections.Generic; using System.Xml; /* Simple quick and dirty parser for messages going from Partymeister to the screen server. Version: 0.4 Author : 2016 by Kim Oliver "RbR" Schweikert License: CC-by-nc */ namespace monoKrom.PartyParser { ///<summary> ///A small piece of code for parsing Partymeister messages to the screen server. This is not finished yet! ///</summary> class PartyParser { ///<summary> ///Request types: Partymeister messages have one of those types ///</summary> public enum RequestType { Unknown, Next, Previous, NextHard, PreviousHard, Playlist, GetPlaylists, Seek, SeekHard } XmlDocument xmld = new XmlDocument(); ///<summary> ///A Playlist entry (a slide in most cases) ///</summary> public class PlaylistElement { ///<summary> ///Either image or video ///</summary> public enum PlaylistElementType { Image, Video } private string name; private string path; private PlaylistElementType type; private int duration; private int midi; private string slidetype; private int transitiontype; private int transitionduration; private bool manualadvance; private bool mute; ///<summary> ///The name of the element ///</summary> public string Name { get { return name; } set { name = value; } } ///<summary> ///The path of the element to download from ///</summary> public string Path { get { return path; } set { path = value; } } ///<summary> ///The type of this element ///</summary> public PlaylistElementType Type { get { return type; } set { type = value; } } ///<summary> ///The duration of this slides in milliseconds (!Note: Partymeister is using seconds by default.) ///</summary> public int Duration { get { return duration; } set { duration = value; } } ///<summary> ///?! Midi command to send with this slide?! Some more reversing work needed here ///</summary> public int Midi { get { return midi; } set { midi = value; } } ///<summary> ///The type of the slide template ///</summary> public string Slidetype { get { return slidetype; } set { slidetype = value; } } ///<summary> ///The id of the transition used by this slide ///</summary> public int Transitiontype { get { return transitiontype; } set { transitiontype = value; } } ///<summary> ///The duration in milliseconds for the transition of this slide ///</summary> public int Transitionduration { get { return transitionduration; } set { transitionduration = value; } } ///<summary> ///Manual advance and no timer if true ///</summary> public bool Manualadvance { get { return manualadvance; } set { manualadvance = value; } } ///<summary> ///Mute this slide? ///</summary> public bool Mute { get { return mute; } set { mute = value; } } } ///<summary> ///Just load in the xml coming from partymeister and you will be fine. In most cases. ///</summary> ////// <param name="xml">The xml string coming from Partymeister</param> public PartyParser(string xml) { xmld.LoadXml(xml); } ///<summary> ///Get a PlaylistElement with specified name ///</summary> ///<param name="name">The name of the element to get</param> ///<returns>A Playlist element</returns> public PlaylistElement parsePlaylistItem(string name) { //Select the playlist item node with given name XmlNode itemnode = xmld.SelectSingleNode(string.Format("/xml/data/item[@name='{0}']", name)); //Create a new playlist element PlaylistElement p = new PlaylistElement(); //Set the name of the playlist element p.Name = name; //Get the type of the element. switch (itemnode.Attributes["type"].Value) { case "image": p.Type = PlaylistElement.PlaylistElementType.Image; break; case "video": p.Type = PlaylistElement.PlaylistElementType.Video; break; } //Fill playlist element with values from xml p.Path = itemnode.SelectSingleNode("path").InnerText; p.Duration = Convert.ToInt32(itemnode.SelectSingleNode("duration").InnerText)*1000; p.Midi = Convert.ToInt32(itemnode.SelectSingleNode("midi").InnerText); p.Slidetype = itemnode.SelectSingleNode("slide_type").InnerText; p.Transitiontype = Convert.ToInt32(itemnode.SelectSingleNode("transition").InnerText); p.Transitionduration = Convert.ToInt32(itemnode.SelectSingleNode("transition").Attributes["duration"].Value); p.Manualadvance = itemnode.SelectSingleNode("manual_advance").InnerText == "1"; p.Mute = itemnode.SelectSingleNode("mute").InnerText == "1"; //And return it return p; } ///<summary> ///Get all playlist item names ///</summary> ///<returns>A list with playlist item names</returns> public List<string> getPlaylistItemNames() { List<string> names = new List<string>(); XmlNodeList itemlist = xmld.SelectNodes("/xml/data/item"); foreach (XmlNode n in itemlist) { names.Add(n.Attributes["name"].Value); } return names; } ///<summary> ///Get the name of the playlist ///</summary> ///<returns>The name of the playlist</returns> public string getPlaylistName() { return getParameter("name"); } ///<summary> ///Get a parameter with specified name ///</summary> ///<returns>The value of the specified parameter</returns> public string getParameter(string name) { return xmld.SelectSingleNode(String.Format("/xml/parameter[@name='{0}']", name)).InnerText; } ///<summary> ///Get the type of the request. See Enum RequestType for more information about request types ///</summary> ///<returns>The request type</returns> public RequestType getRequestType() { XmlNode item = xmld.SelectSingleNode("/xml/rpc"); switch (item.Attributes["name"].Value) { case "playlist": return RequestType.Playlist; case "next": return getParameter("hard")=="0"?RequestType.Next:RequestType.NextHard; case "previous": return getParameter("hard") == "0" ? RequestType.Previous : RequestType.PreviousHard; case "seek": return getParameter("hard") == "0" ? RequestType.Seek : RequestType.SeekHard; case "get_playlists": return RequestType.GetPlaylists; default: return RequestType.Unknown; } } ///<summary> ///Get all playlist elements with their values in a list. See class PlaylistElement for mor information ///</summary> ///<returns>All playlist elements found in the xml</returns> public List<PlaylistElement> getAllPlaylistElements() { List<PartyParser.PlaylistElement> ple = new List<PartyParser.PlaylistElement>(); foreach (string name in getPlaylistItemNames()) { ple.Add(parsePlaylistItem(name)); } return ple; } } }
c8713641f8f9418ead4e545406cd052ff945c83c
C#
tvaras/TLS
/TLS-Datos/ProyectoDAL.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TLS_Entidades; namespace TLS_Datos { public class ProyectoDAL { public ResultadoDTO Crear(Proyecto dto) { ResultadoDTO r = new ResultadoDTO(); try { using (ATLSEntities dbo = new ATLSEntities()) { dbo.Proyecto.Add(dto); dbo.SaveChanges(); r.error = false; r.id = dto.idProyecto; } } catch (Exception e) { r.error = true; r.mensaje = e.Message; } return r; } public List<ProyectoDTO> listarProyectos() { List<ProyectoDTO> entidades = new List<ProyectoDTO>(); using (ATLSEntities dbo = new ATLSEntities()) { entidades = (from v in dbo.Proyecto join c in dbo.Usuario on v.creadoPor equals c.idUsuario select new ProyectoDTO() { idProyecto = v.idProyecto, nombreProyecto = v.nombreProyecto, fechaCreacion = v.fechaCreacion, activo = v.activo, creadoPor = c.idUsuario, aliasCreador = c.alias } ).ToList<ProyectoDTO>(); } return entidades; } } }
83bed5d1b84462f56ccf7ea7125d7fd2ec5a8586
C#
Pawel-Paterak/FileManagementSoft
/JsonSoft/Xml/XmlService.cs
2.609375
3
using FMSoft.Xml.Reader; using FMSoft.Xml.Writer; using FMSoft.File; namespace FMSoft.Xml { public class XmlService { private readonly XmlReader xmlReader = new XmlReader(); private readonly XmlWriter xmlWriter = new XmlWriter(); private readonly FileManagement fileManagement = new FileManagement(); public void Serialize<T>(T obj, string path) where T : class { string directory = PathManagement.GetDirectoryFromPath(path); if (FileValidate.ExistsDirectory(directory)) { fileManagement.ChangeFileExtension(ref path, PathExtension.Xml); xmlWriter.Serialize(obj, path); } } public T Deserialize<T>(string path) where T : class { string directory = PathManagement.GetDirectoryFromPath(path); if (FileValidate.ExistsDirectory(directory)) { fileManagement.ChangeFileExtension(ref path, PathExtension.Xml); return xmlReader.Deserialize<T>(path); } return null; } } }
23dcf3337cf498c09c66d2ffc9b933ebc5f0978a
C#
VanHakobyan/OnlineShop1000Plus
/OnlineShop/OnlineShop.Dal/Repositories/Implementation/UserManagementDAL.cs
2.640625
3
using System.Collections.Generic; using System.Linq; using OnlineShop.Common; using OnlineShop.Common.DbModels; using OnlineShop.Dal.Repositories.Interfaces; namespace OnlineShop.Dal.Repositories.Implementation { public class UserManagementDAL : BaseDAL, IUserManagementDAL { public UserManagementDAL(OnlineShopAlphaContext dbContext) : base(dbContext) { } public void AddUser(Users user) { DbContext.Users.Add(user); DbContext.SaveChanges(); } public IEnumerable<Users> AllUsers => DbContext.Users.AsEnumerable(); public IEnumerable<Users> GetAllUsersByPage(int count, int page) { return AllUsers.Skip((page - 1) * count).Take(count); } public Users GetUserById(int id) { return DbContext.Users.Find(id); } public Users GetUserByUsername(string username) { return DbContext.Users.FirstOrDefault(x => x.Username == username); } public Users GetUserByEmail(string email) { return DbContext.Users.FirstOrDefault(x => x.Email == email); } public bool SearchForEmail(string email) { return DbContext.Users.Any(x => x.Email == email); } public bool SearchForUsername(string username) { if (DbContext.Users.Any(x => x.Username == username)) return true; return false; } public void UpdateUser(Users entity) { DbContext.Users.Update(entity); DbContext.SaveChanges(); } public void RemoveUser(Users user) { DbContext.Users.Remove(user); DbContext.SaveChanges(); } public void RemoveUserById(int id) { DbContext.Users.Remove(GetUserById(id)); DbContext.SaveChanges(); } } }
daa18826b82003bb25405fb8fe68659a110fc98d
C#
rags/playground
/DotNet/Remote/RemoteObject.cs
2.625
3
using System; using System.Diagnostics; using System.Runtime.InteropServices; //[Serializable] public class RemoteObject : MarshalByRefObject { public enum ExitFlags { EWX_LogOff= 0, EWX_SHUTDOWN = 1, EWX_REBOOT= 2, EWX_FORCE= 4, EWX_POWEROFF= 8 } [DllImport("user32.dll")] public extern static bool ExitWindowsEx(ExitFlags uFlags,int dwReason); public RemoteObject() { Console.Write("In constructor..."); } public void Test() { Console.Write("test success!"); Process proc = Process.Start(@"C:\Documents and Settings\raghunandanr\Desktop\temp\DOTNET\Remote\helloworld.exe"); } public string ShutDown(ExitFlags flag) { try { ExitWindowsEx(flag,0); return "doing... " + flag.ToString(); } catch(Exception ex){return ex.Message;} } }
e1221bdeff36c4aab99d1bec9cb46d48b933f8e3
C#
schil227/TetrisAdvanced
/TetrisAdvanced/Services/Factories/ShapeFactory.cs
2.90625
3
using System; using System.Collections.Generic; using System.Text; using TetrisAdvanced.Data; using TetrisAdvanced.Interfaces.Factories; namespace TetrisAdvanced.Services.Factories { public class ShapeFactory : IShapeFactory { public IReadOnlyCollection<Shape> GetShapeTypes() { return new List<Shape> { LeftBolt(), RightBolt(), LeftL(), RightL(), T(), Box(), TheHolyLinePiece() }; } // ╚╗ private Shape LeftBolt() { return new Shape { CenterX = 1, CenterY = 1, Boxes = new List<Box> { new Box {X = 0, Y = 0}, new Box {X = 0, Y = 1}, new Box {X = 1, Y = 1}, new Box {X = 1, Y = 2} } }; } // ╔╝ private Shape RightBolt() { return new Shape { CenterX = 1, CenterY = 1, Boxes = new List<Box> { new Box {X = 1, Y = 0}, new Box {X = 1, Y = 1}, new Box {X = 0, Y = 1}, new Box {X = 0, Y = 2} } }; } // ║ // ╚═ private Shape LeftL() { return new Shape { CenterX = 1, CenterY = 1, Boxes = new List<Box> { new Box {X = 0, Y = 0}, new Box {X = 0, Y = 1}, new Box {X = 0, Y = 2}, new Box {X = 1, Y = 2} } }; } // ║ // ═╝ private Shape RightL() { return new Shape { CenterX = 1, CenterY = 1, Boxes = new List<Box> { new Box {X = 1, Y = 0}, new Box {X = 1, Y = 1}, new Box {X = 1, Y = 2}, new Box {X = 0, Y = 2} } }; } // ╩ private Shape T() { return new Shape { CenterX = 1, CenterY = 1, Boxes = new List<Box> { new Box {X = 0, Y = 1}, new Box {X = 1, Y = 1}, new Box {X = 1, Y = 0}, new Box {X = 2, Y = 1} } }; } // ╔═╗ // ╚═╝ private Shape Box() { return new Shape { CenterX = 1, CenterY = 1, Boxes = new List<Box> { new Box {X = 0, Y = 0}, new Box {X = 1, Y = 0}, new Box {X = 1, Y = 1}, new Box {X = 0, Y = 1} } }; } // ║ // ║ private Shape TheHolyLinePiece() { return new Shape { CenterX = 0, CenterY = 0, Boxes = new List<Box> { new Box {X = 0, Y = 0}, new Box {X = 0, Y = 1}, new Box {X = 0, Y = 2}, new Box {X = 0, Y = 3} } }; } } }
f896dde6b063456801688287956e662619ea65ff
C#
tshevka/tcone
/tcone/TConecs.cs
3.5625
4
using System; using System.Collections.Generic; using System.Text; namespace tcone { class TCone : TCircle { private double height; public double Height { get { return height; } set { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); else this.height = value; } } public TCone() : base() { Height = 1; } public TCone(double height) { this.height = height; } public TCone(double radius, double height) : base(radius) => this.Height = height; public override string ToString() => base.ToString() + $"\tHeight:{this.Height}"; public TCone(TCircle circle, double height) : base(circle) { this.Height = height; } public double Volume() { return (1 / 3) * Math.PI * Math.Pow(Radius, 2) * Height; } public static bool operator >(TCone cone1, TCone cone2) { return cone1.Volume() > cone2.Volume(); } public static bool operator <(TCone cone1, TCone cone2) { return cone1.Volume() < cone2.Volume(); } public static bool operator ==(TCone cone1, TCone cone2) { return cone1.Volume() == cone2.Volume(); } public static bool operator !=(TCone cone1, TCone cone2) { return cone1.Volume() != cone2.Volume(); } public override bool Equals(object? obj) { if (obj is null) { throw new ArgumentNullException(nameof(obj)); } if (this.GetType() != obj.GetType()) return false; TCone temp = (TCone)obj; return Volume() == temp.Volume(); } public override int GetHashCode() { return Volume().GetHashCode(); } } }
c9ddfba9dd9ea239f2d5b91da7242942a89ae6bc
C#
hanhaitao/PdfConverter
/PDF Convert/AnimatorImage.cs
2.890625
3
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Imaging; namespace PDF_Convert { /// /// 表示一类带动画功能的图像。 /// public class AnimateImage { Image image; FrameDimension frameDimension; /// /// 动画当前帧发生改变时触发。 /// public event EventHandler OnFrameChanged; /// /// 实例化一个AnimateImage。 /// /// 动画图片。 public AnimateImage(Image img) { image = img; lock (image) { mCanAnimate = ImageAnimator.CanAnimate(image); if (mCanAnimate) { Guid[] guid = image.FrameDimensionsList; //mFrameCount = image.GetFrameCount(frameDimension); } } } bool mCanAnimate; int mFrameCount = 1, mCurrentFrame = 0; /// /// 图片。 /// public Image Image { get { return image; } } /// /// 是否动画。 /// public bool CanAnimate { get { return mCanAnimate; } } /// /// 总帧数。 /// public int FrameCount { get { return mFrameCount; } } /// /// 播放的当前帧。 /// public int CurrentFrame { get { return mCurrentFrame; } } /// /// 播放这个动画。 /// public void Play() { if (mCanAnimate) { lock (image) { ImageAnimator.Animate(image, new EventHandler(FrameChanged)); } } } /// /// 停止播放。 /// public void Stop() { if (mCanAnimate) { lock (image) { ImageAnimator.StopAnimate(image, new EventHandler(FrameChanged)); } } } /// /// 重置动画,使之停止在第0帧位置上。 /// public void Reset() { if (mCanAnimate) { ImageAnimator.StopAnimate(image, new EventHandler(FrameChanged)); lock (image) { image.SelectActiveFrame(frameDimension, 0); mCurrentFrame = 0; } } } private void FrameChanged(object sender, EventArgs e) { mCurrentFrame = mCurrentFrame + 1 >= mFrameCount ? 0 : mCurrentFrame + 1; lock (image) { image.SelectActiveFrame(frameDimension, mCurrentFrame); } if (OnFrameChanged != null) { OnFrameChanged(image, e); } } } }
79b129cf62480d8a0c0374efab620befdd4124b8
C#
s-kyper/CSharp6sem
/first3/first3/Matrix3x3.cs
3.21875
3
using System; namespace first3 { public struct Matrix3x3 { private CoVector3[] cv; private Vector3[] v; private Vector3 v1; private Vector3 v2; private Vector3 v3; public double X1 => v1.X; public double Y1 => v1.Y; public double Z1 => v1.Z; public double X2 => v2.X; public double Y2 => v2.Y; public double Z2 => v2.Z; public double X3 => v3.X; public double Y3 => v3.Y; public double Z3 => v3.Z; public double Det => X1 * Y2 * Z3 + Y1 * Z2 * X3 + Z1 * Y3 * X2 -X3 * Y2 * Z1 - Y3 * Z2 * X1 - Z3 * Y1 * X2; public double Norm => Math.Sqrt( X1 * X1 + Y1 * Y1 + X2 * X2 + Y2 * Y2); public double Trace => v1.X + v2.Y + v3.Z; public Matrix3x3 Transposed => new Matrix3x3(new Vector3(v1.X, v2.X, v3.X), new Vector3(v1.Y, v2.Y, v3.Y), new Vector3(v1.Z, v2.Z, v3.Z)); public Matrix3x3 Inversed => new Matrix3x3(v2 ^ v3, -1 * v1 ^ v3, v1 ^ v2).Transposed / Det; //It really works public Matrix3x3 Symmetrized => (this + Transposed) / 2; public Matrix3x3 Asymmetrized => (this - Transposed) / 2; public Matrix3x3(Vector3[] vectors) : this(vectors[0], vectors[1], vectors[2]) {} public Matrix3x3(Vector3 u1, Vector3 u2, Vector3 u3) { v1 = u1; v2 = u2; v3 = u3; cv = new CoVector3[3] {new CoVector3(v1.X, v2.X, v3.X), new CoVector3(v1.Y, v2.Y, v3.Y), new CoVector3(v1.Z, v2.Z, v3.Z)}; v = new Vector3[3] {v1, v2, v3}; } public Matrix3x3(CoVector3 cu1, CoVector3 cu2, CoVector3 cu3) : this(new Vector3(cu1.X, cu2.X, cu3.X), new Vector3(cu1.Y, cu2.Y, cu3.Y), new Vector3(cu1.Z, cu2.Z, cu3.Z)) {} public Matrix3x3(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3) : this(new Vector3(x1, y1, z1), new Vector3(x2, y2, z2), new Vector3(x3, y3, z3)) {} public override bool Equals(object obj) { if (!(obj is Matrix3x3)) { return false; } return Equals((Matrix3x3)obj); } public bool Equals(Matrix3x3 m) { return (v1 == m.v1 && v2 == m.v2 && v3 == m.v3); } public static bool operator ==(Matrix3x3 m1, Matrix3x3 m2) { return m1.Equals(m2); } public static bool operator !=(Matrix3x3 m1, Matrix3x3 m2) { return !(m1 == m2); } public static Matrix3x3 operator +(Matrix3x3 m1, Matrix3x3 m2) { return new Matrix3x3(m1.v1 + m2.v1, m1.v2 + m2.v2, m1.v3 + m2.v3); } public static Matrix3x3 operator -(Matrix3x3 m1, Matrix3x3 m2) { return new Matrix3x3(m1.v1 - m2.v1, m1.v2 - m2.v2, m1.v3 - m2.v3); } public static Matrix3x3 operator *(double scalar, Matrix3x3 m) { return new Matrix3x3(Array.ConvertAll(m.v, v => scalar * v)); } public static Matrix3x3 operator *(Matrix3x3 m, double scalar) { return scalar * m; } public static Vector3 operator *(Vector3 vector, Matrix3x3 m) { return new Vector3(Array.ConvertAll(m.v, v => vector * v)); } public static Vector3 operator *(Matrix3x3 m, Vector3 vector) { return vector * m; } public static CoVector3 operator *(CoVector3 covector, Matrix3x3 m) { return new CoVector3(Array.ConvertAll(m.v, v => covector * v)); } public static CoVector3 operator *(Matrix3x3 m, CoVector3 covector) { return covector * m; } public static Matrix3x3 operator *(Matrix3x3 m1, Matrix3x3 m2) { return new Matrix3x3( new Vector3(Array.ConvertAll(m2.cv, cv => cv * m1.v1)), new Vector3(Array.ConvertAll(m2.cv, cv => cv * m1.v2)), new Vector3(Array.ConvertAll(m2.cv, cv => cv * m1.v3)) ); } public static Matrix3x3 operator /(Matrix3x3 m, double scalar) { return new Matrix3x3(Array.ConvertAll(m.v, v => v / scalar)); } public override string ToString() { return string.Format("X1: {0}, Y1: {1}, Z1: {2}\nX2: {3}, Y2: {4}, Z2: {5}\nX3: {6}, Y3: {7}, Z3: {8}", X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); } } }
5e95f012490295ab738f04631d1b0306b96581e0
C#
rickinator9/DawnOfCivilisation
/Assets/Source/Contexts/Game/Model/Map/ILandTile.cs
2.75
3
using System.Collections.Generic; using System.Linq; using Assets.Source.Contexts.Game.Model.Country; using UnityEngine; namespace Assets.Source.Contexts.Game.Model.Map { public interface ILandTile : IHexTile { int Population { get; } ICountry Country { get; set; } ICountry Controller { get; set; } bool IsOccupied { get; } ICity City { get; set; } bool HasCity { get; } bool AllowsCity { get; } void Initialise(HexCoordinates coordinates, HexTerrainType terrainType, int population); } public class LandTile : HexTile, ILandTile { public override Color Color { get { if (Country == null) return new Color(0, 0, 0, 0); return Country.Color; } } private HexTerrainType _terrainType; public override HexTerrainType TerrainType { get { return _terrainType; } } public int Population { get; private set; } private ICountry _country; public ICountry Country { get { return _country; } set { _country = value; foreach (var signal in RefreshHexGridViewSignals) { signal.Dispatch(); } } } private ICountry _controller; public ICountry Controller { get { return _controller; } set { if (_country == null) return; _controller = value; foreach (var signal in RefreshHexGridViewSignals) { signal.Dispatch(); } } } public bool IsOccupied { get { return Country != Controller; } } public ICity City { get; set; } public bool HasCity { get { return City != null; } } public bool AllowsCity { get { var landNeighboursSet = new HashSet<ILandTile>(); foreach (var landNeighbor in GetLandNeighbors(this)) { landNeighboursSet.Add(landNeighbor); foreach (var neighbor in GetLandNeighbors(landNeighbor)) { landNeighboursSet.Add(neighbor); } } return landNeighboursSet.All(hex => !hex.HasCity); } } public void Initialise(HexCoordinates coordinates, HexTerrainType terrainType, int population) { Coordinates = coordinates; _terrainType = terrainType; Population = population; } private IList<ILandTile> GetLandNeighbors(IHexTile tile) { return tile.Neighbors.Where(neighbor => neighbor != null && neighbor.TerrainType != HexTerrainType.Water).Cast<ILandTile>().ToList(); } } }
53cdb1f3737a95726856b1ff4f54ddc80263fabf
C#
IvanParvanov/Indexed.Everything
/src/Indexed.Everything.Tests/IndexedTests/Ctor_Should.cs
2.5625
3
using System; using System.Collections.Generic; using AutoFixture; using Indexed.Everything.Contracts; using Indexed.Everything.Tests.Misc; using Moq; using NUnit.Framework; namespace Indexed.Everything.Tests.IndexedTests { [TestFixture] internal class Ctor_Should { private readonly Fixture fixture = new Fixture(); [Test] public void Throw_ArgumentNullException_WhenInstanceIsNull() { // Act & Assert Assert.Throws<ArgumentNullException>(() => new Indexed(null, false)); } [Test] public void Throw_ArgumentNullException_WhenInstanceIsNull_() { // Act & Assert Assert.Throws<ArgumentNullException>(() => new Indexed<TestPerson>(null)); } [Test] public void DoesNotThrow_ArgumentNullException_WhenInstanceIsNotNull() { // Act & Assert Assert.DoesNotThrow(() => new Indexed<object>(new object())); } [Test] public void Throw_ArgumentException_WhenInstanceIsIndexed() { // Act & Assert Assert.Throws<ArgumentException>(() => new Indexed(new Indexed(1, false), false)); } [Test] public void Call_FactoryBuildGetSetFuncsMethodWithCorrectparamsOnce() { // Arrange TestPerson instance = this.fixture.Create<TestPerson>(); Mock<IFunkyFactory> factoryMock = TestHelper.GetMockedFunkyFactory(); // Act Indexed _ = new Indexed(instance, true, factoryMock.Object); // Assert factoryMock.Verify(x => x.GetPropertyAccessorFuncs(It.Is<Type>(t => t.FullName == typeof(TestPerson).FullName)), Times.Once); } [Test] public void ToString_ShouldAddAllPropertiesToOutput() { // Arrange TestPerson instance = this.fixture.Create<TestPerson>(); Mock<IFunkyFactory> factoryMock = TestHelper.GetMockedFunkyFactory(); Indexed sut = new Indexed(instance, true, factoryMock.Object); // Act string actual = sut.ToString(); // Assert StringAssert.Contains(nameof(TestPerson.Name), actual); StringAssert.Contains(instance.Name, actual); StringAssert.Contains(nameof(TestPerson.Age), actual); StringAssert.Contains(instance.Age.ToString(), actual); } } }
0a715fc9855d564bed0e9f944ce3c292bb5a48a7
C#
gcm10000/MovieTime
/MovieTimeApp/Client.cs
2.921875
3
using Microsoft.AspNet.SignalR.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MovieTimeApp { public class Client { private HubConnection hubConnection; //private IHubProxy hub; public Client() { //Set connection var connection = new HubConnection("http://localhost:5000/"); //Make proxy to hub based on hub name on server var myHub = connection.CreateHubProxy("SocketHub"); //Start connection connection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException()); } else { Console.WriteLine("Connected"); } }).Wait(); //hub.Invoke("SendMessage", new[] { "teste", "alo" }); } public async Task StartConnection() { await hubConnection.Start(); } //public void Send(string method, string window, string message ) //{ // hub.Invoke(method, new[] { window, message }); //} //public void Receive(string method, Action<string, string> data) //{ // hub.On(method, data); //} } }
721e41a7db5d304bfe48144c5688bc881e5dc298
C#
lavanyathotakura22/MainStructures
/Extensions/Extends1.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExtensionMethods { public interface IMyInterface{ //Interface craetion void MethodB(); } class A : IMyInterface { public void MethodB() { Console.WriteLine("A.MethodB()"); } } class B : IMyInterface { public void MethodB() { Console.WriteLine("B.MethodB()"); } public void MethodA(int i) { Console.WriteLine("B.MethodA(int i)"); } } class C : IMyInterface { public void MethodB() { Console.WriteLine("C.MethodB()"); } public void MethodA(object obj) { Console.WriteLine("C.MethodA(object obj)"); } } class ExtMethodDemo { static void Main(string[] args) { A a = new A(); B b = new B(); C c = new C(); a.MethodA(1); // Extension.MethodA(IMyInterface, int) // a.MethodA("hello"); // Extension.MethodA(IMyInterface, string) a.MethodB(); // A.MethodB(). b.MethodA(1); // B.MethodA(int) b.MethodB(); // B.MethodB(). b.MethodA("hello"); // Extension.MethodA(IMyInterface, string) c.MethodA(1); // C.MethodA(object) c.MethodA("hello"); // C.MethodA(object) c.MethodB(); // C.MethodB() } } }
4d42d0e6422b16226980c4c8bb05971df9d25e64
C#
shendongnian/download4
/code10/1734461-50298287-173225772-2.cs
2.796875
3
public interface ISampleRepository : IDisposable { IEnumerable<SampleModel> GetAllSamples(); } public class SampleContext : ISampleRepository { public IEnumerable<SampleModel> GetAllSamples() { // Implementation } } public interface ISampleFactory { ISampleRepository Create(); } public class SampleFactory { ISampleRepository Create() => new SampleContext(); }
03a2287e23fe9e5bdbae0b6e64dc351054a5378f
C#
beandrake/crud-exercise
/PassengerManager/PassengerManager/Data/OverallContext.cs
3.015625
3
// adapted from: https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro using PassengerManager.Models; using Microsoft.EntityFrameworkCore; namespace PassengerManager.Data { /* * In the codeschool MVC ASP.NET Core lectures * (https://www.codeschool.com/courses/try-asp-net-core) * it seemed to be suggested that each Model n get its own nContext class. * However, in the tutorial used to create most of this program, a single * Context class was used. I decided to follow the second approach, * primarily because it looked to be a more manageable method. * I intentionally gave it a very generic name, so as not to restrict * future development when other Models such as Cruises or Cruiseliner * are likely to be introduced. */ public class OverallContext : DbContext { public OverallContext(DbContextOptions<OverallContext> options) : base(options) { } // any models we want to map to the database go here with this format public DbSet<Passenger> Passengers { get; set; } // makes the table name singular instead of plural (overrides the default behavior) protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Passenger>().ToTable("Passenger"); } } }
fbb2b9a279c76bcff9bed1e5af46137bfe57a02e
C#
alexsp17/SnookerByb
/Awpbs.Web.Data/DataLogic/FeedLogic.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Awpbs.Web { public class FeedLogic { private readonly ApplicationDbContext db; public FeedLogic(ApplicationDbContext db) { this.db = db; } public int GetObjectIDFromComment(Comment comment) { switch ((NewsfeedItemTypeEnum)comment.ObjectType) { case NewsfeedItemTypeEnum.Post: return comment.PostID ?? 0; case NewsfeedItemTypeEnum.GameHost: return comment.GameHostID ?? 0; case NewsfeedItemTypeEnum.NewUser: return comment.NewUserID ?? 0; case NewsfeedItemTypeEnum.Result: return comment.ResultID ?? 0; case NewsfeedItemTypeEnum.Score: return comment.ScoreID ?? 0; } return 0; } public int MakePost(int athleteID, Country country, string text) { var athlete = db.Athletes.Where(i => i.AthleteID == athleteID).Single(); var post = new Post() { AthleteID = athleteID, Country = country.ThreeLetterCode, PostText = text, Time = DateTime.UtcNow, }; db.Posts.Add(post); db.SaveChanges(); return post.PostID; } public int MakePost(int athleteID, int metroID, string text) { var athlete = db.Athletes.Where(i => i.AthleteID == athleteID).Single(); var metro = db.Metros.Where(i => i.MetroID == metroID).Single(); string country = metro.Country; if (string.IsNullOrEmpty(country)) throw new Exception("unknown country"); var post = new Post() { AthleteID = athleteID, Country = metro.Country, MetroID = metro.MetroID, PostText = text, Time = DateTime.UtcNow, }; db.Posts.Add(post); db.SaveChanges(); return post.PostID; } public void SetLike(int athleteID, NewsfeedItemTypeEnum objectType, int objectID, bool like) { var athlete = db.Athletes.Where(i => i.AthleteID == athleteID).Single(); var comment = new Comment() { AthleteID = athleteID, ObjectType = (int)objectType, CommentText = null, CommentType = (int)CommentTypeEnum.Like, Time = DateTime.UtcNow, }; switch (objectType) { case NewsfeedItemTypeEnum.Post: comment.PostID = objectID; break; case NewsfeedItemTypeEnum.Result: comment.ResultID = objectID; break; case NewsfeedItemTypeEnum.Score: comment.ScoreID = objectID; break; case NewsfeedItemTypeEnum.GameHost: comment.GameHostID = objectID; break; case NewsfeedItemTypeEnum.NewUser: comment.NewUserID = objectID; break; default: throw new NotImplementedException("unknown objectType"); } var existingComment = (from c in db.Comments where c.ObjectType == comment.ObjectType where c.AthleteID == comment.AthleteID where c.PostID == comment.PostID where c.ResultID == comment.ResultID where c.ScoreID == comment.ScoreID where c.GameHostID == comment.GameHostID where c.NewUserID == comment.NewUserID where c.CommentType == comment.CommentType select c).FirstOrDefault(); if (existingComment != null) db.Comments.Remove(existingComment); if (like) db.Comments.Add(comment); db.SaveChanges(); } public async Task<int> MakeComment(int athleteID, NewsfeedItemTypeEnum objectType, int objectID, string text, bool notifyAll) { var athlete = db.Athletes.Where(i => i.AthleteID == athleteID).Single(); // save the comment var comment = new Comment() { AthleteID = athleteID, ObjectType = (int)objectType, CommentText = text, Time = DateTime.UtcNow, CommentType = (int)CommentTypeEnum.Comment }; switch (objectType) { case NewsfeedItemTypeEnum.Post: comment.PostID = objectID; break; case NewsfeedItemTypeEnum.Result: comment.ResultID = objectID; break; case NewsfeedItemTypeEnum.Score: comment.ScoreID = objectID; break; case NewsfeedItemTypeEnum.GameHost: comment.GameHostID = objectID; break; case NewsfeedItemTypeEnum.NewUser: comment.NewUserID = objectID; break; default: throw new NotImplementedException("unknown objectType"); } db.Comments.Add(comment); db.SaveChanges(); if (notifyAll) { if (objectType == NewsfeedItemTypeEnum.GameHost) await this.notifyAllAttendees(objectID, athlete, text); else await this.notifyAllInvolvedAthletes(athleteID, objectType, objectID, comment.CommentID, text); } return comment.CommentID; } public List<CommentWebModel> GetComments(NewsfeedItemTypeEnum objectType, int objectID) { int? postID = null; int? resultID = null; int? scoreID = null; int? gameHostID = null; int? newUserID = null; switch (objectType) { case NewsfeedItemTypeEnum.Post: postID = objectID; break; case NewsfeedItemTypeEnum.Result: resultID = objectID; break; case NewsfeedItemTypeEnum.Score: scoreID = objectID; break; case NewsfeedItemTypeEnum.GameHost: gameHostID = objectID; break; case NewsfeedItemTypeEnum.NewUser: newUserID = objectID; break; default: throw new NotImplementedException("unknown objectType"); } var comments = (from i in db.Comments where i.CommentType == (int)CommentTypeEnum.Comment where i.ObjectType == (int)objectType where i.PostID == postID where i.ResultID == resultID where i.ScoreID == scoreID where i.GameHostID == gameHostID where i.NewUserID == newUserID orderby i.Time descending select new CommentWebModel() { ID = i.CommentID, AthleteID = i.AthleteID, AthleteName = i.Athlete.Name, AthletePicture = i.Athlete.Picture, Text = i.CommentText, Time = i.Time, }).ToList(); return comments; } public NewsfeedItemWebModel GetNewsfeedItem(int myAthleteID, NewsfeedItemTypeEnum objectType, int objectID) { List<NewsfeedItemWebModel> items = null; switch (objectType) { case NewsfeedItemTypeEnum.Post: items = this.getPosts(myAthleteID, db.Posts.Where(i => i.PostID == objectID)).ToList(); break; case NewsfeedItemTypeEnum.Result: items = this.getResults(myAthleteID, db.Results.Where(i => i.ResultID == objectID)).ToList(); break; case NewsfeedItemTypeEnum.Score: items = this.getScores(myAthleteID, db.Scores.Where(i => i.ScoreID == objectID)).ToList(); break; case NewsfeedItemTypeEnum.GameHost: items = this.getGameHosts(myAthleteID, db.GameHosts.Where(i => i.GameHostID == objectID)).ToList(); break; case NewsfeedItemTypeEnum.NewUser: items = this.getNewUsers(myAthleteID, db.Athletes.Where(i => i.AthleteID == objectID)).ToList(); break; } if (items == null || items.Count != 1) return null; return items[0]; } public NewsfeedWebModel GetGlobalNewsfeed(int myAthleteID) { NewsfeedWebModel newsfeed = new NewsfeedWebModel(); newsfeed.Items = new List<NewsfeedItemWebModel>(); newsfeed.Items.AddRange(this.getPosts(myAthleteID, (from i in db.Posts select i))); newsfeed.Items.AddRange(this.getResults(myAthleteID, (from i in db.Results select i))); newsfeed.Items.AddRange(this.getScores(myAthleteID, (from i in db.Scores select i))); newsfeed.Items.AddRange(this.getGameHosts(myAthleteID, (from i in db.GameHosts where i.EventType != (int)EventTypeEnum.Private select i))); newsfeed.Items.AddRange(this.getNewUsers(myAthleteID, (from i in db.Athletes select i))); newsfeed.Items = newsfeed.Items.OrderByDescending(i => i.Time).Take(NewsfeedWebModel.MaxItems).ToList(); return newsfeed; } public NewsfeedWebModel GetNewsfeedForCountry(int myAthleteID, Country country) { NewsfeedWebModel newsfeed = new NewsfeedWebModel(); newsfeed.Items = new List<NewsfeedItemWebModel>(); newsfeed.Items.AddRange(this.getPosts(myAthleteID, (from i in db.Posts where i.Country == country.ThreeLetterCode select i))); newsfeed.Items.AddRange(this.getResults(myAthleteID, (from i in db.Results where i.Athlete.Country == country.ThreeLetterCode select i))); newsfeed.Items.AddRange(this.getScores(myAthleteID, (from i in db.Scores where i.AthleteA.Country == country.ThreeLetterCode select i))); newsfeed.Items.AddRange(this.getGameHosts(myAthleteID, (from i in db.GameHosts where i.EventType != (int)EventTypeEnum.Private where i.Venue.Country == country.ThreeLetterCode select i))); newsfeed.Items.AddRange(this.getNewUsers(myAthleteID, (from i in db.Athletes where i.Country == country.ThreeLetterCode select i))); newsfeed.Items = newsfeed.Items.OrderByDescending(i => i.Time).Take(NewsfeedWebModel.MaxItems).ToList(); return newsfeed; } public NewsfeedWebModel GetNewsfeedForMetro(int myAthleteID, int metroID) { Metro metro = db.Metros.Where(i => i.MetroID == metroID).Single(); string country = metro.Country; NewsfeedWebModel newsfeed = new NewsfeedWebModel(); newsfeed.Items = new List<NewsfeedItemWebModel>(); newsfeed.Items.AddRange(this.getPosts(myAthleteID, (from i in db.Posts where i.MetroID == metroID || (i.MetroID == null && i.Country == country) select i))); newsfeed.Items.AddRange(this.getResults(myAthleteID, (from i in db.Results where i.Athlete.MetroID == metroID select i))); newsfeed.Items.AddRange(this.getScores(myAthleteID, (from i in db.Scores where i.AthleteA.MetroID == metroID select i))); newsfeed.Items.AddRange(this.getGameHosts(myAthleteID, (from i in db.GameHosts where i.EventType != (int)EventTypeEnum.Private where i.Venue.MetroID == metroID select i))); newsfeed.Items.AddRange(this.getNewUsers(myAthleteID, (from i in db.Athletes where i.MetroID == metroID select i))); newsfeed.Items = newsfeed.Items.OrderByDescending(i => i.Time).Take(NewsfeedWebModel.MaxItems).ToList(); return newsfeed; } List<NewsfeedItemWebModel> getPosts(int myAthleteID, IQueryable<Post> query) { var list = (from i in query orderby i.Time descending select new NewsfeedItemWebModel() { ItemType = NewsfeedItemTypeEnum.Post, ID = i.PostID, AthleteID = i.AthleteID, AthleteName = i.Athlete.Name, AthletePicture = i.Athlete.Picture, Text = i.PostText, Time = i.Time, CommentsCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Comment).Count(), LikesCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like).Count(), Liked = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like && c.AthleteID == myAthleteID).Count() > 0, }).Take(NewsfeedWebModel.MaxItems).ToList(); return list; } List<NewsfeedItemWebModel> getResults(int myAthleteID, IQueryable<Result> query) { var list = (from i in query where i.Date != null where i.IsDeleted == false where i.IsNotAcceptedByAthleteYet == false where i.OpponentConfirmation != (int)OpponentConfirmationEnum.Declined //where i.OpponentConfirmation == (int)OpponentConfirmationEnum.Confirmed where i.Count != null orderby i.Date descending select new NewsfeedItemWebModel() { ItemType = NewsfeedItemTypeEnum.Result, ID = i.ResultID, AthleteID = i.AthleteID, AthleteName = i.Athlete.Name, AthletePicture = i.Athlete.Picture, Text = i.Count.Value.ToString(), Time = i.Date.Value, VenueID = i.VenueID ?? 0, VenueName = i.VenueID != null ? i.Venue.Name : "", CommentsCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Comment).Count(), LikesCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like).Count(), Liked = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like && c.AthleteID == myAthleteID).Count() > 0, }).Take(NewsfeedWebModel.MaxItems).ToList(); return list; } List<NewsfeedItemWebModel> getScores(int myAthleteID, IQueryable<Score> query) { var list = (from i in query where i.Date != null where i.IsDeleted == false where i.IsUnfinished == false where i.AthleteBConfirmation == (int)OpponentConfirmationEnum.Confirmed orderby i.Date descending select new NewsfeedItemWebModel() { ItemType = NewsfeedItemTypeEnum.Score, ID = i.ScoreID, AthleteID = i.AthleteAID, AthleteName = i.AthleteA.Name, AthletePicture = i.AthleteA.Picture, Athlete2ID = i.AthleteBID, Athlete2Name = i.AthleteB.Name, Athlete2Picture = i.AthleteB.Picture, Text = i.PointsA.ToString() + " : " + i.PointsB.ToString(), Time = i.Date, VenueID = i.VenueID ?? 0, VenueName = i.VenueID != null ? i.Venue.Name : "", CommentsCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Comment).Count(), LikesCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like).Count(), Liked = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like && c.AthleteID == myAthleteID).Count() > 0, }).Take(NewsfeedWebModel.MaxItems).ToList(); return list; } List<NewsfeedItemWebModel> getGameHosts(int myAthleteID, IQueryable<GameHost> query) { var list = (from i in query orderby i.When descending select new NewsfeedItemWebModel() { ItemType = NewsfeedItemTypeEnum.GameHost, ID = i.GameHostID, AthleteID = i.AthleteID, AthleteName = i.Athlete.Name, AthletePicture = i.Athlete.Picture, Text = "An invite", Time = i.TimeCreated, TimeOfEvent = i.When, TimeOfEventLocal = i.When_InLocalTimeZone, VenueID = i.VenueID ?? 0, VenueName = i.VenueID != null ? i.Venue.Name : "", CommentsCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Comment).Count(), LikesCount = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like).Count(), Liked = i.Comments.Where(c => c.CommentType == (int)CommentTypeEnum.Like && c.AthleteID == myAthleteID).Count() > 0, }).Take(NewsfeedWebModel.MaxItems).ToList(); return list; } List<NewsfeedItemWebModel> getNewUsers(int myAthleteID, IQueryable<Athlete> query) { var list = (from i in query orderby i.TimeCreated descending let commentsCount = (from c in db.Comments where c.CommentType == (int)CommentTypeEnum.Comment where c.ObjectType == (int)NewsfeedItemTypeEnum.NewUser where c.NewUserID == i.AthleteID select c).Count() let likesCount = (from c in db.Comments where c.CommentType == (int)CommentTypeEnum.Like where c.ObjectType == (int)NewsfeedItemTypeEnum.NewUser where c.NewUserID == i.AthleteID select c).Count() let liked = (from c in db.Comments where c.CommentType == (int)CommentTypeEnum.Like where c.ObjectType == (int)NewsfeedItemTypeEnum.NewUser where c.NewUserID == i.AthleteID where c.AthleteID == myAthleteID select c).Count() > 0 select new NewsfeedItemWebModel() { ItemType = NewsfeedItemTypeEnum.NewUser, ID = i.AthleteID, AthleteID = i.AthleteID, AthleteName = i.Name, AthletePicture = i.Picture, Text = "New user", Time = i.TimeCreated, CommentsCount = commentsCount, LikesCount = likesCount, Liked = liked, }).Take(NewsfeedWebModel.MaxItems).ToList(); return list; } async Task notifyAllInvolvedAthletes(int myAthleteID, NewsfeedItemTypeEnum objectType, int objectID, int commentID, string commentText) { try { var myAthlete = db.Athletes.Where(i => i.AthleteID == myAthleteID).Single(); // list of athletes involved var item = this.GetNewsfeedItem(myAthleteID, objectType, objectID); if (item == null) return; var comments = this.GetComments(objectType, objectID); List<int> athleteIDs = new List<int>(); athleteIDs.Add(item.AthleteID); if (athleteIDs.Contains(item.Athlete2ID) == false) athleteIDs.Add(item.Athlete2ID); foreach (var comment in comments) if (athleteIDs.Contains(comment.AthleteID) == false) athleteIDs.Add(comment.AthleteID); athleteIDs.Remove(0); athleteIDs.Remove(myAthleteID); foreach (int athleteID in athleteIDs) { try { var athlete = db.Athletes.Where(i => i.AthleteID == athleteID).Single(); // send push notification new PushNotificationsLogic(db).SendNotification(athleteID, PushNotificationMessage.BuildComment(myAthlete, commentText, commentID)); // email string subject = "'Byb' - " + athlete.Name + " commented on a tracked conversation"; string link1 = new DeepLinkHelper().BuildOpenBybLink_Comment(commentID); string link2 = new DeepLinkHelper().BuildLinkToComment(commentID); string html = string.Format(htmlMessage_Post, myAthlete.NameOrUserName, commentText, link1, link2); await new EmailService().SendEmailToAthlete(athlete, subject, html); } catch (Exception) { } } PushNotificationProcessor.TheProcessor.PushAllPendingNotifications(); } catch (Exception) { } } async Task notifyAllAttendees(int gameHostID, Athlete myAthlete, string commentText) { try { var gameHost = db.GameHosts.Where(i => i.GameHostID == gameHostID).Single(); var venue = db.Venues.Where(i => i.VenueID == gameHost.VenueID).Single(); // list of attendees and people that commented var athleteIDs = gameHost.GameHostInvites.Where(i => i.IsDeniedByInvitee == false).Select(i => i.AthleteID).ToList(); if (athleteIDs.Contains(gameHost.AthleteID) == false) athleteIDs.Add(gameHost.AthleteID); var commentAthleteIDs = gameHost.Comments.Select(i => i.AthleteID).ToList(); foreach (int id in commentAthleteIDs) if (athleteIDs.Contains(id) == false) athleteIDs.Add(id); athleteIDs.Remove(0); athleteIDs.Remove(myAthlete.AthleteID); foreach (int athleteID in athleteIDs) { try { var athlete = db.Athletes.Where(i => i.AthleteID == athleteID).Single(); // send push notification new PushNotificationsLogic(db).SendNotification(athleteID, PushNotificationMessage.BuildGameCommentMessage(myAthlete, commentText, gameHostID)); // send email string when = gameHost.When_InLocalTimeZone.ToLongDateString() + " - " + gameHost.When_InLocalTimeZone.ToShortTimeString(); string subject = "'Byb' - " + myAthlete.Name + " commented on an invite"; string link1 = new DeepLinkHelper().BuildOpenBybLink_GameHost(gameHost.GameHostID); string link2 = new DeepLinkHelper().BuildLinkToGameHost(gameHost.GameHostID); string html = string.Format(htmlComment_GameHost, myAthlete.Name, gameHost.When_InLocalTimeZone, venue.Name, commentText, link1, link2); await new EmailService().SendEmailToAthlete(athlete, subject, html); } catch (Exception) { } } PushNotificationProcessor.TheProcessor.PushAllPendingNotifications(); } catch (Exception) { } } string htmlMessage_Post = @"<html> <head> </head> <body> <p style=""color:gray;""><i>Do not reply directly to this email, instead please follow the links below.</i></p> <p>A player commented on a tracked conversation:</p> <p><span style=""color:gray;"">Player: </span><span style=""font-weight:bold"">{0}</span></p> <p><span style=""color:gray;"">Comment: </span><span style = ""font-weight:bold;text-color:black"">{1}</span></p> <br> <p>Open conversation in Snooker Byb:</p> <p style = ""margin-top:30px;margin-bottom:30px;"" > <a style=""font-weight:bold; background:#DB3638;color:white;padding: 15px 40px 15px 40px"" href=""{2}"">Open in Byb</a> </p> <p>If doesn't work, try this:</p> <p style = ""margin-top:30px;margin-bottom:30px;"" > <a style=""font-weight:bold; background:#DB3638;color:white;padding: 15px 40px 15px 40px"" href=""{3}"">Open in Byb</a> </p> <p> <span style=""color:gray;"">Snooker Byb Team</span>: This function is in early beta. Please excuse our bugs. Feel free to shoot us a message with your suggestions and ideas: <a>team@snookerbyb.com</a> </p> </body> </html>"; string htmlComment_GameHost = @"<html> <head> </head> <body> <p style=""color:gray;""><i>Do not reply directly to this email, instead please follow the links below.</i></p> <p><span style=""color:gray;"">Player: </span><span style=""font-weight:bold"">{0}</span></p> <p><span style=""color:gray;"">At: </span><span style = ""font-weight:bold"">{2}</span></p> <p><span style=""color:gray;"">When: </span><span style = ""font-weight:bold;text-color:black"">{1}</span></p> <p><span style=""color:gray;"">Comment: </span><span style = ""font-weight:bold;text-color:black"">{3}</span></p> <br> <p>Open in Snooker Byb:</p> <p style = ""margin-top:30px;margin-bottom:30px;"" > <a style=""font-weight:bold; background:#DB3638;color:white;padding: 15px 40px 15px 40px"" href=""{4}"">Open the Invite</a> </p> <p>If doesn't work, try this:</p> <p style = ""margin-top:30px;margin-bottom:30px;"" > <a style=""font-weight:bold; background:#DB3638;color:white;padding: 15px 40px 15px 40px"" href=""{5}"">Open the Invite</a> </p> <p> <span style=""color:gray;"">Snooker Byb Team</span>: This function is in early beta. Please excuse our bugs. Feel free to shoot us a message with your suggestions and ideas: <a>team@snookerbyb.com</a> </p> </body> </html>"; } }
dfffdd247995f4def3adeb3d77539fd60f550d42
C#
Ryujinx/Ryujinx
/src/Ryujinx.Graphics.Vulkan/NativeArray.cs
2.765625
3
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Ryujinx.Graphics.Vulkan { unsafe class NativeArray<T> : IDisposable where T : unmanaged { public T* Pointer { get; private set; } public int Length { get; } public ref T this[int index] { get => ref Pointer[Checked(index)]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int Checked(int index) { if ((uint)index >= (uint)Length) { throw new IndexOutOfRangeException(); } return index; } public NativeArray(int length) { Pointer = (T*)Marshal.AllocHGlobal(checked(length * Unsafe.SizeOf<T>())); Length = length; } public Span<T> AsSpan() { return new Span<T>(Pointer, Length); } public void Dispose() { if (Pointer != null) { Marshal.FreeHGlobal((IntPtr)Pointer); Pointer = null; } } } }
fe90d9c485b1a3db7bd136e58a74cc71cd1c061d
C#
Ttasmiyah/Project_JobHunt
/JobHunt/JobDescriptionforcompany.aspx.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace JobHunt { public partial class JobDescriptionforcompany : System.Web.UI.Page { private String id = ""; protected void Page_Load(object sender, EventArgs e) { if (Session["RUser"] == null) { Response.Redirect("~/Recruiter_login.aspx"); } this.id = Request.QueryString["id"]; } public List<JobHunt.Models.JobDetails> getWhileLoopDataList() { int jobid = Convert.ToInt32(this.id); SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString()); con.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM PostAJob where job_id = " + jobid); cmd.CommandType = System.Data.CommandType.Text; cmd.Connection = con; SqlDataReader reader = cmd.ExecuteReader(); List<JobHunt.Models.JobDetails> data = new List<Models.JobDetails>(); while (reader.Read()) { int cid = reader.GetInt32(1); string Name = reader.GetString(2); string email = reader.GetString(3); string radios = reader.GetString(4); string location = reader.GetString(5); string descrptn = reader.GetString(6); string rqrmnts = reader.GetString(7); JobHunt.Models.JobDetails jobDetails = new Models.JobDetails(); jobDetails.jid = jobid; jobDetails.id = cid; jobDetails.Name = Name; jobDetails.email = email; jobDetails.radios = radios; jobDetails.loation = location; jobDetails.jobdesc = descrptn; jobDetails.reqrmnts = rqrmnts; data.Add(jobDetails); } con.Close(); return data; } } }
e538291eaeaafb4a15ac34a1e9a1038a40726ac2
C#
mmarus-old/BIO-Iris-Recognition
/BIO.Framework/Core/Evaluation/Results/Statistics.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BIO.Framework.Core.Comparator; namespace BIO.Framework.Core.Evaluation.Results { public class Statistics { public class StatisticsSettings { public double newThresh; public bool underThreshAccept; public StatisticsSettings(double thresh, bool underThreshaccepted) { this.newThresh = thresh; this.underThreshAccept = underThreshaccepted; } } public delegate void SettingsChangedEventHandler(StatisticsSettings statisticsSettings); //public delegate void ChangedOrientationEventHandler(object sender, EventArgsStatistics); public event SettingsChangedEventHandler ThreshChanged; public event SettingsChangedEventHandler OrientationChanged; public class Extremes { bool inited = false; public double min = 0.0; public double max = 0.0; public override string ToString() { if (!inited) { return "???"; } return "min:" + String.Format("{0:0.000}", min) + " max:" + String.Format("{0:0.000}", max); } public void update(double val) { if (!inited) { inited = true; min = val; max = val; } if (val < min) min = val; if (val > max) max = val; } } //evaluation object Results results = null; string method = ""; public string Method { get { return method; } } private double trueAcceptance = 0.0; public double TrueAcceptance { get { return trueAcceptance; } set { trueAcceptance = value; } } private double falseAcceptance = 0.0; public double FalseAcceptance { get { return falseAcceptance; } set { falseAcceptance = value; } } private double trueRejection = 0.0; public double TrueRejection { get { return trueRejection; } set { trueRejection = value; } } private double falseRejection = 0.0; public double FalseRejection { get { return falseRejection; } set { falseRejection = value; } } public double FAR { get { return this.FalseAcceptance / (this.FalseAcceptance + this.TrueRejection); } } public double FRR { get { return this.FalseRejection / (this.FalseRejection + this.TrueAcceptance); } } //actual thresh private double thresh = 0.0; public double Thresh { get { return thresh; } set { if (value != thresh) { thresh = value; this.updateBecauseOfThreshChange(); if (ThreshChanged != null) { StatisticsSettings ste = new StatisticsSettings(thresh, this.underThreshAccepted); ThreshChanged(ste); } } } } private bool underThreshAccepted = true; public bool UnderThreshAccepted { get { return underThreshAccepted; } set { if (value != underThreshAccepted) { underThreshAccepted = value; this.updateBecauseOfThreshChange(); if (OrientationChanged != null) { StatisticsSettings ste = new StatisticsSettings(this.thresh, this.underThreshAccepted); OrientationChanged(ste); } } } } private Extremes extremes = new Extremes(); public Extremes GlobalExtremes { get { return extremes; } set { extremes = value; } } private Extremes overlapArea = new Extremes(); public Extremes OverlapAreaExtremes { get { return overlapArea; } set { overlapArea = value; } } private Extremes gExtremes = new Extremes(); public Extremes GenuineExtremes { get { return gExtremes; } set { gExtremes = value; } } private Extremes iExtremes = new Extremes(); public Extremes ImpostorExtremes { get { return iExtremes; } set { iExtremes = value; } } double genuinesCount = 0.0; public double GenuinesCount { get { return genuinesCount; } set { genuinesCount = value; } } double impostorsCount = 0.0; public double ImpostorsCount { get { return impostorsCount; } set { impostorsCount = value; } } double totalResultsCount = 0.0; public double TotalResultsCount { get { return totalResultsCount; } set { totalResultsCount = value; } } public Statistics(string method_, Results results_) { method = method_; results = results_; this.updateAll(); this.autocomputeThresh(); } public void updateAll() { //not work yet this.updateBecauseOfThreshChange(); } private void innerUpdate(List<Result> resultsList) { this.clear(true); foreach (Result r in resultsList) { //if (results.ActiveFiltering != null && !results.ActiveFiltering.pass(r)) { // continue; //} MatchingScore cmpValue = r.getMatchingScore(method); if (!cmpValue.IsValid) { continue; } bool isGeniune = r.isGenuine(); //Console.Write(isGeniune ? "G" : "I"); //Console.Write(cmpValue.ToString()); if (isGeniune) { this.GenuinesCount++; } else { this.ImpostorsCount++; } this.TotalResultsCount++; this.GlobalExtremes.update(cmpValue.Score); if (isGeniune) { this.GenuineExtremes.update(cmpValue.Score); if (this.UnderThreshAccepted) { if (cmpValue.Score < this.Thresh) { this.TrueAcceptance++; } else { this.FalseRejection++; } } else { if (cmpValue.Score > this.Thresh) { this.TrueAcceptance++; } else { this.FalseRejection++; } } } else { this.ImpostorExtremes.update(cmpValue.Score); if (this.UnderThreshAccepted) { if (cmpValue.Score < this.Thresh) { this.FalseAcceptance++; } else { this.TrueRejection++; } } else { if (cmpValue.Score > this.Thresh) { this.FalseAcceptance++; } else { this.TrueRejection++; } } } } if (this.underThreshAccepted) { this.overlapArea.max = this.GenuineExtremes.max; this.overlapArea.min = this.ImpostorExtremes.min; } else { this.overlapArea.max = this.ImpostorExtremes.max; this.overlapArea.min = this.GenuineExtremes.min; } } public void updateBecauseOfThreshChange() { this.innerUpdate(results.getResultsList()); //not work yet } public void clear(bool all) { if (all) { this.TotalResultsCount = 0; this.ImpostorExtremes = new Extremes(); } this.GlobalExtremes = new Extremes(); this.GenuineExtremes = new Extremes(); this.OverlapAreaExtremes = new Extremes(); this.ImpostorsCount = 0; this.GenuinesCount = 0; this.FalseAcceptance = 0; this.FalseRejection = 0; this.TrueAcceptance = 0; this.TrueRejection = 0; } public void autocomputeThresh() { if (this.impostorsCount > 0) { if (this.ImpostorExtremes.min > this.GlobalExtremes.min) { this.UnderThreshAccepted = true; } else { this.UnderThreshAccepted = false; } if (this.underThreshAccepted) { this.Thresh = this.ImpostorExtremes.min; } else { this.Thresh = this.ImpostorExtremes.max; } } } public bool isTrueImpostor(double score) { return this.underThreshAccepted ? score > thresh : score < thresh; } public bool isTrueGenuine(double score) { return this.underThreshAccepted ? score <= thresh : score >= thresh; } public Statistics createCopy() { Statistics s = new Statistics(this.method, this.results); s.underThreshAccepted = this.underThreshAccepted; s.thresh = this.thresh; return s; } } }
c9429bb09b65327dd7fac96ba8cafc8dbeb33548
C#
MaximPeshkur/TRPOProject
/TRPOProject/GetInfoForm.cs
2.515625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TRPOProject { public partial class GetInfoForm : Form { public GetInfoForm() { InitializeComponent(); } private void labelExit_Click(object sender, EventArgs e) { this.Hide(); MainForm mainForm = new MainForm(); mainForm.Show(); } private void labelExit_MouseLeave(object sender, EventArgs e) { labelExit.BackColor = Color.FromArgb(34, 36, 49); } private void labelExit_MouseMove(object sender, MouseEventArgs e) { labelExit.BackColor = Color.Red; } private void textBoxNumber_TextChanged(object sender, EventArgs e) { panelNumber.BackColor = Color.FromArgb(78, 184, 206); textBoxNumber.ForeColor = Color.FromArgb(78, 184, 206); } private void textBoxNumber_Click(object sender, EventArgs e) { textBoxNumber.Clear(); panelNumber.BackColor = Color.FromArgb(78, 184, 206); textBoxNumber.ForeColor = Color.FromArgb(78, 184, 206); } private void buttonRegisration_Click(object sender, EventArgs e) { dataGridView1.Rows.Clear(); string sql = $"select order_date, product_name, ordered_product_count, product_price, order_cost from[order] inner join ordered_product on order_id = ordered_product_order_id inner join product on product_id = ordered_product_product_id where(order_id= {Convert.ToInt32(textBoxNumber.Text)})"; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.AllowUserToAddRows = false; SqlConnection connection = new SqlConnection(LoginForm.get_cs()); connection.Open(); SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader(); List<string[]> data = new List<string[]>(); int count = 0; while (reader.Read()) { data.Add(new string[5]); if (count==0) { data[data.Count - 1][0] = reader[0].ToString(); data[data.Count - 1][4] = reader[4].ToString(); } data[data.Count - 1][1] = reader[1].ToString(); data[data.Count - 1][2] = reader[2].ToString(); data[data.Count - 1][3] = reader[3].ToString(); count++; } reader.Close(); connection.Close(); foreach (var s in data) { dataGridView1.Rows.Add(s); } } private void textBoxNumber_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { buttonRegisration_Click(sender, e); } } } }
cf48afe512e3ef0062882124570534ff567389fa
C#
digitalnelson/LitStore
/LitStore.Server/PubMedController.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.Http; using System.Xml; namespace LightSwitchApplication { public class Art { public string Title { get; set; } } public class PubMedController : ApiController { // GET api/<controller> public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/<controller>/5 public async Task<Art> Get(string id) { HttpClient hc = new HttpClient(); string xml = await hc.GetStringAsync("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=" + id + "&retmode=xml&rettype=abstract"); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); //doc.RemoveChild(doc.DocumentType); var title = doc.SelectSingleNode("PubmedArticleSet/PubmedArticle/MedlineCitation/Article/ArticleTitle"); Art art = new Art(); art.Title = title.InnerText; return art; } // POST api/<controller> public string Post([FromBody]string value) { return "success"; } // PUT api/<controller>/5 public void Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 public void Delete(int id) { } } }
ec078deeac8d4290172b734b3f92188b86a5d930
C#
Illedan/DllCopy
/src/DllCopy/DllCopy/Services/ConfigService.cs
2.75
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using DllCopy.Models; using Newtonsoft.Json; namespace DllCopy.Services { static class ConfigService { private static Task m_saveTask; public static async Task<Config> ReadConfig() { return await Task.Run(() => { try { if(!FileService.FileExists(Const.ConfigFileLocation)) { return new Config(); } var json = FileService.ReadTextFromFile(Const.ConfigFileLocation); FileService.CreateFolder(Const.AppData, "DllCopyBackup"); var path = Path.Combine(Const.BackupLocation, "backup".AppendTimeStamp()); System.IO.File.WriteAllText(path, json); return JsonConvert.DeserializeObject<Config>(json); } catch(Exception e) { return new Config(); } }); } public static async Task SaveConfig(Config config) { if(m_saveTask != null) return; var t = Task.Run(() => { var json = JsonConvert.SerializeObject(config); FileService.WriteToFile(Const.ConfigFileLocation, json); FileService.CreateFolder(Const.AppData, "DllCopyBackup"); var path = Path.Combine(Const.BackupLocation, "backup".AppendTimeStamp()); System.IO.File.WriteAllText(path, json); }); m_saveTask = t; await t; m_saveTask = null; } public static string AppendTimeStamp(this string fileName) { return string.Concat( Path.GetFileNameWithoutExtension(fileName), DateTime.Now.ToString("yyyyMMddHHmmss"), Path.GetExtension(fileName)); } } }
9eea3d52319c1e2d6a61943a11143901912e0f33
C#
shendongnian/download4
/code8/1433904-39335588-126460606-1.cs
2.578125
3
using UnityEngine; public class ScriptA : MonoBehaviour { public ScriptB anyName; void Update() { anyName.DoSomething(); } } ---------- using UnityEngine; public class ScriptB : MonoBehaviour { public void DoSomething() { Debug.Log("Hi there"); } }
041e6a4680eeb70a47d87c385ab4c5f5b926ac9b
C#
alexandrupetrut/CsharpFeatures
/CSharp6.Library/e. Exception Filters - new way/Demo.cs
3.3125
3
using System; namespace CSharp6.Library.e._Exception_Filters___new_way { class Demo { // C# 5 => we define a function with proper name followed by statement block public string GetTime() { return "Current Time - " + DateTime.Now.ToString("hh:mm:ss"); } public void Output() { Console.WriteLine(GetTime()); } // C# 6 => functions & properties in lambda expressions public string GetTheTime() => "Current Time - " + DateTime.Now.ToString("hh:mm:ss"); } }
ce80cf408e5652354daa6aa184f98a419d54e019
C#
SuperBugCompany/politrange.webapi
/src/SuperBug.Politrange.Data/Repositories/SiteRepository.cs
3
3
using System.Collections.Generic; using System.Data.Entity; using System.Linq; using SuperBug.Politrange.Data.Contexts; using SuperBug.Politrange.Models; namespace SuperBug.Politrange.Data.Repositories { public class SiteRepository: ISiteRepository { public IEnumerable<Site> GetAll() { using (var context = new PolitrangeContext()) { return context.Sites.ToList(); } } public Site GetById(int id) { using (var context = new PolitrangeContext()) { return context.Sites.Find(id); } } public Site Add(Site entity) { using (var context = new PolitrangeContext()) { entity = context.Sites.Add(entity); context.SaveChanges(); return entity; } } public bool Update(Site entity) { bool isUpdated = false; using (var context = new PolitrangeContext()) { context.Sites.Attach(entity); context.Entry(entity).State = EntityState.Modified; if (context.SaveChanges() > 0) { isUpdated = true; } } return isUpdated; } public bool Delete(int id) { bool isDeleted = false; using (var context = new PolitrangeContext()) { var site = context.Sites.Find(id); if (site != null) { context.Sites.Remove(site); context.SaveChanges(); isDeleted = true; } } return isDeleted; } } }
b38bd32f2eba90506fa8a26799ed29e3ade542a3
C#
nuraalam/C-Sharp.Three-Layer-Architecture
/Department App/Department App/BLL/DepartmentBLL.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Department_App.DLL.DAO; using Department_App.DLL.Gateway; namespace Department_App.BLL { class DepartmentBLL { DepartmentGatway aDepartmentGatway=new DepartmentGatway(); public string Save(Department aDepartment) { aDepartmentGatway.GetDepartmentList(); foreach (Department bDepartment in aDepartmentGatway.GetDepartmentList()) { if (bDepartment.Name != aDepartment.Name) { if (bDepartment.Code != aDepartment.Code) { aDepartmentGatway.Save(aDepartment); return "data is save"; } else { return "data is not valid"; } } } return "i dont know"; } } }
921facfe7cdb6d8d4bb5a4be25a918bc6c4ac9d4
C#
VPolziukov/FindTheWord
/FindWord/FindWord/DAL/Repository/SentenceRepository.cs
2.671875
3
using System.Collections.Generic; using System.Threading.Tasks; namespace FindWord.DAL.Repository { public class SentenceRepository : GenericRepository<Sentence> { private readonly List<Sentence> _sentence; public SentenceRepository(ContextDB context) : base(context) { } public override async Task<Sentence> GetAsync(params object[] id) { var sentence = await base.GetAsync(id); if (sentence == null) { return null; } return sentence; } //public override async Task<List<Sentence>> GetAll() //{ // return await Task.Run(() => _sentence); //} } }
72f989f4f11892b113ace22e00337b48fdaf4f45
C#
Wiks00/NET.W.2016.01.Lipai.02
/Task3/BitNumberLogic.cs
3.796875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task3 { public static class BitNumberLogic { /// <summary> /// Method inserts first in second number from prefBit to nextBit. /// </summary> /// <param name="firstNumber">the insert number</param> /// <param name="secondNumber">the variable number</param> /// <param name="firstBit">start number of bit</param> /// <param name="lastBit">end number of bit</param> /// <returns>the inserted number</returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static int InsertBinaryNumber(int firstNumber, int secondNumber, int firstBit, int lastBit) { if (firstBit < 0 || firstBit > 30 || lastBit > 30 || lastBit < 0) { throw new ArgumentOutOfRangeException(); } int n = (int)Math.Pow(2, lastBit - firstBit + 1) - 1; secondNumber &= n; secondNumber <<= firstBit; return firstNumber | secondNumber; } } }
6f30822390b016a159c7c870249f139e7e93ed46
C#
mistbiu/learngit
/Homework9/project1/Program.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace project1 { public class Program { public static void Main(string[] args) { OrderService orderService = new OrderService(); OrderDetails details1 = new OrderDetails("1","beats", 2, 1099); OrderDetails details2 = new OrderDetails("2","xiaomi", 1, 1999); OrderDetails details3 = new OrderDetails("3","iphone", 4, 6999); List<OrderDetails> items1 = new List<OrderDetails> { details1, details2 }; List<OrderDetails> items2 = new List<OrderDetails> { details3 }; Order order1 = new Order("100001", "fafa", "13647118626", items1); Order order2 = new Order("100002", "lulu", "13886318833", items2); orderService.AddOrder(order1); orderService.AddOrder(order2); } } }
5be839303f315f87e157160871ace10d8c7731b2
C#
LoveLan1314/LeetCode
/LeetCode/SAOA/0658_FindClosestElements.cs
3.90625
4
using System.Collections.Generic; namespace LeetCode.SAOA { internal sealed class FindClosestElementsSolution { public IList<int> FindClosestElements(int[] arr, int k, int x) { var right = BinarySearch(arr, x); int left = right - 1; while (k-- > 0) { if (left < 0) { right++; } else if (right >= arr.Length) { left--; } else if (x - arr[left] <= arr[right] - x) { left--; } else { right++; } } var result = new List<int>(); for (int i = left + 1; i < right; i++) { result.Add(arr[i]); } return result; } private int BinarySearch(int[] arr, int x) { int low = 0, high = arr.Length - 1; while (low < high) { int mid = low + (high - low) / 2; if (arr[mid] >= x) { high = mid; } else { low = mid + 1; } } return low; } } }
67cdd03216d930de1150d9a81e7bfe0127ff3554
C#
JoonasLeminen/programming-basics
/loop-statements/loop-statements/task-2/Program.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task_2 { class Program { static void Main(string[] args) { Console.WriteLine("Ohjelma laskee N ensimmäistä lukua yhteen."); string userInput = Console.ReadLine(); int number = int.Parse(userInput); int i = 1; int f = 1; int k = 1; if (number < 0) { k = -1; } do { i = i + 1; f = f + i; } while (i < number*k); Console.Write($"Syötit: {number}, Summa: {f*k}"); Console.ReadLine(); } } }
e5b08fd06b428686c3f1ea75cfa050970e9f7fbd
C#
jmocon/MRPS
/ajax/MenuItem.aspx.cs
2.515625
3
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ajax_MenuItem : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*"); HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Methods", "*"); Utility clsUtil = new Utility(); string json = ""; JsonId jsn = new JsonId(); MenuItemModel mdl = new MenuItemModel(); switch (Request.QueryString["f"]) { case ("add"): json = clsUtil.GetJson(Request.InputStream); mdl = JsonConvert.DeserializeObject<MenuItemModel>(json); AddItem(mdl); break; case ("getbyid"): json = clsUtil.GetJson(Request.InputStream); jsn = JsonConvert.DeserializeObject<JsonId>(json); GetById(jsn.Id); break; case ("editSave"): json = clsUtil.GetJson(Request.InputStream); mdl = JsonConvert.DeserializeObject<MenuItemModel>(json); EditSaveItem(mdl); break; case ("delete"): json = clsUtil.GetJson(Request.InputStream); jsn = JsonConvert.DeserializeObject<JsonId>(json); DeleteItem(jsn.Id); break; default: ResponseModel res = new ResponseModel { Success = false, Title = "Application Error", Message = "No function called." }; Response.Write(JsonConvert.SerializeObject(res)); break; } } private void AddItem(MenuItemModel mdl) { ResponseModel res = new ResponseModel(); MenuItem cls = new MenuItem(); if (cls.IsItemExist(mdl.Menu_Id,mdl.Item_Id)) { res.Success = false; res.Message = "Name already exist"; } else { mdl = cls.Add(mdl); res.Success = true; res.Message = "Successfully Added New Item"; res.Model = mdl; } string output = JsonConvert.SerializeObject(res); Response.Write(output); } private void GetById(int id) { ResponseModel res = new ResponseModel(); MenuItem clsItem = new MenuItem(); MenuItemModel mdlItem = clsItem.GetById(id); res.Success = true; res.Message = "Successfully Retrieved Item"; res.Model = mdlItem; string output = JsonConvert.SerializeObject(res); Response.Write(output); } private void EditSaveItem(MenuItemModel mdlItem) { ResponseModel res = new ResponseModel(); MenuItem clsItem = new MenuItem(); if (clsItem.IsItemExist(mdlItem.Menu_Id, mdlItem.Item_Id)) { res.Success = false; res.Message = "Item already exist"; } else { int affected = clsItem.Edit(mdlItem); if (affected > 0) { res.Success = true; res.Message = "Successfully Updated Item"; res.Model = mdlItem; } else { res.Success = false; res.Message = "No Item were Updated."; res.Model = mdlItem; } } string output = JsonConvert.SerializeObject(res); Response.Write(output); } private void DeleteItem(int id) { ResponseModel res = new ResponseModel(); MenuItem clsItem = new MenuItem(); int affected = clsItem.Delete(id); if (affected > 0) { res.Success = true; res.Message = "Item Successfully Deleted"; } else { res.Success = false; res.Message = "No Item were Deleted."; } string output = JsonConvert.SerializeObject(res); Response.Write(output); } }
168b56742799010f630f90d6ee29d801f51d8e8d
C#
Vutov/SoftUni
/CSharp Basics/Homeworks/Loops-Homework/05.MathSum/MathSum.cs
4
4
using System; class MathSum { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int x = int.Parse(Console.ReadLine()); double sum = 1d; ulong factorial = 1u; double rooted = 0d; for (uint i = 1; i <= n; i++) { factorial *= i; rooted = Math.Pow(x, i); sum += (factorial / rooted); } Console.WriteLine("{0:F5}", sum); } } //Write a program that, for a given two integer numbers n and x, //calculates the sum S = 1 + 1!/x + 2!/x2 + … + n!/xn. //Use only one loop. Print the result with 5 digits after the decimal point.
de158e3e609339e8344fbaf84687194632382b22
C#
mnikolovski/CC
/10 Common/CC.Common.Base/Exceptions/EmitBaseException.cs
2.921875
3
using System; namespace CC.Common.Base.Exceptions { /// <summary> /// Represents base exception /// </summary> [Serializable] public abstract class EmitBaseException : Exception, IErrorInfo { private string _mErrorMessage; /// <summary> /// User visible error message /// </summary> private string _mUserVisibleErrorMessage; /// <summary> /// Return combined exception message (ErrorGroup + ErrorCode + Error Message) /// </summary> public override string Message { get { return string.Concat(GetErrorGroupAndCode(), @" ", GetCombinedExceptionMessage()); } } /// <summary> /// In which error group the exception belongs to /// </summary> public abstract string Group { get; } /// <summary> /// What is the error code of the exception /// </summary> public abstract string Code { get; } /// <summary> /// Custom error message /// </summary> public string FaultMessage { get { return _mErrorMessage ?? string.Empty; } protected set { _mErrorMessage = value; } } /// <summary> /// Interface error /// </summary> public string UserVisibleMessage { get { return _mUserVisibleErrorMessage ?? string.Empty; } protected set { _mUserVisibleErrorMessage = value; } } /// <summary> /// Create the custom error message format /// </summary> /// <returns></returns> protected virtual string GetCombinedExceptionMessage() { if (string.IsNullOrEmpty(base.Message)) { return FaultMessage; } string _message; if (FaultMessage.Contains(Environment.NewLine)) { _message = string.Format("{0}Base:{1}{2}Stack:{3}", FaultMessage, base.Message, Environment.NewLine, StackTrace); } else { _message = string.Format("{0}{2}Base:{1}{2}Stack:{3}", FaultMessage, base.Message, Environment.NewLine, StackTrace); } return _message; } /// <summary> /// Return concat. error group + error code /// </summary> /// <returns></returns> public string GetErrorGroupAndCode() { return string.Concat(Group, Code); } /// <summary> /// Returns the message /// </summary> /// <returns></returns> public override string ToString() { return Message; } } }
1347178a938e760d9ee8f94d1bd4474bcebea6d8
C#
Bogdansky/Graduate-work
/Graduate-Work/Business Logic Layer/Helpers/TimeHelper.cs
3.53125
4
using System; using System.Collections.Generic; using System.Linq; using System.Globalization; namespace Business_Logic_Layer.Helpers { public static class TimeHelper { /// <summary> /// Преобразует время формата hh:mm:ss в TimeSpan /// </summary> /// <param name="hhmmss">Строка в формате hh:mm:ss</param> /// <returns>Время = hh+mm+ss</returns> public static TimeSpan ParseTime(string time) { if (time == null) { return default; } var values = time.Split(":"); var valid = values.All(v => int.TryParse(v, NumberStyles.Integer,CultureInfo.InvariantCulture, out int _)); if (values.Length != 3 || !valid) { return default; } var result = TimeSpan.FromHours(int.Parse(values[0])) + TimeSpan.FromMinutes(int.Parse(values[1])) + TimeSpan.FromSeconds(int.Parse(values[2])); return result; } } }
f49f93f00744d774c4bc5c652010934f9d788174
C#
paulmaidmentuk/WhoLivesInThisHouseLib
/WhoLivesInThisHouseTest/TagTest.cs
3.046875
3
using NUnit.Framework; using System; using WhoLivesInThisHouse; namespace WhoLivesInThisHouseTest { [TestFixture()] public class TagTest { [Test()] public void it_should_be_considered_equal_to_another_tag_with_identical_attributes() { Tag tag1 = new Tag("Test Tag"); Tag tag2 = new Tag("Test Tag"); Assert.AreEqual(tag1, tag2); } [Test()] public void it_should_be_possible_to_construct_a_tag() { Tag tag = new Tag("This is a tag"); Assert.AreEqual("This is a tag", tag.Name); } } }
e666617bc06d680ea637ccf75816f0666cd5f03f
C#
Drazuul/itse1430
/labs/Lab1/Itse1430.Maze/Program.cs
3.09375
3
// Jacob Ivey // Lab1 Maze // ITSE 1430 // // Concept for the maze borrowed from Star Wars freighter // MY MAP - https://i.gyazo.com/6ab2e5290089cd389ea02717d9023176.png // ORIGINAL FREIGHTER MAP - https://vignette.wikia.nocookie.net/starwars/images/d/d5/Dynamic-class.png/revision/latest?cb=20080330025657 using System; namespace Itse1430.Maze { class Program { private static int currentDirection; static void Main ( string[] args ) { currentDirection = 2; Console.WriteLine ("You are a starship pilot. You have been given emergency instruction to fire up an unfamiliar freight ship and leave immediately. Start at the ship's ramp and find your way to the cockpit."); Console.WriteLine (""); Ramp (); } enum Command { Quit = 1, MoveForward = 2, MoveBackward = 3, MoveLeft = 4, MoveRight = 5, } enum Direction { North = 0, East = 1, South = 2, West = 3, } static Direction MoveDirection ( Command command ) { switch (command) { case Command.MoveForward: return (Direction)currentDirection; case Command.MoveBackward: return (Direction)((currentDirection + 2 + 4) % 4); case Command.MoveLeft: return (Direction)((currentDirection - 1 + 4) % 4); case Command.MoveRight: return (Direction)((currentDirection + 1 + 4) % 4); default: Console.WriteLine ("You somehow broke it."); break; } return (Direction)currentDirection; } static void DisplayDirection () { Console.WriteLine ("You are facing " + (Direction)currentDirection + "."); } static Command CommandHandler () { while (true) { Console.WriteLine ("What will you do? "); string command = CommandValidation (); switch (command) { case "quit": { if (BoolValidation ("Are you sure you want to quit? ")) return Command.Quit; else continue; } case "move forward": return Command.MoveForward; case "move backward": return Command.MoveBackward; case "move left": return Command.MoveLeft; case "move right": return Command.MoveRight; case "turn left": currentDirection = (currentDirection - 1 + 4) % 4; DisplayDirection (); break; case "turn right": currentDirection = (currentDirection + 1 + 4) % 4; DisplayDirection (); break; case "turn around": currentDirection = (currentDirection + 2 + 4) % 4; DisplayDirection (); break; default: { Console.WriteLine ("Invalid Command. Try again."); continue; } } } } static string CommandValidation () { while (true) { string input = Console.ReadLine (); if (String.IsNullOrEmpty (input)) continue; input = input.Trim (); input = input.ToLower (); return input; } } static bool BoolValidation ( string message ) { while (true) { Console.WriteLine (message); string input = Console.ReadLine (); bool result; if (Boolean.TryParse (input, out result)) return result; Console.WriteLine ("Not a boolean"); } } static void Ramp () { string roomName = "Ramp"; string roomDescription = "Up the ramp is the ship's only point of entry for a pilot. at the top of the ramp, there is a door leading to the rest of the ship."; //string south = "Hallway"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Console.WriteLine ("The ramp has already closed. There's no going back now."); break; case Direction.South: Hallway (); return; case Direction.East: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.West: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; } } } } static void Hallway () { string roomName = "Hallway"; string roomDescription = "This is the hallway. there are three doors. One is the ramp, where you came from. the other two are not marked."; //north = "Ramp"; //east = "Starboard Dorm"; //south = "Garage"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Ramp (); return; case Direction.South: Garage (); return; case Direction.East: StarboardDorm (); return; case Direction.West: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; } } } } static void StarboardDorm () { string roomName = "Starboard Dorm"; string roomDescription = "This is the Starboard Dormitory. This ship is supposed to have a crew. There are three beds and a few closets, but no other doors except for the way you came in. It's a dead end."; //string west = "Hallway"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.West: Hallway (); return; } } } } static void Garage () { string roomName = "Garage"; string roomDescription = "This is the garage. there are a couple of land vehicles in here, covered by tarps. There is a door marked \"Turret Access\", and the hallway leading out to the ramp. "; //string north = "Hallway"; //string west = "Turret Access"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Hallway (); return; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.West: TurretAccess (); return; } } } } static void TurretAccess () { string roomName = "Turret Access"; string roomDescription = "This is a small junction with everywhere to go. Up and down are locked latches, marked with a \'1\' and a \'2\'. " + "Besides that, there is an open way to the main area, a door leading to the Medical Bay, a door leading to the garage, and a door leading to the engine room."; //string north = "Main Hold"; //string west = "Medical Bay"; //string east = "Garage"; //string south = "Engine Room"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: MainHold (); return; case Direction.South: EngineRoom (); return; case Direction.East: Garage (); return; case Direction.West: MedicalBay (); return; } } } } static void EngineRoom () { string roomName = "Engine Room"; string roomDescription = "This is the engine room. it's a room with a big engine in it. dead end."; //string north = "Turret Access"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: TurretAccess (); return; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.West: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; } } } } static void MedicalBay () { string roomName = "Medical Bay"; string roomDescription = "This looks like it used to be a coat closet. it's small, and it has a single bed and a cabinet. dead end."; //string east = "Turret Access"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: TurretAccess (); return; case Direction.West: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; } } } } static void MainHold () { string roomName = "Main Hold"; string roomDescription = "This is the Main Hold, there is a big planning table, some chairs, and a couch. There are two hallways, a door marked \"Storage\", and a door marked \"Turret Access\"."; //string north = "Hallway 3"; //string west = "Hallway 2"; //string east = "Storage"; //string south = "Turret Access"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: HallwayThree (); return; case Direction.South: HallwayTwo (); return; case Direction.East: Storage (); return; case Direction.West: Storage (); return; } } } } static void HallwayTwo () { string roomName = "Hallway 2"; string roomDescription = "This is a hallway. there is an open way to the main area, and two unmarked doors"; //string north = "Port Dorm"; //string west = "Cargo Hold"; //string east = "Main Hold"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: PortDorm (); return; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: MainHold (); return; case Direction.West: CargoHold (); return; } } } } static void CargoHold () { string roomName = "Cargo Hold"; string roomDescription = "This is a big room full of boxes. dead end."; //string east = "Hallway 2"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: HallwayTwo (); return; case Direction.West: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; } } } } static void PortDorm () { string roomName = "Port Dorm"; string roomDescription = "This is the Port Dorm. it has three beds and a few closets. dead end."; //string south = "Hallway 2"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.South: HallwayTwo (); return; case Direction.East: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.West: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; } } } } static void Storage () { string roomName = "Storage"; string roomDescription = "this is a storage closet. you've got some coats, some brooms, cleaning supplies, and that's about it. dead end."; //string west = "Main Hold"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.West: MainHold (); return; } } } } static void HallwayThree () { string roomName = "Hallway 3"; string roomDescription = "this is a hallway. there is an open way to the main hold, and two unmarked doors."; //string north = "Cockpit"; //string east = "Communications"; //string south = "Main Hold"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Cockpit (); return; case Direction.South: MainHold (); return; case Direction.East: Communications (); return; case Direction.West: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; } } } } static void Communications () { string roomName = "Communications"; string roomDescription = "this is the comms room.there are a couple of computers with chairs, some fancy-looking radio equipment, and a mini-fridge. dead end."; //west = hallway 3 Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); DisplayDirection (); while (true) { Command command = CommandHandler (); Direction direction; if (command == Command.Quit) return; else { direction = MoveDirection (command); switch (direction) { case Direction.North: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.South: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.East: Console.WriteLine ("That is a wall. you cant walk into a wall."); break; case Direction.West: HallwayThree (); return; } } } } static void Cockpit () { string roomName = "Cockpit"; string roomDescription = "This is the Cockpit. The Bridge. The Pilot's Station. there are four chairs, one of them clearly a pilot's chair." + " Directly ahead of you is the blackness of space. You sit down and fire up the controls. its lucky you got there in time."; //string south = "Hallway 3"; Console.WriteLine ("------------------------" + roomName + "-----------------------"); Console.WriteLine (roomDescription); Console.WriteLine (""); Console.WriteLine ("YOU WIN. GAME OVER"); return; } } }
12ed5dc7cd37c17d313f2dd4672eaffe80475978
C#
PGsHub/mathnet-numerics
/src/Numerics/Copulas/EllipticalCopula.cs
2.515625
3
 using System; using MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.Random; using MathNet.Numerics; using MathNet.Numerics.Properties; namespace MathNet.Numerics.Copulas { public abstract class EllipticalCopula : Copula { private MatrixNormal _matrixnormal; private IContinuousDistribution _transformDist; protected EllipticalCopula() { } protected EllipticalCopula(IContinuousDistribution transformDist) { _transformDist = transformDist; _transformDist.RandomSource = RandomSource; } public sealed override System.Random RandomSource { protected set { base.RandomSource = value; if (_transformDist != null) _transformDist.RandomSource = value; } } protected void SetTransformDist(IContinuousDistribution transformDist) { _transformDist = transformDist; } public sealed override Matrix<double> Rho { protected set { if (!Copula.IsValidParameterSet(value)) { throw new Copula.InvalidCorrelationMatrixException(); } base.Rho = value; Dimension = Rho.ColumnCount; _matrixnormal = GetMatrixNormal(); } } private MatrixNormal GetMatrixNormal() { var mu = Matrix<double>.Build.Sparse(Dimension, 1); var k = Matrix<double>.Build.Sparse(1, 1, 1.0); return new MatrixNormal(mu, Rho, k, RandomSource); } public override Matrix<double> Sample() { Matrix<double> result = Matrix<double>.Build.Dense(1, Dimension); var mvnSample = _matrixnormal.Sample(); for (var m = 0; m < Dimension; ++m) result[0, m] = _transformDist.CumulativeDistribution(mvnSample[m, 0]); return result; } public static Matrix<double> GetPearsonRho(Matrix<double> rho, CorrelationType correlationType) { Matrix<double> pearsonRho; switch (correlationType) { case CorrelationType.PearsonLinear: pearsonRho = rho; break; case CorrelationType.KendallRank: pearsonRho = EllipticalCopula.ConvertKendallToPearson(rho); break; case CorrelationType.SpearmanRank: pearsonRho = EllipticalCopula.ConvertSpearmanToPearson(rho); break; default: throw new System.ArgumentException(); } return pearsonRho; } public static double ConvertKendallToPearson(double rho) { return Math.Sin(rho * Math.PI / 2); } public static double ConvertSpearmanToPearson(double rho) { return 2 * Math.Sin(rho * Math.PI / 6); } public static Matrix<double> ConvertKendallToPearson(Matrix<double> rho) { Matrix<double> pearsonRho = Matrix<double>.Build.Dense(rho.RowCount, rho.ColumnCount); pearsonRho.SetDiagonal(Vector<double>.Build.Dense(pearsonRho.RowCount,1)); for (int i = 0; i < rho.RowCount; ++i) { for (int j = 0; j < rho.ColumnCount; ++j) { if (i != j) pearsonRho[i, j] = ConvertKendallToPearson(rho[i, j]); } } return pearsonRho; } public static Matrix<double> ConvertSpearmanToPearson(Matrix<double> rho) { Matrix<double> pearsonRho = Matrix<double>.Build.Dense(rho.RowCount, rho.ColumnCount); pearsonRho.SetDiagonal(Vector<double>.Build.Dense(pearsonRho.RowCount, 1)); for (int i = 0; i < rho.RowCount; ++i) { for (int j = 0; j < rho.ColumnCount; ++j) { if (i != j) pearsonRho[i, j] = ConvertSpearmanToPearson(rho[i, j]); } } return pearsonRho; } } }
1368c6de08835a4077632c46d38e1f8b008b40c5
C#
itshivansh/AnalogWatchHackathon
/Hackathon_2/Hackathon_2/Company/Titan.cs
3.171875
3
using Hackathon_2.Models; using System; using System.Collections.Generic; using System.Text; namespace Hackathon_2.Company { /// <summary> /// Titan class inheriting Analog interface /// </summary> # region implementation public class Titan:IAnalog { void IAnalog.MovingHand() { Console.WriteLine("Hour Hand,Minute Hand and Second Hand will be moving "); } void IAnalog.StrapColor() { Console.WriteLine("Black,Brown and Gold colors are available"); } void IAnalog.StrapType() { Console.WriteLine("Only Metal Strap is available"); } void IAnalog.ManufacturingCountry() { Console.WriteLine("Made in Germany"); } void IAnalog.Price_Range() { Console.WriteLine("Price ranges between 1500 to 10000"); } public void Calender_Window() { Console.WriteLine("Calender Window unavailable"); } } #endregion }
feb8215b357a01c2b03cfa007fec73fb5ecf88e5
C#
jangocheng/EApp
/EApp.Mvvm/ViewModelBase.cs
2.875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; namespace EApp.Mvvm { public abstract class ViewModelBase: INotifyPropertyChanged, IDisposable { public string DisplayName { get; protected set; } public event PropertyChangedEventHandler PropertyChanged; public void Dispose() { this.Dispose(true); } protected virtual void Dispose(bool disposing) { } /// <summary> /// Verify that the property name matches a real, // public, instance property on this object. /// </summary> /// <param name="propertyName"></param> /// <returns></returns> [Conditional("DEBUG")] [DebuggerStepThrough] protected void VerifyPropertyName(string propertyName) { // Verify that the property name matches a real, // public, instance property on this object. PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(this)[propertyName]; if (propertyDescriptor == null) { throw new ArgumentException("The specified property doesn't exist in the view model."); } else { if (propertyDescriptor.IsReadOnly) { throw new ArgumentException("The property is read-only."); } } } protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.VerifyPropertyName(propertyName); PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName); this.PropertyChanged(this, e); } } } }
63131765c8e4f60a8a294352d5e551ebecc53ae9
C#
alklokov/PatternsHomework
/Lesson24/IIterator.cs
2.640625
3
namespace Lesson24 { public interface IIterator<out T> { T Current { get; } bool MoveNext(); bool MovePrev(); void Reset(); } }
b7419bb8f68f6371f04ca83994d9b334b647f39c
C#
Thimoderam/Design-Patterns
/DesignPatternsBoekOpdrachten/Week 2/AdapterPattern/TurkeyAdapter.cs
3.09375
3
namespace DesignPatternsBoekOpdrachten.Week2.Hoofdstuk_7 { public class TurkeyAdapter { //Should extend Duck so duck methods can be called aswell. However in this code Duck is not an interface. private readonly Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey = turkey; } public void Quack() { turkey.Gobble(); } public void Fly() { for (var i = 0; i < 5; i++) turkey.Fly(); } } }
f9f0d43fe540041f5117e33c58c44b4f63671c62
C#
LucianoQue/Course_git
/Exec_OO_01_01/Exec_OO_01_01/Program.cs
3.640625
4
using System; using System.Globalization; namespace Exec_OO_01_01 { class Program { static void Main(string[] args) { Pessoas x, y; x = new Pessoas(); y = new Pessoas(); Console.WriteLine("Insira os dados da primeira pessoa:"); Console.WriteLine("Nome Completo"); x.nome = Console.ReadLine(); Console.WriteLine("Salario"); x.salario = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); Console.WriteLine("Insira os dados da segunda pessoa:"); Console.WriteLine("Nome completo"); y.nome = Console.ReadLine(); Console.WriteLine("Salario"); y.salario = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); Console.WriteLine(x.nome + " tem salario = " + x.salario); Console.WriteLine(y.nome + " tem salario = " + y.salario); double media = (x.salario + y.salario) / 2; Console.WriteLine("Salario médio = " + media.ToString("F2",CultureInfo.InvariantCulture)); } } }
05bb4e992590d53169d258d17f2d9ce0d0c6f94c
C#
Gnutz/uni
/semester4/GUI/Lek06/07DataBindingDemos/DataBindingDemos/20_ProcessMonitor/AddPaddingValueConverter.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; namespace ProcessMonitor { public class AddPaddingValueConverter : IValueConverter { public AddPaddingValueConverter() { } public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double d = System.Convert.ToDouble(value); return d + 20; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double d = System.Convert.ToDouble(value); return d - 20; } } }
5b8e284b8cff5b47ea0e60305fdfcbee05aa641d
C#
achakravarty/Jalapeno
/Core/Tossd.Jalapeno.Reporting/ImageCapturer.cs
2.515625
3
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace Tossd.Jalapeno.Reporting { public class ImageCapturer { private readonly string _screenCaptureImagesPath; public ImageCapturer(string screenCaptureImagesPath, int testNumber) { _screenCaptureImagesPath = screenCaptureImagesPath + "_Test " + testNumber; Directory.CreateDirectory(_screenCaptureImagesPath); } public void CaptureScreen(string fileName) { var destinationImagePath = _screenCaptureImagesPath + "\\" + fileName; var screenWidth = Screen.GetBounds(new Point(0, 0)).Width; var screenHeight = Screen.GetBounds(new Point(0, 0)).Height; var screenBitmap = new Bitmap(screenWidth, screenHeight); var screenBitmapGFX = Graphics.FromImage(screenBitmap); screenBitmapGFX.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(screenWidth, screenHeight)); screenBitmap.Save(destinationImagePath, ImageFormat.Png); } } }
66ea0a8fa2fda96cce37a774645ec6489517725d
C#
rihard11/AlgebraCSharp2019
/ConsoleApp1/8.2.1_static_zadaca/Static.cs
3.5625
4
using System; namespace _8._2._1_static_zadaca { internal class Static { // PRIVATE konstruktor onemogućava instanciranje private Static() { } #region STATIC metode public static double Zbroj(double broj1, double broj2) { return broj1 + broj2; } public static double Kub(double broj) { return broj * broj * broj; } public static double UdaljenostTocaka(double x1, double x2, double y1, double y2) { return Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } public static double Fahrenheit(double stupnjevaCelzijusa) { return ((double)9 / 5) * stupnjevaCelzijusa + 32; } #endregion } }
41ef9805ac337849e3e0c3839d22c8a5fff4a2c2
C#
mitim/sps
/SkyPhotoSharing/model/Enlister.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SKYPE4COMLib; using System.Windows.Media; namespace SkyPhotoSharing { class Enlister { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public string Handle { get; protected set; } public string Name { get; protected set; } public Color Color { get; protected set; } public SkypeDelivery Delivery { get; protected set; } public bool IsConnecting { get { return Delivery != null ? true : false; } } private Brush _brush; public Brush Brush { get { return _brush; } } public SkypeDelivery.State ConnectionState { get { return Delivery.ConnectionState; } } public Enlister(User skypeUser) { Handle = skypeUser.Handle; Name = GetDisplayName(skypeUser); Color = NextColor(); _brush = new SolidColorBrush(Color); Delivery = new SkypeDelivery(this); } private static Enlister _owner = null; public static Enlister Owner { get { if (_owner != null) return _owner; _owner = new Enlister(SkypeConnection.Instance.Skype.CurrentUser); _owner.Color = Colors.Blue; return _owner; } } public void Close() { if (!IsConnecting) return; Delivery.PostChatMessage(string.Format(Properties.Resources.CHAT_CLOSE, Owner.Name)); Delivery.Close(); Delivery = null; } public void SendPhoto(Photo photo) { Delivery.Send(photo); Delivery.PostChatMessage(string.Format(Properties.Resources.CHAT_SENT_PHOTO, Owner.Name, photo.FileName)); } public void PostPacket(string packet) { if (SkypeDelivery.IsCommand(packet)) { Delivery.PostCommand(packet); } else { Delivery.PostPacket(packet); } } public static string GetDisplayName(User skypeUser) { if (!string.IsNullOrEmpty(skypeUser.DisplayName)) return skypeUser.DisplayName; else if (!string.IsNullOrEmpty(skypeUser.FullName)) return skypeUser.FullName; else return skypeUser.Handle; } private static readonly Queue<Color> COLOR_TABLE = new Queue<Color>(new[] { Colors.Black, Colors.Red, Colors.Green, Colors.Cyan, Colors.Magenta, Colors.Yellow, Colors.DodgerBlue, Colors.MediumSpringGreen, Colors.Crimson, Colors.Aquamarine, Colors.Purple, Colors.Orange }); private static Color NextColor() { Color r = COLOR_TABLE.Dequeue(); COLOR_TABLE.Enqueue(r); return r; } } }
f37699eb074eada17ab41e6396dce0c957f2a66d
C#
Spoon-Games/LSHGame-2.1
/Assets/LSHGame/Util/Effects/ParticleSystemModifier.cs
2.53125
3
using System; using UnityEngine; namespace LSHGame.Util { [RequireComponent(typeof(ParticleSystem))] public class ParticleSystemModifier : MonoBehaviour { protected ParticleSystem ps; protected virtual void Awake() { ps = GetComponent<ParticleSystem>(); } } [System.Serializable] public class PSCurveMultiplier { public AnimationCurve modifier; public ParticleSystem.MinMaxCurve startCurve; private Action<ParticleSystem.MinMaxCurve> setCurve; internal bool isInitialized => setCurve != null; public void Awake(Action<ParticleSystem.MinMaxCurve> setCurve) { this.setCurve += setCurve; } public void Evaluate(float t) { var curve = new ParticleSystem.MinMaxCurve(); curve.constantMin = modifier.Evaluate(t) * startCurve.constantMin; curve.constantMax = modifier.Evaluate(t) * startCurve.constantMax; curve.mode = startCurve.mode; setCurve.Invoke(curve); } } }
2d51c3a6831ce3ef9b08ac9c3bbd30f28d015995
C#
LeoDFT/designPatterns
/ComandPattern/Dispositivos/Stereo.cs
3.09375
3
using System; namespace ComandPattern.Dispositivos { public class Stereo { public void On() { Console.WriteLine("Turning on the stereo"); } public void Off() { Console.WriteLine("Turning off the stereo"); } public void Cd(string CdName = null) { Console.WriteLine("setting the cd " + CdName); } public void Volume(int predefinedVolume) { Console.WriteLine("Set volume at value " + predefinedVolume); } } }
c0fd988773a1d3288d32234cb7427bc002236b1a
C#
ojari/mslearn
/EventHub/Program.cs
2.78125
3
using Azure.Messaging.EventHubs; using Azure.Messaging.EventHubs.Consumer; using Azure.Messaging.EventHubs.Producer; using System; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EventHub { class Program { private static string connectionString = "Endpoint=sb://ehubns-309.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=IbJ9JZBP75ZbkEsbmGndMC4iTGLMEEDqFA4repdsxtY="; private static string eventHubName = "hubname-19777"; static async Task Main(string[] args) { Console.WriteLine("EventHub exercise"); //await SendAll(); await ReadEvents(); } static async Task SendAll() { await using (var producer = new EventHubProducerClient(connectionString, eventHubName)) { int counter = 1; foreach (string prefix in new string[] { "a", "b", "c", "d" }) { await SendEvent(producer, $"{prefix}_Test_{counter}"); counter++; } } } static async Task SendEvent(EventHubProducerClient client, string message) { EventDataBatch batch = await client.CreateBatchAsync(); batch.TryAdd(new EventData(Encoding.UTF8.GetBytes(message))); await client.SendAsync(batch); } static async Task ReadEvents() { string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName; await using (var consumer = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName)) { using var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(TimeSpan.FromSeconds(45)); await foreach (PartitionEvent ev in consumer.ReadEventsAsync(cancellationSource.Token)) { Console.WriteLine("EVENT = " + Encoding.UTF8.GetString(ev.Data.Body.ToArray())); } } } } }
742403f303ea354817b0661bd842e9d4b7bb05b5
C#
jtneumann/CS4B
/Car RentalBizRulesDataLayer/Data Layer/Entities/Vehicle.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Data_Layer.Interfaces; namespace Data_Layer.Entities { public class Vehicle : IVehicle { public int Id { get; set; } public int TypeId { get; set; } public double BasePricePerKm { get; set; } public double BasePricePerDay { get; set; } public double DayTariff { get; set; } public double KmTariff { get; set; } public string RegistrationNumber { get; set; } public double Meter { get; set; } public Vehicle() { } public Vehicle(IVehicle vehicle) { Id = vehicle.Id; TypeId = vehicle.TypeId; BasePricePerKm = vehicle.BasePricePerKm; BasePricePerDay = vehicle.BasePricePerDay; DayTariff = vehicle.DayTariff; KmTariff = vehicle.KmTariff; RegistrationNumber = vehicle.RegistrationNumber; Meter = vehicle.Meter; } } }
29694b894db6113386e61a8098d2cdc2a26bda27
C#
cppisking/ffrkx
/client/UI/EnumDataViewGridCell.cs
2.71875
3
using FFRKInspector.GameData; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FFRKInspector.UI { public class EnumDataViewGridCell<T> : DataGridViewTextBoxCell, IDataGridViewAutoCompleteSource where T : struct { private AutoCompleteStringCollection mAutoComplete; public EnumDataViewGridCell() { mAutoComplete = new AutoCompleteStringCollection(); string[] values = Enum.GetValues(typeof(T)).Cast<T>().Select(x => x.ToString()).ToArray(); mAutoComplete.AddRange(values); } public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.ComponentModel.TypeConverter valueTypeConverter) { if (formattedValue == null || formattedValue == DBNull.Value) return DBNull.Value; string s = (string)formattedValue; if (s == string.Empty) return DBNull.Value; return Enum.Parse(typeof(T), s, true); } protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { if (value == DBNull.Value || value == null) return ""; string value_str = value.ToString(); T result; if (Enum.TryParse<T>(value_str, true, out result)) return result.ToString(); return value_str; } public AutoCompleteStringCollection AutoCompleteSource { get { return mAutoComplete; } } } public class EnumDataViewGridComboBoxCell<T> : DataGridViewComboBoxCell where T : struct { public EnumDataViewGridComboBoxCell() { string[] values = Enum.GetValues(typeof(T)).Cast<T>().Select(x => x.ToString()).ToArray(); this.DataSource = values; } public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.ComponentModel.TypeConverter valueTypeConverter) { if (formattedValue == null || formattedValue == DBNull.Value) return DBNull.Value; string s = (string)formattedValue; if (s == string.Empty) return DBNull.Value; return Enum.Parse(typeof(T), s, true); } protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { if (value == DBNull.Value || value == null) return ""; string value_str = value.ToString(); T result; if (Enum.TryParse<T>(value_str, true, out result)) return result.ToString(); return value_str; } } }
4e955192152a451953c406ac653f55d53ae1cfcc
C#
firefield2/Magazyn
/Magazyn/Magazyn/Delivery.cs
2.65625
3
using Be.Timvw.Framework.ComponentModel; using System; using System.Collections.Generic; using System.Linq; namespace Magazyn { public class Delivery { private int id; private string name; private string code; private string date; SortableBindingList<ProductOnMove> productsList = new SortableBindingList<ProductOnMove>(); public Delivery() { } public Delivery(int id, string code, string name, string date) { this.id = id; this.name = name; this.date = date; this.code = code; } public int Id { get => id; set => id = value; } public string Name { get => name; set => name = value; } public string Date { get => date; set => date = value; } public string Code { get => code; set => code = value; } public SortableBindingList<ProductOnMove> ProductsList { get => productsList; set => productsList = value; } public Delivery Clone() { return new Delivery(id, code ,name, date); } public List<ProductOnMove> GetDeliveryDetails() { productsList = DataBase.GetInstance.GetDeliveryProducts(code); return productsList.ToList(); } } }
b43166e24fe721fb6a54ccd719c228018760ee50
C#
brettski/EntLibCryptoCli
/EntLibCryptoCli/Service/GenerateKeyService.cs
3
3
using EntLibCryptoCli.Options; using System; using System.IO; using System.Text; namespace EntLibCryptoCli.Service { public static class GenerateKeyService { public static int RunGenerate(GenerateKey GenerateKeyOpts) { // Checks int inError = 0; StringBuilder errMsgText = new StringBuilder(); try { using (FileStream tfs = File.OpenWrite(GenerateKeyOpts.KeyFile)) { } } catch (UnauthorizedAccessException) { inError = 2; errMsgText.Append($"- Unable to open output file, '{GenerateKeyOpts.KeyFile}', for writting\n"); } catch (DirectoryNotFoundException) { inError = 3; errMsgText.Append($"- Directory not found, cannot create output file: '{GenerateKeyOpts.KeyFile}'\n"); } catch (Exception ex) { inError = 9; errMsgText.Append($"- Unknown error encountered:\n{ex.Message}\n"); } if (GenerateKeyOpts.Password.Trim() == string.Empty) { inError = 4; errMsgText.Append($"- Provided password value is empty or contains only whitespace\n"); } if (inError > 0) { Console.Write($"\nThere is a problem with the provided parameters:\n\n{errMsgText.ToString()}\n\n"); return inError; } // Work FileInfo generateFile = new FileInfo(GenerateKeyOpts.KeyFile); bool result = GenerateSecureKey.Generate(generateFile, GenerateKeyOpts.Password); if (!result) { Console.Write($"\nUnable to generate secure key."); return 5; } if (File.Exists(GenerateKeyOpts.KeyFile) && new FileInfo(GenerateKeyOpts.KeyFile).Length > 10) { Console.Write($"\nKey, {GenerateKeyOpts.KeyFile}, created successfully!\n"); return 0; } else { Console.Write($"\nKey, {GenerateKeyOpts.KeyFile}, creation failed!\n"); return -1; } } } }
99dd06870fc88ae41fa20cdde68a72238e12b879
C#
carlkassebaum/LeetCode
/Pairs/Program.cs
3.125
3
using System; namespace Pairs { class Program { static void Main(string[] args) { var solution = new Solution(); var result = solution.Pairs(new string[] { "code", "bug" }); foreach (var key in result.Keys) { Console.WriteLine($"{key}: {result[key]}"); } Console.WriteLine("Hello World!"); } } }
a6bbea17e48141133005f80bd81523909767c417
C#
ShanahanColin/APR-Calc
/Coding-Test/Program.cs
3.46875
3
using System; namespace Coding_Test { class Program { static void Main(string[] args) { int amount = 0; int apr = 249; Console.WriteLine("Enter Credit Limit"); int creditLimit = (int)Convert.ToInt64(Console.ReadLine()); Console.WriteLine("Enter Advance Amount"); int advanceAmount = (int)Convert.ToInt64(Console.ReadLine()); SetUp nums = new SetUp(creditLimit, advanceAmount, amount, apr); amount = (int)nums.EquationForOutput(); Console.WriteLine($"Amount: {amount}"); Console.WriteLine($"APR: {apr}"); //SECOND AMOUNT AND APR var newApr = (apr * .25) + apr; if (advanceAmount <= creditLimit * .5) { Restart(); } else if (advanceAmount -amount < creditLimit * .25) { Console.WriteLine($"Amount: {advanceAmount-amount}"); Console.WriteLine($"APR: {newApr}"); Restart(); }else { Console.WriteLine($"Amount: {amount * .5}"); Console.WriteLine($"APR: {newApr}"); } //THIRD AMOUNT AND APR int newAmount = (int)(advanceAmount - (creditLimit * .25) + amount) - creditLimit; bool endTrue = Convert.ToBoolean(newAmount); if (endTrue) { newApr = (apr * .5) + apr; Console.WriteLine($"Amount: {(advanceAmount - amount) - amount * .5}"); Console.WriteLine($"APR: {newApr}"); Restart(); } //Restart App void Restart() { Console.WriteLine("Restart? (yes or no)"); string res = Console.ReadLine(); string resLower = res.ToLower(); if (resLower == "yes") { Main(args); } else { Environment.Exit(-1); } } } } }
cbdd92603b3b88284352ee04dbd0984e93f9973d
C#
randmfun/3I-VS
/SCD_UVSS/ViewModel/SearchViewModel.cs
2.53125
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Windows; using System.Windows.Input; using SCD_UVSS.Dal; using SCD_UVSS.Dal.DBProviders; using SCD_UVSS.Model; using SCD_UVSS.View; namespace SCD_UVSS.ViewModel { public class SearchViewModel { private readonly DataAccessLayer _dataAccessLayer; public ICommand SearchCommand { get; set; } public SearchViewModel(DataAccessLayer dataAccessLayer) : this() { this._dataAccessLayer = dataAccessLayer; } private SearchViewModel() { this.SearchDataList = new ObservableCollection<SearchDataViewItem>(); this.StartTimeSpanViewModel = new TimeSpanViewModel(); this.EndTimeSpanViewModel = new TimeSpanViewModel(); this.SearchCommand = new RelayCommand(Search); this.StartDateTime = DateTime.Now; this.EndDateTime = DateTime.Now; this.VehicleNumber = ""; } public TimeSpanViewModel StartTimeSpanViewModel { get; set; } public TimeSpanViewModel EndTimeSpanViewModel { get; set; } public string VehicleNumber { get; set; } public DateTime StartDateTime { get; set; } public DateTime EndDateTime { get; set;} public ObservableCollection<SearchDataViewItem> SearchDataList { get; set; } public void Search(object arg) { var startHour = int.Parse(this.StartTimeSpanViewModel.SelectedHour); if(this.StartTimeSpanViewModel.SelectedSession == "PM") { startHour += 12; } var endHour = int.Parse(this.EndTimeSpanViewModel.SelectedHour); if (this.EndTimeSpanViewModel.SelectedSession == "PM") { endHour += 12; } var startDateWithTime = new DateTime(this.StartDateTime.Year, this.StartDateTime.Month, this.StartDateTime.Day, startHour, int.Parse(this.StartTimeSpanViewModel.SelectedMinute), 0); var endDateWithTime = new DateTime(this.EndDateTime.Year, this.EndDateTime.Month, this.EndDateTime.Day, endHour, int.Parse(this.EndTimeSpanViewModel.SelectedMinute), 0); var dalSearchModel = new DbSearchRequestModel() { StaDateTime = startDateWithTime, EnDateTime = endDateWithTime, VehicleNumber = this.VehicleNumber }; var listDbResultModels = this._dataAccessLayer.Search(dalSearchModel); // Update the View this.SearchDataList.Clear(); foreach (var dbSearchResultModel in listDbResultModels) { this.SearchDataList.Add(new SearchDataViewItem(this._dataAccessLayer) { ID = dbSearchResultModel.UniqueId, Date = dbSearchResultModel.EntryDateTime, VehicleNumber = dbSearchResultModel.VehicleNumber }); } } } public class SearchDataViewItem { private string _id; private DateTime _date; private DataAccessLayer dataAccessLayer; public ICommand ShowImage { get; set; } public SearchDataViewItem() { this.ShowImage = new RelayCommand(this.ShowImageCallback); this._id = "1"; this._date = DateTime.Now; } public SearchDataViewItem(DataAccessLayer dataAccessLayer):this() { this.dataAccessLayer = dataAccessLayer; } public string ID { get { return _id; } set { _id = value; } } public DateTime Date { get { return _date; } set { _date = value; } } public string VehicleNumber { get; set; } public void ShowImageCallback(object args) { var camImagesViewWindow = new CameraImagesViewWindow(this.dataAccessLayer, this.ID, this.VehicleNumber); camImagesViewWindow.ShowDialog(); } } }
f07382b9b4e6b879f2b55fefe421d539dff249b5
C#
itaibh/WebEngineSharp
/WebEngineSharp/Tokenizer/States/BeforeAttributeValueState.cs
2.75
3
using System; using System.IO; namespace WebEngineSharp.Tokenizer.States { // 8.2.4.37 http://www.w3.org/TR/html5/syntax.html#before-attribute-value-state public class BeforeAttributeValueState : BaseState { private BeforeAttributeValueState() { } private static BeforeAttributeValueState s_Instance = new BeforeAttributeValueState(); public static BeforeAttributeValueState Instance { get { return s_Instance; } } public AttributeToken Token { get; set; } public override BaseState Process(HtmlTokenizer tokenizer, StreamReader reader) { int c; do { c = Read(reader); } while (IsWhitespace(c)); if (c == '"') { AttributeValueQuotedState.InstanceDoubleQuoted.Token = Token; return AttributeValueQuotedState.InstanceDoubleQuoted; } if (c == '&') { AttributeValueUnquotedState.Instance.Token = Token; AttributeValueUnquotedState.Instance.LastConsumedCharacters.Enqueue((char)c); return AttributeValueUnquotedState.Instance; } if (c == '\'') { AttributeValueQuotedState.InstanceSingleQuoted.Token = Token; return AttributeValueQuotedState.InstanceSingleQuoted; } if (c == 0) { ReportParseError(); Token.AttributeValue += "\uFFFD"; AttributeValueUnquotedState.Instance.Token = Token; return AttributeValueUnquotedState.Instance; } if (c == '>') { ReportParseError(); tokenizer.EmitToken(Token); return DataState.Instance; } if (c == -1) { ReportParseError(); return DataState.Instance; //reconsume... ? } if (c == '<' || c == '=' || c == '`') { ReportParseError(); } Token.AttributeValue += (char)c; AttributeValueUnquotedState.Instance.Token = Token; return AttributeValueUnquotedState.Instance; } } }
cb16565150e74941dbcfcf18347e90491a07dc10
C#
sgkoumassi/AzureDevOpsTrainingCICD
/ConsumingAgetodaysWebService/ConsumingAgetodaysWebService/Default.aspx.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ConsumingAgetodaysWebService { public partial class Default : System.Web.UI.Page { protected void button1_Click(object sender, EventArgs e) { localhost.AgeTodaysWebService age = new localhost.AgeTodaysWebService(); int day = int.Parse(textbox1.Text.ToString()); int month = int.Parse(textbox2.Text.ToString()); int year = int.Parse(textbox3.Text.ToString()); int a = age.converttodaysweb(day, month, year); label1.Text = "Your are currently" + "" + a.ToString() + " " + "Days old"; } } }
e8a5d53aad9c2d70bb0294ddecce7108dcbeb759
C#
lionelherrerobattista/practica_C_sharp
/intro_c_sharp/05_Funciones/5_09_Funciones_utiles/5_9_2_Funciones_mate/Ej_05_09_02_10.cs
3.5625
4
/*(5.9.2.10) Crea un programa que "dibuje" un círculo dentro de un array * de dos dimensiones, usando las ecuaciones * x = xCentro + radio * coseno(ángulo), * y = yCentro + radio * seno(ángulo). Si tu array es de 24x79, * las coordenadas del centro serían (12,40). * Recuerda que el ángulo se debe indicar en radianes * (mira el ejercicio 5.9.1.5 y el 5.9.2.9). */ using System; public class Ejercicio_5_9_2_10 { public static double EnRadianes(double anguloGrados) { double anguloRadianes; //Formula de conversión anguloRadianes = (anguloGrados * (2*Math.PI))/360; return anguloRadianes; } public static void Main() { char[,] circulo = new char [24,79]; int angulo; double anguloRadianes; double x; double y; int radio; int i; int j; //Pido al usuario el radio Console.WriteLine("Ingrese el radio del circulo."); Console.Write("Radio: "); radio = Convert.ToInt32(Console.ReadLine()); //Guardo los * en el array para formar el circulo for(angulo = 0; angulo <= 360; angulo++) { //formula para trabajar en radianes anguloRadianes = EnRadianes(angulo); //Formula para dibujar el circulo x = 12d + radio * Math.Cos(angulo); y = 40d + radio * Math.Sin(angulo); //Redondeo los valores y los paso a int de acuerdo a las //coordenadas resultantes circulo [(int)Math.Round(x),(int)Math.Round(y)] = '*'; } //Dibujo el circulo for(i = 23; i >= 0; i--)//Empiezo desde el valor mayor para 'y' { for(j = 0; j < 79; j++)//Imprimo toda la linea { Console.Write(circulo[i,j]); } Console.WriteLine();//Paso a la siguiente } } }
3db0eaf134858ea8df50b3a4629dcfae233880f5
C#
dlangmeyer/NFLGreats_Dennis
/MainProgram.cs
3
3
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; using System.Linq; namespace ShowBestPlayer { public class Program { private static Excel.Workbook MyBook = null; private static Excel.Application MyApp = null; private static Excel.Worksheet MySheet = null; private static Excel.Range XlRange = null; public int SkipRow; public int AccumPlayerTotals; static void Main(string[] args) { string StartTime = DateTime.Now.ToString(); Console.WriteLine("Simple List - Start time: {0}", StartTime); string Player = null; string Position = null; double PassYards = 0; double RushYards = 0; int Index; SetUpExcel(); //Open EXCEL and spreadsheet int LastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row; List<AccumPlayerTotals> PlayerTotalList = new List<AccumPlayerTotals>(); for (int i = 2; i < LastRow; i++) // Start at row 2 to bypass column headers { Position = XlRange.Cells.Value2[i, 22].ToString(); Player = XlRange.Cells.Value2[i, 2].ToString(); if ((Player != " " && Player != null) && (Position == "QB" || Position == "RB")) // Bypass rows without valid player, position { Index = i; ProcessPlayer(Player, Position, PassYards, RushYards, Index, PlayerTotalList); } } GetLeaders(PlayerTotalList, out IOrderedEnumerable<AccumPlayerTotals> QBLeader, out IOrderedEnumerable<AccumPlayerTotals> RBLeader); //-- close the collection CloseSheet(); } //###################################################################### private static void SetUpExcel() { MyApp = new Excel.Application { Visible = false //suppress the display of the Excel spreadsheet }; string XLS_PATH = "C:\\Users\\Dennis.Langmeyer\\Desktop\\NFL_Small_Set.xlsx"; MyBook = MyApp.Workbooks.Open(XLS_PATH); MySheet = (Excel.Worksheet)MyBook.Sheets["Sheet1"]; XlRange = MySheet.UsedRange; } //###################################################################### private static void ProcessPlayer(string Player, string Position, double PassYards, double RushYards, int Index, List<AccumPlayerTotals> PlayerTotalList) { VerifyYards(out PassYards, out RushYards, Index); if (PlayerTotalList.Count == 0) // List is empty - Insert the first entry { AddEntry(Player, Position, PassYards, RushYards, PlayerTotalList); } else // the list has existing entries { Index = PlayerTotalList.FindIndex(x => x.Player.Contains(Player)); if (Index == -1) // - Player not found in list - insert { AddEntry(Player, Position, PassYards, RushYards, PlayerTotalList); } else // Player found in list - accummulate totals { PlayerTotalList[Index].PassYards += PassYards; PlayerTotalList[Index].RushYards += RushYards; } } } //###################################################################### private static void GetLeaders(List<AccumPlayerTotals> PlayerTotalList, out IOrderedEnumerable<AccumPlayerTotals> QBLeader, out IOrderedEnumerable<AccumPlayerTotals> RBLeader) { //---Sort in descending order to put highest yard total as top row QBLeader = PlayerTotalList.OrderByDescending(x => x.PassYards); RBLeader = PlayerTotalList.OrderByDescending(x => x.RushYards); WriteStats(QBLeader, RBLeader); } //###################################################################### private static void WriteStats(IOrderedEnumerable<AccumPlayerTotals> QBLeader, IOrderedEnumerable<AccumPlayerTotals> RBLeader) { //-- Write the solution Console.WriteLine("Passing Leader " + QBLeader.First().Player + " " + QBLeader.First().PassYards); Console.WriteLine("Rushing Leader " + RBLeader.First().Player + " " + RBLeader.First().RushYards); string endTime = DateTime.Now.ToString(); Console.WriteLine("Simple List - End time: {0}", endTime); Console.ReadKey(); } //###################################################################### private static void CloseSheet() { GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.ReleaseComObject(XlRange); Marshal.ReleaseComObject(MySheet); MyBook.Close(); //-- close the Excel spreadsheet Marshal.ReleaseComObject(MyBook); MyApp.Quit(); //-- close Excel Marshal.ReleaseComObject(MyApp); } //###################################################################### private static void AddEntry(string player, string position, double PassYards, double RushYards, List<AccumPlayerTotals> PlayerTotalList) { AccumPlayerTotals AccumPlayerTotals = new AccumPlayerTotals { Player = player, Position = position, PassYards = PassYards, RushYards = RushYards }; PlayerTotalList.Add(AccumPlayerTotals); } //###################################################################### private static void VerifyYards(out double PassYards, out double RushYards, int i) { string CheckNull = " "; CheckNull = Convert.ToString(XlRange.Cells[i, 11].Value2); if (string.IsNullOrWhiteSpace(CheckNull)) { PassYards = 0; } else { PassYards = XlRange.Cells.Value2[i, 11]; } CheckNull = Convert.ToString(XlRange.Cells[i, 15].Value2); if (string.IsNullOrWhiteSpace(CheckNull)) { RushYards = 0; } else { RushYards = XlRange.Cells.Value2[i, 15]; } CheckNull = Convert.ToString(XlRange.Cells[i, 19].Value2); } } }
1f07e36b8b028bf4ecbff11b5d926229cc5ac632
C#
hylasoft-usa/KeyenceIQSConnector
/KeyenceSimulation/Dto/KeyenceLine.cs
3.109375
3
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace KeyenceSimulation.Dto { public class KeyenceLine { public Collection<KeyenceLineSegment> Segments { get; private set; } public KeyenceLine(string prefix, params string[] segments) : this(BuildSegmentList(prefix, segments)) { } public KeyenceLine(IEnumerable<KeyenceLineSegment> segments) { var segmentList = segments == null ? new List<KeyenceLineSegment>() : segments.ToList(); Segments = new Collection<KeyenceLineSegment>(segmentList); } public override string ToString() { var line = new StringBuilder(); var segmentValues = Segments .Where(seg => seg != null) .Select(seg => seg.Value); line.Append(string.Join("\t", segmentValues)); return line.ToString(); } private static IEnumerable<KeyenceLineSegment> BuildSegmentList(string prefix, IEnumerable<string> segments) { var segmentList = new List<KeyenceLineSegment>(); if (!string.IsNullOrEmpty(prefix)) segmentList.Add(new KeyenceLineSegment(prefix)); if (segments != null) segmentList.AddRange(segments.Select(seg => new KeyenceLineSegment(seg))); return segmentList; } } }
2da8cbe2616b44ae01d156d29996a3e354207d50
C#
gampixi/hackcreative2020
/HackCreativeGame/Assets/Scripts/Simulation/Money.cs
2.671875
3
using Game.Simulation; using System; using UnityEngine; namespace Assets.Scripts.Simulation { public class Money { public float Amount { get; private set; } = 1000; public float CalculateBenefitTax() { var amount = 0f; var benefits = SimulationController.Instance.benefits; foreach (var item in benefits.Get()) { var pricePerHealthy = item.PricePerHealthy * (SimulationController.Instance.statistics.TotalHealthy + SimulationController.Instance.statistics.TotalRecovered); var pricePerSick = item.PricePerKnownSick * SimulationController.Instance.statistics.TotalSymptomatic; amount -= (pricePerHealthy + pricePerSick); } return amount; } public float CalculateWorkFlowTax() { var amount = 0f; foreach (var regions in SimulationController.Instance.regions) { foreach (var population in regions.population) { var positive = population.Settings.TaxPerTurn * (population.population.healthy + population.population.recovered + population.population.asymptomatic); if (population.Settings.kind == FlowGroupKind.Anarchist || population.Settings.kind == FlowGroupKind.Unemployed) { positive *= -1; } var negative = population.Settings.TaxPerTurnSymptomatic * (population.population.symptomatic); amount += positive + negative; } } return amount; } internal void CalculateTax() { Amount += CalculateBenefitTax(); Amount += CalculateWorkFlowTax(); } public float CalculateFutureSpending() { return CalculateBenefitTax() + CalculateWorkFlowTax(); } } }
92f8a57dc2a1a087e49548951858e6c95f329182
C#
chromelyapps/Chromely
/src_5.1/Chromely/Browser/HostTaskRunner.cs
2.921875
3
using System; using System.Threading; using System.Threading.Tasks; namespace Chromely.Browser { /// <summary> /// A Helper class for launching Chromely under a seperate thread / task, this helps with /// cleanup on exit. /// </summary> public class HostTaskRunner { private Task BlazorTask; private CancellationTokenSource BlazorTaskTokenSource; private Action HostBuilderAction; private int Port; /// <summary> Constructor. </summary> /// <param name="action"> The action to run for creating the hostbuilder. </param> /// <param name="port"> The port to monitor. </param> public HostTaskRunner(Action action, int port) { HostBuilderAction = action; Port = port; } /// <summary> start the kestrel server in a background thread. </summary> public void Launch() { BlazorTaskTokenSource = new CancellationTokenSource(); // start the kestrel server in a background thread. BlazorTask = new Task(HostBuilderAction, BlazorTaskTokenSource.Token, TaskCreationOptions.LongRunning); BlazorTask.Start(); // wait untill its up while (ClientUrlHelper.IsPortAvailable(Port)) { Thread.Sleep(1); } } /// <summary> /// Clean up kestrel process if not taken down by OS. This can occur when the app is closed /// from WindowController (frameless). /// </summary> /// <param name="sender"> Source of the event. </param> /// <param name="e"> Event information. </param> public void ProcessExit(object sender, EventArgs e) { Task.Run(() => { WaitHandle.WaitAny(new[] { BlazorTaskTokenSource?.Token.WaitHandle }); }); BlazorTaskTokenSource?.Cancel(); } } }