content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace GroupingSampleListView
{
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
}
| 19.681818 | 82 | 0.725173 | [
"Apache-2.0"
] | 15217711253/xamarin-forms-samples | UserInterface/ListView/Grouping/groupingSampleListView/iOS/Main.cs | 435 | C# |
using System;
namespace mysql.demo.Models
{
public class Actor
{
private DbContext context;
public int ActorId {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public DateTime LastUpdate {get; set;}
}
} | 22.230769 | 46 | 0.619377 | [
"Apache-2.0"
] | bomlinh/mysql.demo | Models/Actor.cs | 289 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using War3Api.Object.Abilities;
using War3Api.Object.Enums;
using War3Net.Build.Object;
using War3Net.Common.Extensions;
namespace War3Api.Object.Abilities
{
public sealed class DreadlordInferno : Ability
{
private readonly Lazy<ObjectProperty<float>> _dataDamage;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataDamageModified;
private readonly Lazy<ObjectProperty<float>> _dataDuration;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataDurationModified;
private readonly Lazy<ObjectProperty<float>> _dataImpactDelay;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataImpactDelayModified;
private readonly Lazy<ObjectProperty<string>> _dataSummonedUnitRaw;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataSummonedUnitModified;
private readonly Lazy<ObjectProperty<Unit>> _dataSummonedUnit;
public DreadlordInferno(): base(1852396865)
{
_dataDamage = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamage, SetDataDamage));
_isDataDamageModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageModified));
_dataDuration = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDuration, SetDataDuration));
_isDataDurationModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDurationModified));
_dataImpactDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataImpactDelay, SetDataImpactDelay));
_isDataImpactDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataImpactDelayModified));
_dataSummonedUnitRaw = new Lazy<ObjectProperty<string>>(() => new ObjectProperty<string>(GetDataSummonedUnitRaw, SetDataSummonedUnitRaw));
_isDataSummonedUnitModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataSummonedUnitModified));
_dataSummonedUnit = new Lazy<ObjectProperty<Unit>>(() => new ObjectProperty<Unit>(GetDataSummonedUnit, SetDataSummonedUnit));
}
public DreadlordInferno(int newId): base(1852396865, newId)
{
_dataDamage = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamage, SetDataDamage));
_isDataDamageModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageModified));
_dataDuration = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDuration, SetDataDuration));
_isDataDurationModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDurationModified));
_dataImpactDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataImpactDelay, SetDataImpactDelay));
_isDataImpactDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataImpactDelayModified));
_dataSummonedUnitRaw = new Lazy<ObjectProperty<string>>(() => new ObjectProperty<string>(GetDataSummonedUnitRaw, SetDataSummonedUnitRaw));
_isDataSummonedUnitModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataSummonedUnitModified));
_dataSummonedUnit = new Lazy<ObjectProperty<Unit>>(() => new ObjectProperty<Unit>(GetDataSummonedUnit, SetDataSummonedUnit));
}
public DreadlordInferno(string newRawcode): base(1852396865, newRawcode)
{
_dataDamage = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamage, SetDataDamage));
_isDataDamageModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageModified));
_dataDuration = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDuration, SetDataDuration));
_isDataDurationModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDurationModified));
_dataImpactDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataImpactDelay, SetDataImpactDelay));
_isDataImpactDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataImpactDelayModified));
_dataSummonedUnitRaw = new Lazy<ObjectProperty<string>>(() => new ObjectProperty<string>(GetDataSummonedUnitRaw, SetDataSummonedUnitRaw));
_isDataSummonedUnitModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataSummonedUnitModified));
_dataSummonedUnit = new Lazy<ObjectProperty<Unit>>(() => new ObjectProperty<Unit>(GetDataSummonedUnit, SetDataSummonedUnit));
}
public DreadlordInferno(ObjectDatabaseBase db): base(1852396865, db)
{
_dataDamage = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamage, SetDataDamage));
_isDataDamageModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageModified));
_dataDuration = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDuration, SetDataDuration));
_isDataDurationModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDurationModified));
_dataImpactDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataImpactDelay, SetDataImpactDelay));
_isDataImpactDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataImpactDelayModified));
_dataSummonedUnitRaw = new Lazy<ObjectProperty<string>>(() => new ObjectProperty<string>(GetDataSummonedUnitRaw, SetDataSummonedUnitRaw));
_isDataSummonedUnitModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataSummonedUnitModified));
_dataSummonedUnit = new Lazy<ObjectProperty<Unit>>(() => new ObjectProperty<Unit>(GetDataSummonedUnit, SetDataSummonedUnit));
}
public DreadlordInferno(int newId, ObjectDatabaseBase db): base(1852396865, newId, db)
{
_dataDamage = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamage, SetDataDamage));
_isDataDamageModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageModified));
_dataDuration = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDuration, SetDataDuration));
_isDataDurationModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDurationModified));
_dataImpactDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataImpactDelay, SetDataImpactDelay));
_isDataImpactDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataImpactDelayModified));
_dataSummonedUnitRaw = new Lazy<ObjectProperty<string>>(() => new ObjectProperty<string>(GetDataSummonedUnitRaw, SetDataSummonedUnitRaw));
_isDataSummonedUnitModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataSummonedUnitModified));
_dataSummonedUnit = new Lazy<ObjectProperty<Unit>>(() => new ObjectProperty<Unit>(GetDataSummonedUnit, SetDataSummonedUnit));
}
public DreadlordInferno(string newRawcode, ObjectDatabaseBase db): base(1852396865, newRawcode, db)
{
_dataDamage = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamage, SetDataDamage));
_isDataDamageModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageModified));
_dataDuration = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDuration, SetDataDuration));
_isDataDurationModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDurationModified));
_dataImpactDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataImpactDelay, SetDataImpactDelay));
_isDataImpactDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataImpactDelayModified));
_dataSummonedUnitRaw = new Lazy<ObjectProperty<string>>(() => new ObjectProperty<string>(GetDataSummonedUnitRaw, SetDataSummonedUnitRaw));
_isDataSummonedUnitModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataSummonedUnitModified));
_dataSummonedUnit = new Lazy<ObjectProperty<Unit>>(() => new ObjectProperty<Unit>(GetDataSummonedUnit, SetDataSummonedUnit));
}
public ObjectProperty<float> DataDamage => _dataDamage.Value;
public ReadOnlyObjectProperty<bool> IsDataDamageModified => _isDataDamageModified.Value;
public ObjectProperty<float> DataDuration => _dataDuration.Value;
public ReadOnlyObjectProperty<bool> IsDataDurationModified => _isDataDurationModified.Value;
public ObjectProperty<float> DataImpactDelay => _dataImpactDelay.Value;
public ReadOnlyObjectProperty<bool> IsDataImpactDelayModified => _isDataImpactDelayModified.Value;
public ObjectProperty<string> DataSummonedUnitRaw => _dataSummonedUnitRaw.Value;
public ReadOnlyObjectProperty<bool> IsDataSummonedUnitModified => _isDataSummonedUnitModified.Value;
public ObjectProperty<Unit> DataSummonedUnit => _dataSummonedUnit.Value;
private float GetDataDamage(int level)
{
return _modifications.GetModification(829319509, level).ValueAsFloat;
}
private void SetDataDamage(int level, float value)
{
_modifications[829319509, level] = new LevelObjectDataModification{Id = 829319509, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 1};
}
private bool GetIsDataDamageModified(int level)
{
return _modifications.ContainsKey(829319509, level);
}
private float GetDataDuration(int level)
{
return _modifications.GetModification(846096725, level).ValueAsFloat;
}
private void SetDataDuration(int level, float value)
{
_modifications[846096725, level] = new LevelObjectDataModification{Id = 846096725, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 2};
}
private bool GetIsDataDurationModified(int level)
{
return _modifications.ContainsKey(846096725, level);
}
private float GetDataImpactDelay(int level)
{
return _modifications.GetModification(862873941, level).ValueAsFloat;
}
private void SetDataImpactDelay(int level, float value)
{
_modifications[862873941, level] = new LevelObjectDataModification{Id = 862873941, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 3};
}
private bool GetIsDataImpactDelayModified(int level)
{
return _modifications.ContainsKey(862873941, level);
}
private string GetDataSummonedUnitRaw(int level)
{
return _modifications.GetModification(879651157, level).ValueAsString;
}
private void SetDataSummonedUnitRaw(int level, string value)
{
_modifications[879651157, level] = new LevelObjectDataModification{Id = 879651157, Type = ObjectDataType.String, Value = value, Level = level};
}
private bool GetIsDataSummonedUnitModified(int level)
{
return _modifications.ContainsKey(879651157, level);
}
private Unit GetDataSummonedUnit(int level)
{
return GetDataSummonedUnitRaw(level).ToUnit(this);
}
private void SetDataSummonedUnit(int level, Unit value)
{
SetDataSummonedUnitRaw(level, value.ToRaw(null, null));
}
}
} | 69.577778 | 168 | 0.721575 | [
"MIT"
] | YakaryBovine/AzerothWarsCSharp | src/War3Api.Object/Generated/1.32.10.17734/Abilities/DreadlordInferno.cs | 12,524 | C# |
namespace MicroLite.Tests.Configuration
{
using System;
using MicroLite.Configuration;
using MicroLite.Dialect;
using MicroLite.Driver;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="SQLiteConfigurationExtensions"/> class.
/// </summary>
public class SQLiteConfigurationExtensionsTests
{
public class WhenCallingForSQLiteConnection_WithConnectionDetails
{
private readonly Mock<IConfigureConnection> mockConfigureConnection = new Mock<IConfigureConnection>();
public WhenCallingForSQLiteConnection_WithConnectionDetails()
{
SQLiteConfigurationExtensions.ForSQLiteConnection(this.mockConfigureConnection.Object, "TestConnection", "Data Source=.", "System.Data.SQLite");
}
[Fact]
public void ForConnectionIsCalledWithTheConnectionNameConnectionStringProviderNameAndAnInstanceOfTheSqlDialectAndDbDriver()
{
this.mockConfigureConnection.Verify(
x => x.ForConnection("TestConnection", "Data Source=.", "System.Data.SQLite", It.IsNotNull<SQLiteDialect>(), It.IsNotNull<SQLiteDbDriver>()),
Times.Once());
}
}
public class WhenCallingForSQLiteConnection_WithConnectionDetails_AndTheConfigureConnectionIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(
() => SQLiteConfigurationExtensions.ForSQLiteConnection(null, "TestConnection", "Data Source=.", "System.Data.SQLite"));
Assert.Equal("configureConnection", exception.ParamName);
}
}
public class WhenCallingForSQLiteConnection_WithNamedConnection
{
private readonly Mock<IConfigureConnection> mockConfigureConnection = new Mock<IConfigureConnection>();
public WhenCallingForSQLiteConnection_WithNamedConnection()
{
SQLiteConfigurationExtensions.ForSQLiteConnection(this.mockConfigureConnection.Object, "TestConnection");
}
[Fact]
public void ForConnectionIsCalledWithAnInstanceOfTheSqlDialectAndDbDriver()
{
this.mockConfigureConnection.Verify(
x => x.ForConnection("TestConnection", It.IsNotNull<SQLiteDialect>(), It.IsNotNull<SQLiteDbDriver>()),
Times.Once());
}
}
public class WhenCallingForSQLiteConnection_WithNamedConnection_AndTheConfigureConnectionIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(
() => SQLiteConfigurationExtensions.ForSQLiteConnection(null, "TestConnection"));
Assert.Equal("configureConnection", exception.ParamName);
}
}
}
} | 41.626667 | 162 | 0.629725 | [
"Apache-2.0"
] | orangesocks/MicroLite | MicroLite.Database.SQLite.Tests/Configuration/SQLiteConfigurationExtensionsTests.cs | 3,050 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// Ported to managed code from c_is2022.c and related iso 2022 dll files from mlang
//
// Abstract:
//
// Managed implementation of ISO 2022 code pages, ported from the implementation in c_is2022.dll
// This code should be kept in sync with the other implementations
// This encoding wraps the basic encodings in code that adds the shift in/out wrapper methods
//
// Notes:
//
// IsAlwaysNormalized ???
// Regarding Normalization for ISO-2022-JP (50220, 50221, 50222), its the same rules as EUCJP
// Forms KC & KD are precluded because of things like halfwidth Katakana that has compatibility mappings
// Form D is precluded because of 0x00a8, which changes to space + dieresis.
//
// Note: I think that IsAlwaysNormalized should probably return true for form C for Japanese 20932 based CPs.
//
// For ISO-2022-KR
// Never normalized, C & D (& therefore KC & KD) are precluded because of Hangul syllables and combined characters.
//
// IsAlwaysNormalized ???
// Regarding Normalization for ISO-2022-CN (50227, 50229) & HZ-GB2312 (52936) I think is similar to the Japanese case.
// Forms KC & KD are precluded because of things like halfwidth Katakana that has compatibility mappings
// Form D is precluded because of 0x00a8, which changes to space + dieresis.
//
// Note: I think that IsAlwaysNormalized should probably return true for form C for Chinese 20936 based CPs.
//
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using System;
using System.Security;
using System.Runtime.CompilerServices;
namespace System.Text
{
/*=================================ISO2022Encoding============================
**
** This is used to support ISO 2022 encodings that use shift/escape sequences.
**
==============================================================================*/
internal sealed class ISO2022Encoding : DBCSCodePageEncoding
{
private const byte SHIFT_OUT = (byte)0x0E;
private const byte SHIFT_IN = (byte)0x0F;
private const byte ESCAPE = 0x1B;
private const byte LEADBYTE_HALFWIDTH = 0x10;
// We have to load the 936 code page tables, so impersonate 936 as our base
// This pretends to be other code pages as far as memory sections are concerned.
internal ISO2022Encoding(int codePage) : base(codePage, s_tableBaseCodePages[codePage % 10])
{ }
private static readonly int[] s_tableBaseCodePages =
{
932, // 50220 ISO-2022-JP, No halfwidth Katakana, convert to full width
932, // 50221 ISO-2022-JP, Use escape sequence for half width Katakana
932, // 50222 ISO-2022-JP, Use shift-in/shift-out for half width Katakana
0,
0,
949, // 50225 ISO-2022-KR, Korean
936, // 52936 HZ-GB2312, 936 might be better source
0, //20936, // 50227 ISO-2022-CN, Note: This is just the same as CP 936 in Everett.
0,
// 50229 is currently unsupported, CP 20000 is currently not built in .nlp file
0, //20000, // 50229 ISO-2022-CN, ModeCNS11643_1
0, //20000, // 50229 ISO-2022-CN, ModeCNS11643_2
0 // ModeASCII
};
internal enum ISO2022Modes
{
ModeHalfwidthKatakana = 0,
ModeJIS0208 = 1,
ModeKR = 5,
ModeHZ = 6,
ModeGB2312 = 7,
ModeCNS11643_1 = 9,
ModeCNS11643_2 = 10,
ModeASCII = 11,
ModeIncompleteEscape = -1,
ModeInvalidEscape = -2,
ModeNOOP = -3
}
// Clean up characters for ISO2022 code pages, etc.
// ISO2022 (50220, 50221, 50222)
// GB-HZ (52936)
protected override bool CleanUpBytes(ref int bytes)
{
switch (CodePage)
{
// 932 based code pages
case 50220:
case 50221:
case 50222:
{
if (bytes >= 0x100)
{
// map extended char (0xfa40-0xfc4b) to a special range
// (ported from mlang)
if (bytes >= 0xfa40 && bytes <= 0xfc4b)
{
if (bytes >= 0xfa40 && bytes <= 0xfa5b)
{
if (bytes <= 0xfa49)
bytes = bytes - 0x0b51;
else if (bytes >= 0xfa4a && bytes <= 0xfa53)
bytes = bytes - 0x072f6;
else if (bytes >= 0xfa54 && bytes <= 0xfa57)
bytes = bytes - 0x0b5b;
else if (bytes == 0xfa58)
bytes = 0x878a;
else if (bytes == 0xfa59)
bytes = 0x8782;
else if (bytes == 0xfa5a)
bytes = 0x8784;
else if (bytes == 0xfa5b)
bytes = 0x879a;
}
else if (bytes >= 0xfa5c && bytes <= 0xfc4b)
{
byte tc = unchecked((byte)bytes);
if (tc < 0x5c)
bytes = bytes - 0x0d5f;
else if (tc >= 0x80 && tc <= 0x9B)
bytes = bytes - 0x0d1d;
else
bytes = bytes - 0x0d1c;
}
}
// Convert 932 code page to 20932 like code page range
// (also ported from mlang)
byte bLead = unchecked((byte)(bytes >> 8));
byte bTrail = unchecked((byte)bytes);
bLead -= ((bLead > (byte)0x9f) ? (byte)0xb1 : (byte)0x71);
bLead = (byte)((bLead << 1) + 1);
if (bTrail > (byte)0x9e)
{
bTrail -= (byte)0x7e;
bLead++;
}
else
{
if (bTrail > (byte)0x7e)
bTrail--;
bTrail -= (byte)0x1f;
}
bytes = ((int)bLead) << 8 | (int)bTrail;
// Don't step out of our allocated lead byte area.
// All DBCS lead and trail bytes should be >= 0x21 and <= 0x7e
// This is commented out because Everett/Mlang had illegal PUA
// mappings to ISO2022 code pages that we're maintaining.
// if ((bytes & 0xFF00) < 0x2100 || (bytes & 0xFF00) > 0x7e00 ||
// (bytes & 0xFF) < 0x21 || (bytes & 0xFF) > 0x7e)
// return false;
}
else
{
// Adjust 1/2 Katakana
if (bytes >= 0xa1 && bytes <= 0xdf)
bytes += (LEADBYTE_HALFWIDTH << 8) - 0x80;
// 0x81-0x9f and 0xe0-0xfc CP 932
// 0x8e and 0xa1-0xfe CP 20932 (we don't use 8e though)
// b0-df is 1/2 Katakana
if (bytes >= 0x81 && (bytes <= 0x9f || (bytes >= 0xe0 && bytes <= 0xfc)))
{
// Don't do lead bytes, we use escape sequences instead.
return false;
}
}
break;
}
case 50225:
{
// For 50225 since we don't rely on lead byte marks, return false and don't add them,
// esp. since we're only a 7 bit code page.
if (bytes >= 0x80 && bytes <= 0xff)
return false;
// Ignore characters out of range (a1-7f)
if (
bytes >= 0x100
&& (
(bytes & 0xff) < 0xa1
|| (bytes & 0xff) == 0xff
|| (bytes & 0xff00) < 0xa100
|| (bytes & 0xff00) == 0xff00
)
)
return false;
// May as well get them into our 7 bit range
bytes &= 0x7f7f;
break;
}
case 52936:
{
// Since we don't rely on lead byte marks for 52936, get rid of them so we
// don't end up with extra weird fffe mappings.
if (bytes >= 0x81 && bytes <= 0xfe)
return false;
break;
}
}
return true;
}
// GetByteCount
public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? baseEncoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative");
Debug.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null");
// Just call GetBytes with null byte* to get count
return GetBytes(chars, count, null, 0, baseEncoder);
}
public override unsafe int GetBytes(
char* chars,
int charCount,
byte* bytes,
int byteCount,
EncoderNLS? baseEncoder
)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null");
Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative");
Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(
EncoderFallback != null,
"[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback"
);
// Fix our encoder
ISO2022Encoder? encoder = (ISO2022Encoder?)baseEncoder;
// Our return value
int iCount = 0;
switch (CodePage)
{
case 50220:
case 50221:
case 50222:
iCount = GetBytesCP5022xJP(chars, charCount, bytes, byteCount, encoder);
break;
case 50225:
iCount = GetBytesCP50225KR(chars, charCount, bytes, byteCount, encoder);
break;
// Everett had 50227 the same as 936
/* case 50227:
iCount = GetBytesCP50227CN( chars, charCount, bytes, byteCount, encoder );
break;
*/
case 52936:
iCount = GetBytesCP52936(chars, charCount, bytes, byteCount, encoder);
break;
}
return iCount;
}
// This is internal and called by something else,
public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null");
Debug.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative");
// Just call getChars with null char* to get count
return GetChars(bytes, count, null, 0, baseDecoder);
}
public override unsafe int GetChars(
byte* bytes,
int byteCount,
char* chars,
int charCount,
DecoderNLS? baseDecoder
)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null");
Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative");
Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative");
// Fix our decoder
ISO2022Decoder? decoder = (ISO2022Decoder?)baseDecoder;
int iCount = 0;
switch (CodePage)
{
case 50220:
case 50221:
case 50222:
iCount = GetCharsCP5022xJP(bytes, byteCount, chars, charCount, decoder);
break;
case 50225:
iCount = GetCharsCP50225KR(bytes, byteCount, chars, charCount, decoder);
break;
// Currently 50227 is the same as 936
// case 50227:
// iCount = GetCharsCP50227CN( bytes, byteCount, chars, charCount, decoder);
// break;
case 52936:
iCount = GetCharsCP52936(bytes, byteCount, chars, charCount, decoder);
break;
default:
Debug.Fail("[ISO2022Encoding.GetChars] had unexpected code page");
break;
}
return iCount;
}
// ISO 2022 Code pages for JP.
// 50220 - No halfwidth Katakana, convert to full width
// 50221 - Use escape sequence for half width Katakana
// 50222 - Use shift-in/shift-out for half width Katakana
//
// These are the JIS code pages, superset of ISO-2022 / ISO-2022-JP-1
// 0E Shift Out (following bytes are Katakana)
// 0F Shift In (back to "normal" behavior)
// 21-7E Byte ranges (1 or 2 bytes)
// <ESC> $ @ To Double Byte 0208 Mode (actually older code page, but subset of 0208)
// <ESC> $ B To Double Byte 0208 Mode (duplicate)
// <ESC> $ ( D To Double Byte 0212 Mode (previously we misinterpreted this)
// <ESC> $ I To half width Katakana
// <ESC> ( J To JIS-Roman
// <ESC> ( H To JIS-Roman (swedish character set)
// <ESC> ( B To ASCII
// <ESC> & @ Alternate lead in to <ESC> $ B so just ignore it.
//
// So in Katakana mode we add 0x8e as a lead byte and use CP 20932 to convert it
// In ASCII mode we just spit out the single byte.
// In Roman mode we should change 0x5c (\) -> Yen sign and 0x7e (~) to Overline, however
// we didn't in mLang, otherwise roman is like ASCII.
// In 0208 double byte mode we have to |= with 0x8080 and use CP 20932 to convert it.
// In 0212 double byte mode we have to |= with 0x8000 and use CP 20932 to convert it.
//
// Note that JIS Shift In/Shift Out is different than the other ISO2022 encodings. For JIS
// Shift out always shifts to half-width Katakana. Chinese encodings use designator sequences
// instead of escape sequences and shift out to the designated sequence or back in to ASCII.
//
// When decoding JIS 0208, MLang used a '*' (0x2a) character in JIS 0208 mode to map the trailing byte
// to halfwidth katakana. I found no description of that behavior, however that block of 0208 is
// undefined, so we maintain that behavior when decoding. We will never generate characters using
// that technique, but the decoder will process them.
//
private unsafe int GetBytesCP5022xJP(
char* chars,
int charCount,
byte* bytes,
int byteCount,
ISO2022Encoder? encoder
)
{
// prepare our helpers
EncodingByteBuffer buffer = new EncodingByteBuffer(
this,
encoder,
bytes,
byteCount,
chars,
charCount
);
// Get our mode
ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Mode
ISO2022Modes shiftInMode = ISO2022Modes.ModeASCII; // Mode that shift in will go back to (only used by CP 50222)
// Check our encoder
if (encoder != null)
{
char charLeftOver = encoder.charLeftOver;
currentMode = encoder.currentMode;
shiftInMode = encoder.shiftInOutMode;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(
char.IsHighSurrogate(charLeftOver),
"[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate"
);
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
}
}
while (buffer.MoreData)
{
// Get our char
char ch = buffer.GetNextChar();
// Get our bytes
ushort iBytes = mapUnicodeToBytes[ch];
StartConvert:
// Check for halfwidth bytes
byte bLeadByte = (byte)(iBytes >> 8);
byte bTrailByte = (byte)(iBytes & 0xff);
if (bLeadByte == LEADBYTE_HALFWIDTH)
{
// Its Halfwidth Katakana
if (CodePage == 50220)
{
// CodePage 50220 doesn't use halfwidth Katakana, convert to fullwidth
// See if its out of range, fallback if so, throws if recursive fallback
if (
bTrailByte < 0x21
|| bTrailByte >= 0x21 + s_HalfToFullWidthKanaTable.Length
)
{
buffer.Fallback(ch);
continue;
}
// Get the full width katakana char to use.
iBytes = unchecked(
(ushort)(s_HalfToFullWidthKanaTable[bTrailByte - 0x21] & 0x7F7F)
);
// May have to do all sorts of fun stuff for mode, go back to start convert
goto StartConvert;
}
// Can use halfwidth Katakana, make sure we're in right mode
// Make sure we're in right mode
if (currentMode != ISO2022Modes.ModeHalfwidthKatakana)
{
// 50222 or 50221, either shift in/out or escape to get to Katakana mode
if (CodePage == 50222)
{
// Shift Out
if (!buffer.AddByte(SHIFT_OUT))
break; // convert out of space, stop
// Don't change modes until after AddByte in case it fails for convert
// We get to shift out to Katakana, make sure we'll go back to the right mode
// (This ends up always being ASCII)
shiftInMode = currentMode;
currentMode = ISO2022Modes.ModeHalfwidthKatakana;
}
else
{
// 50221 does halfwidth katakana by escape sequence
Debug.Assert(
CodePage == 50221,
"[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221"
);
// Add our escape sequence
if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'I')))
break; // convert out of space, stop
currentMode = ISO2022Modes.ModeHalfwidthKatakana;
}
}
// We know we're in Katakana mode now, so add it.
// Go ahead and add the Katakana byte. Our table tail bytes are 0x80 too big.
if (!buffer.AddByte(unchecked((byte)(bTrailByte & 0x7F))))
break; // convert out of space, stop
// Done with this one
continue;
}
else if (bLeadByte != 0)
{
//
// It's a double byte character.
//
// If we're CP 50222 we may have to shift in from Katakana mode first
if (CodePage == 50222 && currentMode == ISO2022Modes.ModeHalfwidthKatakana)
{
// Shift In
if (!buffer.AddByte(SHIFT_IN))
break; // convert out of space, stop
// Need to shift in from katakana. (Still might not be right, but won't be shifted out anyway)
currentMode = shiftInMode;
}
// Make sure we're in the right mode (JIS 0208 or JIS 0212)
// Note: Right now we don't use JIS 0212. Also this table would be wrong
// Its JIS extension 0208
if (currentMode != ISO2022Modes.ModeJIS0208)
{
// Escape sequence, we can fail after this, mode will be correct for convert
if (!buffer.AddByte(ESCAPE, unchecked((byte)'$'), unchecked((byte)'B')))
break; // Convert out of space, stop
currentMode = ISO2022Modes.ModeJIS0208;
}
// Add our double bytes
if (
!buffer.AddByte(unchecked((byte)(bLeadByte)), unchecked((byte)(bTrailByte)))
)
break; // Convert out of space, stop
continue;
}
else if (iBytes != 0 || ch == 0)
{
// Single byte Char
// If we're CP 50222 we may have to shift in from Katakana mode first
if (CodePage == 50222 && currentMode == ISO2022Modes.ModeHalfwidthKatakana)
{
// Shift IN
if (!buffer.AddByte(SHIFT_IN))
break; // convert ran out of room
// Need to shift in from katakana. (Still might not be right, but won't be shifted out anyway)
currentMode = shiftInMode;
}
// Its a single byte character, switch to ASCII if we have to
if (currentMode != ISO2022Modes.ModeASCII)
{
if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'B')))
break; // convert ran out of room
currentMode = ISO2022Modes.ModeASCII;
}
// Add the ASCII char
if (!buffer.AddByte(bTrailByte))
break; // convert had no room left
continue;
}
// Its unknown, do fallback, throws if recursive (knows because we called InternalGetNextChar)
buffer.Fallback(ch);
}
// Switch back to ASCII if MustFlush or no encoder
if (currentMode != ISO2022Modes.ModeASCII && (encoder == null || encoder.MustFlush))
{
// If we're CP 50222 we may have to shift in from Katakana mode first
if (CodePage == 50222 && currentMode == ISO2022Modes.ModeHalfwidthKatakana)
{
// Shift IN, only shift mode if necessary.
if (buffer.AddByte(SHIFT_IN))
// Need to shift in from katakana. (Still might not be right, but won't be shifted out anyway)
currentMode = shiftInMode;
else
// If not successful, convert will maintain state for next time, also
// AddByte will have decremented our char count, however we need it to remain the same
buffer.GetNextChar();
}
// switch back to ASCII to finish neatly
if (
currentMode != ISO2022Modes.ModeASCII
&& (CodePage != 50222 || currentMode != ISO2022Modes.ModeHalfwidthKatakana)
)
{
// only shift if it was successful
if (buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'B')))
currentMode = ISO2022Modes.ModeASCII;
else
// If not successful, convert will maintain state for next time, also
// AddByte will have decremented our char count, however we need it to remain the same
buffer.GetNextChar();
}
}
// Remember our encoder state
if (bytes != null && encoder != null)
{
// This is ASCII if we had to flush
encoder.currentMode = currentMode;
encoder.shiftInOutMode = shiftInMode;
if (!buffer.fallbackBufferHelper.bUsedEncoder)
{
encoder.charLeftOver = (char)0;
}
encoder.m_charsUsed = buffer.CharsUsed;
}
// Return our length
return buffer.Count;
}
// ISO 2022 Code pages for Korean - CP 50225
//
// CP 50225 has Shift In/Shift Out codes, and a single designator sequence that is supposed
// to appear once in the file, at the beginning of a line, before any multibyte code points.
// So we stick the designator at the beginning of the output.
//
// These are the KR code page codes for ISO-2022-KR
// 0E Shift Out (following bytes are double byte)
// 0F Shift In (back to ASCII behavior)
// 21-7E Byte ranges (1 or 2 bytes)
// <ESC> $)C Double byte ISO-2022-KR designator
//
// Note that this encoding is a little different than other encodings. The <esc>$)C sequence
// should only appear once per file. (Actually I saw another spec/rfc that said at the beginning
// of each line, but it shouldn't really matter.)
//
// During decoding Mlang accepted ' ', '\t, and '\n' as their respective characters, even if
// it was in double byte mode. We maintain that behavior, although I couldn't find a reference or
// reason for that behavior. We never generate data using that shortcut.
//
// Also Mlang always assumed KR mode, even if the designator wasn't found yet, so we do that as
// well. So basically we just ignore <ESC>$)C when decoding.
//
private unsafe int GetBytesCP50225KR(
char* chars,
int charCount,
byte* bytes,
int byteCount,
ISO2022Encoder? encoder
)
{
// prepare our helpers
EncodingByteBuffer buffer = new EncodingByteBuffer(
this,
encoder,
bytes,
byteCount,
chars,
charCount
);
// Get our mode
ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Mode
ISO2022Modes shiftOutMode = ISO2022Modes.ModeASCII; // ModeKR if already stamped lead bytes
// Check our encoder
if (encoder != null)
{
// May have leftover stuff
char charLeftOver = encoder.charLeftOver;
currentMode = encoder.currentMode;
shiftOutMode = encoder.shiftInOutMode;
// We may have a l left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(
char.IsHighSurrogate(charLeftOver),
"[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate"
);
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
}
}
while (buffer.MoreData)
{
// Get our data
char ch = buffer.GetNextChar();
// Get our bytes
ushort iBytes = mapUnicodeToBytes[ch];
// Check for double byte bytes
byte bLeadByte = (byte)(iBytes >> 8);
byte bTrailByte = (byte)(iBytes & 0xff);
if (bLeadByte != 0)
{
//
// It's a double byte character.
//
// If we haven't done our Korean designator, then do so, if we have any input
if (shiftOutMode != ISO2022Modes.ModeKR)
{
// Add our code page designator sequence
if (
!buffer.AddByte(
ESCAPE,
unchecked((byte)'$'),
unchecked((byte)')'),
unchecked((byte)'C')
)
)
break; // No room during convert.
shiftOutMode = ISO2022Modes.ModeKR;
}
// May have to switch to ModeKR first
if (currentMode != ISO2022Modes.ModeKR)
{
if (!buffer.AddByte(SHIFT_OUT))
break; // No convert room
currentMode = ISO2022Modes.ModeKR;
}
// Add the bytes
if (!buffer.AddByte(bLeadByte, bTrailByte))
break; // no convert room
continue;
}
else if (iBytes != 0 || ch == 0)
{
// Its a single byte character, switch to ASCII if we have to
if (currentMode != ISO2022Modes.ModeASCII)
{
if (!buffer.AddByte(SHIFT_IN))
break;
currentMode = ISO2022Modes.ModeASCII;
}
// Add the ASCII char
if (!buffer.AddByte(bTrailByte))
break;
continue;
}
// Its unknown, do fallback, throws if recursive (knows because we called InternalGetNextChar)
buffer.Fallback(ch);
}
// Switch back to ASCII if MustFlush or no encoder
if (currentMode != ISO2022Modes.ModeASCII && (encoder == null || encoder.MustFlush))
{
// Get back to ASCII to be safe. Only do it if it success.
if (buffer.AddByte(SHIFT_IN))
currentMode = ISO2022Modes.ModeASCII;
else
// If not successful, convert will maintain state for next time, also
// AddByte will have decremented our char count, however we need it to remain the same
buffer.GetNextChar();
}
// Remember our encoder state
if (bytes != null && encoder != null)
{
// If we didn't use the encoder, then there's no chars left over
if (!buffer.fallbackBufferHelper.bUsedEncoder)
{
encoder.charLeftOver = (char)0;
}
// This is ASCII if we had to flush
encoder.currentMode = currentMode;
// We don't use shift out mode, but if we've flushed we need to reset it so it doesn't
// get output again.
if (!encoder.MustFlush || encoder.charLeftOver != (char)0)
{
// We should be not flushing or converting
Debug.Assert(
!encoder.MustFlush || !encoder.m_throwOnOverflow,
"[ISO2022Encoding.GetBytesCP50225KR]Expected no left over data or not flushing or not converting"
);
encoder.shiftInOutMode = shiftOutMode;
}
else
encoder.shiftInOutMode = ISO2022Modes.ModeASCII;
encoder.m_charsUsed = buffer.CharsUsed;
}
// Return our length
return buffer.Count;
}
// CP52936 is HZ Encoding
// HZ Encoding has 4 shift sequences:
// ~~ '~' (\u7e)
// ~} shift into 1 byte mode,
// ~{ shift into 2 byte GB 2312-80
// ~<NL> Maintain 2 byte mode across new lines (ignore both ~ and <NL> characters)
// (This is for mailers that restrict to 70 or 80 or whatever character lines)
//
// According to comment in mlang, lead & trail byte ranges are described in RFC 1843
// RFC 1843 => valid HZ code range: leading byte 0x21 - 0x77, 2nd byte 0x21 - 0x7e
// Our 936 code points are or'd with 0x8080, so lead byte 0xa1 - 0xf7, trail byte 0xa1 - 0xfe
//
// This encoding is designed for transmission by e-mail and news. No bytes should have high bit set.
// (all bytes <= 0x7f)
private unsafe int GetBytesCP52936(
char* chars,
int charCount,
byte* bytes,
int byteCount,
ISO2022Encoder? encoder
)
{
// prepare our helpers
EncodingByteBuffer buffer = new EncodingByteBuffer(
this,
encoder,
bytes,
byteCount,
chars,
charCount
);
// Mode
ISO2022Modes currentMode = ISO2022Modes.ModeASCII;
// Check our encoder
if (encoder != null)
{
char charLeftOver = encoder.charLeftOver;
currentMode = encoder.currentMode;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(
char.IsHighSurrogate(charLeftOver),
"[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate"
);
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
}
}
while (buffer.MoreData)
{
// Get our char
char ch = buffer.GetNextChar();
// Get our bytes
ushort sChar = mapUnicodeToBytes[ch];
if (sChar == 0 && ch != 0)
{
// Wasn't a legal byte sequence, its a surrogate or fallback
// Throws if recursive (knows because we called InternalGetNextChar)
buffer.Fallback(ch);
// Done with our char, now process fallback
continue;
}
// Check for halfwidth bytes
byte bLeadByte = (byte)(sChar >> 8);
byte bTrailByte = (byte)(sChar & 0xff);
// If its a double byte, it has to fit in the lead byte 0xa1 - 0xf7, trail byte 0xa1 - 0xfe range
// (including the 0x8080 that our codepage or's to the value)
if (
(
bLeadByte != 0
&& (
bLeadByte < 0xa1
|| bLeadByte > 0xf7
|| bTrailByte < 0xa1
|| bTrailByte > 0xfe
)
) || (bLeadByte == 0 && bTrailByte > 0x80 && bTrailByte != 0xff)
)
{
// Illegal character, in 936 code page, but not in HZ subset, get fallback for it
buffer.Fallback(ch);
continue;
}
// sChar is now either ASCII or has an 0x8080 mask
if (bLeadByte != 0)
{
// Its a double byte mode
if (currentMode != ISO2022Modes.ModeHZ)
{
// Need to add the double byte mode marker
if (!buffer.AddByte((byte)'~', (byte)'{', 2))
break; // Stop if no buffer space in convert
currentMode = ISO2022Modes.ModeHZ;
}
// Go ahead and add the 2 bytes
if (
!buffer.AddByte(
unchecked((byte)(bLeadByte & 0x7f)),
unchecked((byte)(bTrailByte & 0x7f))
)
)
break; // Stop if no buffer space in convert
}
else
{
// Its supposed to be ASCII
if (currentMode != ISO2022Modes.ModeASCII)
{
// Need to add the ASCII mode marker
// Will have 1 more byte (or 2 if ~)
if (!buffer.AddByte((byte)'~', (byte)'}', bTrailByte == '~' ? 2 : 1))
break;
currentMode = ISO2022Modes.ModeASCII;
}
// If its a '~' we'll need an extra one
if (bTrailByte == '~')
{
// Need to add the extra ~
if (!buffer.AddByte((byte)'~', 1))
break;
}
// Need to add the character
if (!buffer.AddByte(bTrailByte))
break;
}
}
// Add ASCII shift out if we're at end of decoder
if (currentMode != ISO2022Modes.ModeASCII && (encoder == null || encoder.MustFlush))
{
// Need to add the ASCII mode marker
// Only turn off other mode if this works
if (buffer.AddByte((byte)'~', (byte)'}'))
currentMode = ISO2022Modes.ModeASCII;
else
// If not successful, convert will maintain state for next time, also
// AddByte will have decremented our char count, however we need it to remain the same
buffer.GetNextChar();
}
// Need to remember our mode
if (encoder != null && bytes != null)
{
// This is ASCII if we had to flush
encoder.currentMode = currentMode;
if (!buffer.fallbackBufferHelper.bUsedEncoder)
{
encoder.charLeftOver = (char)0;
}
encoder.m_charsUsed = buffer.CharsUsed;
}
// Return our length
return buffer.Count;
}
private unsafe int GetCharsCP5022xJP(
byte* bytes,
int byteCount,
char* chars,
int charCount,
ISO2022Decoder? decoder
)
{
// Get our info.
EncodingCharBuffer buffer = new EncodingCharBuffer(
this,
decoder,
chars,
charCount,
bytes,
byteCount
);
// No mode information yet
ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Our current Mode
ISO2022Modes shiftInMode = ISO2022Modes.ModeASCII; // Mode that we'll shift in to
byte[] escapeBytes = new byte[4];
int escapeCount = 0;
if (decoder != null)
{
currentMode = decoder.currentMode;
shiftInMode = decoder.shiftInOutMode;
// See if we have leftover decoder buffer to use
// Load our bytesLeftOver
escapeCount = decoder.bytesLeftOverCount;
// Don't want to mess up decoder if we're counting or throw an exception
for (int i = 0; i < escapeCount; i++)
escapeBytes[i] = decoder.bytesLeftOver[i];
}
// Do this until the end
while (buffer.MoreData || escapeCount > 0)
{
byte ch;
if (escapeCount > 0)
{
// Get more escape sequences if necessary
if (escapeBytes[0] == ESCAPE)
{
// Stop if no more input
if (!buffer.MoreData)
{
if (decoder != null && !decoder.MustFlush)
break;
}
else
{
// Add it to the sequence we can check
escapeBytes[escapeCount++] = buffer.GetNextByte();
// We have an escape sequence
ISO2022Modes modeReturn = CheckEscapeSequenceJP(
escapeBytes,
escapeCount
);
if (modeReturn != ISO2022Modes.ModeInvalidEscape)
{
if (modeReturn != ISO2022Modes.ModeIncompleteEscape)
{
// Processed escape correctly
escapeCount = 0;
// We're now this mode
currentMode = shiftInMode = modeReturn;
}
// Either way, continue to get next escape or real byte
continue;
}
}
// If ModeInvalidEscape, or no input & must flush, then fall through to add escape.
}
// Read next escape byte and move them down one.
ch = DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
}
else
{
// Get our next byte
ch = buffer.GetNextByte();
if (ch == ESCAPE)
{
// We'll have an escape sequence, use it if we don't have one buffered already
if (escapeCount == 0)
{
// Start this new escape sequence
escapeBytes[0] = ch;
escapeCount = 1;
continue;
}
// Flush the previous escape sequence, then reuse this escape byte
buffer.AdjustBytes(-1);
}
}
if (ch == SHIFT_OUT)
{
shiftInMode = currentMode;
currentMode = ISO2022Modes.ModeHalfwidthKatakana;
continue;
}
else if (ch == SHIFT_IN)
{
currentMode = shiftInMode;
continue;
}
// Get our full character
ushort iBytes = ch;
bool b2Bytes = false;
if (currentMode == ISO2022Modes.ModeJIS0208)
{
//
// To handle errors, we need to check:
// 1. if trailbyte is there
// 2. if code is valid
//
if (escapeCount > 0)
{
// Let another escape fall through
if (escapeBytes[0] != ESCAPE)
{
// Move them down one & get the next data
iBytes <<= 8;
iBytes |= DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
b2Bytes = true;
}
}
else if (buffer.MoreData)
{
iBytes <<= 8;
iBytes |= buffer.GetNextByte();
b2Bytes = true;
}
else
{
// Not enough input, use decoder if possible
if (decoder == null || decoder.MustFlush)
{
// No decoder, do fallback for this byte
buffer.Fallback(ch);
break;
}
// Stick it in the decoder if we're not counting
if (chars != null)
{
escapeBytes[0] = ch;
escapeCount = 1;
}
break;
}
// MLang treated JIS 0208 '*' lead byte like a single halfwidth katakana
// escape, so use 0x8e00 as katakana lead byte and keep same trail byte.
// 0x2a lead byte range is normally unused in JIS 0208, so shouldn't have
// any weird compatibility issues.
if ((b2Bytes == true) && ((iBytes & 0xff00) == 0x2a00))
{
iBytes = (ushort)(iBytes & 0xff);
iBytes |= (LEADBYTE_HALFWIDTH << 8); // Put us in the halfwidth katakana range
}
}
else if (iBytes >= 0xA1 && iBytes <= 0xDF)
{
// Everett accidentally mapped Katakana like shift-jis (932),
// even though this is a 7 bit code page. We keep that mapping
iBytes |= (LEADBYTE_HALFWIDTH << 8); // Map to halfwidth katakana range
iBytes &= 0xff7f; // remove extra 0x80
}
else if (currentMode == ISO2022Modes.ModeHalfwidthKatakana)
{
// Add 0x10 lead byte that our encoding expects for Katakana:
iBytes |= (LEADBYTE_HALFWIDTH << 8);
}
// We have an iBytes to try to convert.
char c = mapBytesToUnicode[iBytes];
// See if it was unknown
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
// Have to do fallback
if (b2Bytes)
{
if (!buffer.Fallback((byte)(iBytes >> 8), (byte)iBytes))
break;
}
else
{
if (!buffer.Fallback(ch))
break;
}
}
else
{
// If we were JIS 0208, then we consumed an extra byte
if (!buffer.AddChar(c, b2Bytes ? 2 : 1))
break;
}
}
// Make sure our decoder state matches our mode, if not counting
if (chars != null && decoder != null)
{
// Remember it if we don't flush
if (!decoder.MustFlush || escapeCount != 0)
{
// Either not flushing or had state (from convert)
Debug.Assert(
!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP5022xJP]Expected no state or not converting or not flushing"
);
decoder.currentMode = currentMode;
decoder.shiftInOutMode = shiftInMode;
// Remember escape buffer
decoder.bytesLeftOverCount = escapeCount;
decoder.bytesLeftOver = escapeBytes;
}
else
{
// We flush, clear buffer
decoder.currentMode = ISO2022Modes.ModeASCII;
decoder.shiftInOutMode = ISO2022Modes.ModeASCII;
decoder.bytesLeftOverCount = 0;
// Slightly different if counting/not counting
}
decoder.m_bytesUsed = buffer.BytesUsed;
}
// Return # of characters we found
return buffer.Count;
}
// We know we have an escape sequence, so check it starting with the byte after the escape
private ISO2022Modes CheckEscapeSequenceJP(byte[] bytes, int escapeCount)
{
// Have an escape sequence
if (bytes[0] != ESCAPE)
return ISO2022Modes.ModeInvalidEscape;
if (escapeCount < 3)
return ISO2022Modes.ModeIncompleteEscape;
if (bytes[1] == '(')
{
if (bytes[2] == 'B') // <esc>(B
{
return ISO2022Modes.ModeASCII;
}
else if (bytes[2] == 'H') // <esc>(H
{
// Actually this is supposed to be Swedish
// We treat it like ASCII though.
return ISO2022Modes.ModeASCII;
}
else if (bytes[2] == 'J') // <esc>(J
{
// Actually this is supposed to be Roman
// 2 characters are different, but historically we treat it as ascii
return ISO2022Modes.ModeASCII;
}
else if (bytes[2] == 'I') // <esc>(I
{
return ISO2022Modes.ModeHalfwidthKatakana;
}
}
else if (bytes[1] == '$')
{
if (
bytes[2] == '@'
|| // <esc>$@
bytes[2] == 'B'
) // <esc>$B
{
return ISO2022Modes.ModeJIS0208;
}
else
{
// Looking for <esc>$(D
if (escapeCount < 4)
return ISO2022Modes.ModeIncompleteEscape;
if (bytes[2] == '(' && bytes[3] == 'D') // <esc>$(D
{
// Mlang treated 0208 like 0212 even though that's wrong
return ISO2022Modes.ModeJIS0208;
}
}
}
else if (bytes[1] == '&')
{
if (bytes[2] == '@') // <esc>&@
{
// Ignore ESC & @ (prefix to <esc>$B)
return ISO2022Modes.ModeNOOP;
}
}
// If we get here we fell through and have an invalid/unknown escape sequence
return ISO2022Modes.ModeInvalidEscape;
}
private byte DecrementEscapeBytes(ref byte[] bytes, ref int count)
{
Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
// Decrement our count
count--;
// Remember the first one
byte returnValue = bytes[0];
// Move them down one.
for (int i = 0; i < count; i++)
{
bytes[i] = bytes[i + 1];
}
// Clear out the last byte
bytes[count] = 0;
// Return the old 1st byte
return returnValue;
}
// Note that in DBCS mode mlang passed through ' ', '\t' and '\n' as SBCS characters
// probably to allow mailer formatting without too much extra work.
private unsafe int GetCharsCP50225KR(
byte* bytes,
int byteCount,
char* chars,
int charCount,
ISO2022Decoder? decoder
)
{
// Get our info.
EncodingCharBuffer buffer = new EncodingCharBuffer(
this,
decoder,
chars,
charCount,
bytes,
byteCount
);
// No mode information yet
ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Our current Mode
byte[] escapeBytes = new byte[4];
int escapeCount = 0;
if (decoder != null)
{
currentMode = decoder.currentMode;
// See if we have leftover decoder buffer to use
// Load our bytesLeftOver
escapeCount = decoder.bytesLeftOverCount;
// Don't want to mess up decoder if we're counting or throw an exception
for (int i = 0; i < escapeCount; i++)
escapeBytes[i] = decoder.bytesLeftOver[i];
}
// Do this until the end, just do '?' replacement because we don't have fallbacks for decodings.
while (buffer.MoreData || escapeCount > 0)
{
byte ch;
if (escapeCount > 0)
{
// Get more escape sequences if necessary
if (escapeBytes[0] == ESCAPE)
{
// Stop if no more input
if (!buffer.MoreData)
{
if (decoder != null && !decoder.MustFlush)
break;
}
else
{
// Add it to the sequence we can check
escapeBytes[escapeCount++] = buffer.GetNextByte();
// We have an escape sequence
ISO2022Modes modeReturn = CheckEscapeSequenceKR(
escapeBytes,
escapeCount
);
if (modeReturn != ISO2022Modes.ModeInvalidEscape)
{
if (modeReturn != ISO2022Modes.ModeIncompleteEscape)
{
// Processed escape correctly, no effect (we know about KR mode)
escapeCount = 0;
}
// Either way, continue to get next escape or real byte
continue;
}
}
// If ModeInvalidEscape, or no input & must flush, then fall through to add escape.
}
// Still have something left over in escape buffer
// Get it and move them down one
ch = DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
}
else
{
// Get our next byte
ch = buffer.GetNextByte();
if (ch == ESCAPE)
{
// We'll have an escape sequence, use it if we don't have one buffered already
if (escapeCount == 0)
{
// Start this new escape sequence
escapeBytes[0] = ch;
escapeCount = 1;
continue;
}
// Flush previous escape sequence, then reuse this escape byte
buffer.AdjustBytes(-1);
}
}
if (ch == SHIFT_OUT)
{
currentMode = ISO2022Modes.ModeKR;
continue;
}
else if (ch == SHIFT_IN)
{
currentMode = ISO2022Modes.ModeASCII;
continue;
}
// Get our full character
ushort iBytes = ch;
bool b2Bytes = false;
// MLANG was passing through ' ', '\t' and '\n', so we do so as well, but I don't see that in the RFC.
if (currentMode == ISO2022Modes.ModeKR && ch != ' ' && ch != '\t' && ch != '\n')
{
//
// To handle errors, we need to check:
// 1. if trailbyte is there
// 2. if code is valid
//
if (escapeCount > 0)
{
// Let another escape fall through
if (escapeBytes[0] != ESCAPE)
{
// Move them down one & get the next data
iBytes <<= 8;
iBytes |= DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
b2Bytes = true;
}
}
else if (buffer.MoreData)
{
iBytes <<= 8;
iBytes |= buffer.GetNextByte();
b2Bytes = true;
}
else
{
// Not enough input, use decoder if possible
if (decoder == null || decoder.MustFlush)
{
// No decoder, do fallback for lonely 1st byte
buffer.Fallback(ch);
break;
}
// Stick it in the decoder if we're not counting
if (chars != null)
{
escapeBytes[0] = ch;
escapeCount = 1;
}
break;
}
}
// We have a iBytes to try to convert.
char c = mapBytesToUnicode[iBytes];
// See if it was unknown
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
// Have to do fallback
if (b2Bytes)
{
if (!buffer.Fallback((byte)(iBytes >> 8), (byte)iBytes))
break;
}
else
{
if (!buffer.Fallback(ch))
break;
}
}
else
{
if (!buffer.AddChar(c, b2Bytes ? 2 : 1))
break;
}
}
// Make sure our decoder state matches our mode, if not counting
if (chars != null && decoder != null)
{
// Remember it if we don't flush
if (!decoder.MustFlush || escapeCount != 0)
{
// Either not flushing or had state (from convert)
Debug.Assert(
!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP50225KR]Expected no state or not converting or not flushing"
);
decoder.currentMode = currentMode;
// Remember escape buffer
decoder.bytesLeftOverCount = escapeCount;
decoder.bytesLeftOver = escapeBytes;
}
else
{
// We flush, clear buffer
decoder.currentMode = ISO2022Modes.ModeASCII;
decoder.shiftInOutMode = ISO2022Modes.ModeASCII;
decoder.bytesLeftOverCount = 0;
}
decoder.m_bytesUsed = buffer.BytesUsed;
}
// Return # of characters we found
return buffer.Count;
}
// We know we have an escape sequence, so check it starting with the byte after the escape
private ISO2022Modes CheckEscapeSequenceKR(byte[] bytes, int escapeCount)
{
// Have an escape sequence
if (bytes[0] != ESCAPE)
return ISO2022Modes.ModeInvalidEscape;
if (escapeCount < 4)
return ISO2022Modes.ModeIncompleteEscape;
if (bytes[1] == '$' && bytes[2] == ')' && bytes[3] == 'C') // <esc>$)C
return ISO2022Modes.ModeKR;
// If we get here we fell through and have an invalid/unknown escape sequence
return ISO2022Modes.ModeInvalidEscape;
}
// CP52936 is HZ Encoding
// HZ Encoding has 4 shift sequences:
// ~~ '~' (\u7e)
// ~} shift into 1 byte mode,
// ~{ shift into 2 byte GB 2312-80
// ~<NL> Maintain 2 byte mode across new lines (ignore both ~ and <NL> characters)
// (This is for mailers that restrict to 70 or 80 or whatever character lines)
//
// According to comment in mlang, lead & trail byte ranges are described in RFC 1843
// RFC 1843 => valid HZ code range: leading byte 0x21 - 0x77, 2nd byte 0x21 - 0x7e
// Our 936 code points are or'd with 0x8080, so lead byte 0xa1 - 0xf7, trail byte 0xa1 - 0xfe
//
// This encoding is designed for transmission by e-mail and news. No bytes should have high bit set.
// (all bytes <= 0x7f)
private unsafe int GetCharsCP52936(
byte* bytes,
int byteCount,
char* chars,
int charCount,
ISO2022Decoder? decoder
)
{
Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetCharsCP52936]count >=0");
Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null");
// Get our info.
EncodingCharBuffer buffer = new EncodingCharBuffer(
this,
decoder,
chars,
charCount,
bytes,
byteCount
);
// No mode information yet
ISO2022Modes currentMode = ISO2022Modes.ModeASCII;
int byteLeftOver = -1;
bool bUsedDecoder = false;
if (decoder != null)
{
currentMode = decoder.currentMode;
// See if we have leftover decoder buffer to use
// Don't want to mess up decoder if we're counting or throw an exception
if (decoder.bytesLeftOverCount != 0)
{
// Load our bytesLeftOver
byteLeftOver = decoder.bytesLeftOver[0];
}
}
// Do this until the end, just do '?' replacement because we don't have fallbacks for decodings.
while (buffer.MoreData || byteLeftOver >= 0)
{
byte ch;
// May have a left over byte
if (byteLeftOver >= 0)
{
ch = (byte)byteLeftOver;
byteLeftOver = -1;
}
else
{
ch = buffer.GetNextByte();
}
// We're in escape mode
if (ch == '~')
{
// Next char is type of switch
if (!buffer.MoreData)
{
// We don't have anything left, it'll be in decoder or a ?
// don't fail if we are allowing overflows
if (decoder == null || decoder.MustFlush)
{
// We'll be a '?'
buffer.Fallback(ch);
// break if we fail & break if we don't (because !MoreData)
// Add succeeded, continue
break;
}
// Stick it in decoder
decoder.ClearMustFlush();
if (chars != null)
{
decoder.bytesLeftOverCount = 1;
decoder.bytesLeftOver[0] = (byte)'~';
bUsedDecoder = true;
}
break;
}
// What type is it?, get 2nd byte
ch = buffer.GetNextByte();
if (ch == '~' && currentMode == ISO2022Modes.ModeASCII)
{
// Its just a ~~ replacement for ~, add it
if (!buffer.AddChar((char)ch, 2))
// Add failed, break for converting
break;
// Add succeeded, continue
continue;
}
else if (ch == '{')
{
// Switching to Double Byte mode
currentMode = ISO2022Modes.ModeHZ;
continue;
}
else if (ch == '}')
{
// Switching to ASCII mode
currentMode = ISO2022Modes.ModeASCII;
continue;
}
else if (ch == '\n')
{
// Ignore ~\n sequence
continue;
}
else
{
// Unknown escape, back up and try the '~' as a "normal" byte or lead byte
buffer.AdjustBytes(-1);
ch = (byte)'~';
}
}
// go ahead and add our data
if (currentMode != ISO2022Modes.ModeASCII)
{
// Should be ModeHZ
Debug.Assert(
currentMode == ISO2022Modes.ModeHZ,
"[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ"
);
char cm;
// Everett allowed characters < 0x20 to be passed as if they were ASCII
if (ch < 0x20)
{
// Emit it as ASCII
goto STOREASCII;
}
// Its multibyte, should have another byte
if (!buffer.MoreData)
{
// No bytes left
// don't fail if we are allowing overflows
if (decoder == null || decoder.MustFlush)
{
// Not enough bytes, fallback lead byte
buffer.Fallback(ch);
// Break if we fail & break because !MoreData
break;
}
decoder.ClearMustFlush();
// Stick it in decoder
if (chars != null)
{
decoder.bytesLeftOverCount = 1;
decoder.bytesLeftOver[0] = ch;
bUsedDecoder = true;
}
break;
}
// Everett uses space as an escape character for single SBCS bytes
byte ch2 = buffer.GetNextByte();
ushort iBytes = (ushort)(ch << 8 | ch2);
if (ch == ' ' && ch2 != 0)
{
// Get next char and treat it like ASCII (Everett treated space like an escape
// allowing the next char to be just ascii)
cm = (char)ch2;
goto STOREMULTIBYTE;
}
// Bytes should be in range: lead byte 0x21-0x77, trail byte: 0x21 - 0x7e
if (
(ch < 0x21 || ch > 0x77 || ch2 < 0x21 || ch2 > 0x7e)
&&
// Everett allowed high bit mappings for same characters (but only if both bits set)
(ch < 0xa1 || ch > 0xf7 || ch2 < 0xa1 || ch2 > 0xfe)
)
{
// For some reason Everett allowed XX20 to become unicode 3000... (ideo sp)
if (ch2 == 0x20 && 0x21 <= ch && ch <= 0x7d)
{
iBytes = 0x2121;
goto MULTIBYTE;
}
// Illegal char, use fallback. If lead byte is 0 have to do it special and do it first
if (!buffer.Fallback((byte)(iBytes >> 8), (byte)(iBytes)))
break;
continue;
}
MULTIBYTE:
iBytes |= 0x8080;
// Look up the multibyte char to stick it in our data
// We have a iBytes to try to convert.
cm = mapBytesToUnicode[iBytes];
STOREMULTIBYTE:
// See if it was unknown
if (cm == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
// Fall back the unknown stuff
if (!buffer.Fallback((byte)(iBytes >> 8), (byte)(iBytes)))
break;
continue;
}
if (!buffer.AddChar(cm, 2))
break; // convert ran out of buffer, stop
continue;
}
// Just ASCII
// We allow some chars > 7f because Everett did, so we have to look them up.
STOREASCII:
char c = mapBytesToUnicode[ch];
// Check if it was unknown
if ((c == UNKNOWN_CHAR_FLAG || c == 0) && (ch != 0))
{
// fallback the unknown bytes
if (!buffer.Fallback((byte)ch))
break;
continue;
}
// Go ahead and add our ASCII character
if (!buffer.AddChar(c))
break; // convert ran out of buffer, stop
}
// Need to remember our state, IF we're not counting
if (chars != null && decoder != null)
{
if (!bUsedDecoder)
{
// If we didn't use it, clear the byte left over
decoder.bytesLeftOverCount = 0;
}
if (decoder.MustFlush && decoder.bytesLeftOverCount == 0)
{
decoder.currentMode = ISO2022Modes.ModeASCII;
}
else
{
// Either not flushing or had state (from convert)
Debug.Assert(
!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP52936]Expected no state or not converting or not flushing"
);
decoder.currentMode = currentMode;
}
decoder.m_bytesUsed = buffer.BytesUsed;
}
// Return # of characters we found
return buffer.Count;
}
// Note: These all end up with 1/2 bytes of average byte count, so unless we're 1 we're always
// charCount/2 bytes too big.
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(
nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum
);
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// Start with just generic DBCS values (sort of).
int perChar = 2;
int extraStart = 0;
int extraEnd = 0;
switch (CodePage)
{
case 50220:
case 50221:
// 2 bytes per char + 3 bytes switch to JIS 0208 or 1 byte + 3 bytes switch to 1 byte CP
perChar = 5; // 5 max (4.5 average)
extraEnd = 3; // 3 bytes to shift back to ASCII
break;
case 50222:
// 2 bytes per char + 3 bytes switch to JIS 0208 or 1 byte + 3 bytes switch to 1 byte CP
perChar = 5; // 5 max (4.5 average)
extraEnd = 4; // 1 byte to shift from Katakana -> DBCS, 3 bytes to shift back to ASCII from DBCS
break;
case 50225:
// 2 bytes per char + 1 byte SO, or 1 byte per char + 1 byte SI.
perChar = 3; // 3 max, (2.5 average)
extraStart = 4; // EUC-KR marker appears at beginning of file.
extraEnd = 1; // 1 byte to shift back to ascii if necessary.
break;
case 52936:
// 2 bytes per char + 2 byte shift, or 1 byte + 1 byte shift
// Worst case: left over surrogate with no low surrogate is extra ?, could have to switch to ASCII, then could have HZ and flush to ASCII mode
perChar = 4; // 4 max, (3.5 average if every other char is HZ/ASCII)
extraEnd = 2; // 2 if we have to shift back to ASCII
break;
}
// Return our surrogate and End plus perChar for each char.
byteCount *= perChar;
byteCount += extraStart + extraEnd;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(
nameof(charCount),
SR.ArgumentOutOfRange_GetByteCountOverflow
);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(
nameof(byteCount),
SR.ArgumentOutOfRange_NeedNonNegNum
);
int perChar = 1;
int extraDecoder = 1;
switch (CodePage)
{
case 50220:
case 50221:
case 50222:
case 50225:
perChar = 1; // Worst case all ASCII
extraDecoder = 3; // Could have left over 3 chars of 4 char escape sequence, that all become ?
break;
case 52936:
perChar = 1; // Worst case all ASCII
extraDecoder = 1; // sequences are 2 chars, so if next one is illegal, then previous 1 could be ?
break;
}
// Figure out our length, perchar * char + whatever extra our decoder could do to us.
long charCount = ((long)byteCount * perChar) + extraDecoder;
// Just in case we have to fall back unknown ones.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(
nameof(byteCount),
SR.ArgumentOutOfRange_GetCharCountOverflow
);
return (int)charCount;
}
public override Encoder GetEncoder()
{
return new ISO2022Encoder(this);
}
public override Decoder GetDecoder()
{
return new ISO2022Decoder(this);
}
internal sealed class ISO2022Encoder : System.Text.EncoderNLS
{
internal ISO2022Modes currentMode;
internal ISO2022Modes shiftInOutMode;
internal ISO2022Encoder(EncodingNLS encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
// Reset
currentMode = ISO2022Modes.ModeASCII;
shiftInOutMode = ISO2022Modes.ModeASCII;
charLeftOver = (char)0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our encoder?
internal override bool HasState
{
get
{
// Don't check shift-out mode, it may be ascii (JP) or not (KR)
return (charLeftOver != (char)0 || currentMode != ISO2022Modes.ModeASCII);
}
}
}
internal sealed class ISO2022Decoder : System.Text.DecoderNLS
{
internal byte[] bytesLeftOver = null!; // initialized by base calling Reset
internal int bytesLeftOverCount;
internal ISO2022Modes currentMode;
internal ISO2022Modes shiftInOutMode;
internal ISO2022Decoder(EncodingNLS encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
// Reset
bytesLeftOverCount = 0;
bytesLeftOver = new byte[4];
currentMode = ISO2022Modes.ModeASCII;
shiftInOutMode = ISO2022Modes.ModeASCII;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
// If we have bytes left over or not shifted back to ASCII then we have a problem
return (bytesLeftOverCount != 0 || currentMode != ISO2022Modes.ModeASCII);
}
}
}
private static readonly ushort[] s_HalfToFullWidthKanaTable =
{
0xa1a3, // 0x8ea1 : Halfwidth Ideographic Period
0xa1d6, // 0x8ea2 : Halfwidth Opening Corner Bracket
0xa1d7, // 0x8ea3 : Halfwidth Closing Corner Bracket
0xa1a2, // 0x8ea4 : Halfwidth Ideographic Comma
0xa1a6, // 0x8ea5 : Halfwidth Katakana Middle Dot
0xa5f2, // 0x8ea6 : Halfwidth Katakana Wo
0xa5a1, // 0x8ea7 : Halfwidth Katakana Small A
0xa5a3, // 0x8ea8 : Halfwidth Katakana Small I
0xa5a5, // 0x8ea9 : Halfwidth Katakana Small U
0xa5a7, // 0x8eaa : Halfwidth Katakana Small E
0xa5a9, // 0x8eab : Halfwidth Katakana Small O
0xa5e3, // 0x8eac : Halfwidth Katakana Small Ya
0xa5e5, // 0x8ead : Halfwidth Katakana Small Yu
0xa5e7, // 0x8eae : Halfwidth Katakana Small Yo
0xa5c3, // 0x8eaf : Halfwidth Katakana Small Tu
0xa1bc, // 0x8eb0 : Halfwidth Katakana-Hiragana Prolonged Sound Mark
0xa5a2, // 0x8eb1 : Halfwidth Katakana A
0xa5a4, // 0x8eb2 : Halfwidth Katakana I
0xa5a6, // 0x8eb3 : Halfwidth Katakana U
0xa5a8, // 0x8eb4 : Halfwidth Katakana E
0xa5aa, // 0x8eb5 : Halfwidth Katakana O
0xa5ab, // 0x8eb6 : Halfwidth Katakana Ka
0xa5ad, // 0x8eb7 : Halfwidth Katakana Ki
0xa5af, // 0x8eb8 : Halfwidth Katakana Ku
0xa5b1, // 0x8eb9 : Halfwidth Katakana Ke
0xa5b3, // 0x8eba : Halfwidth Katakana Ko
0xa5b5, // 0x8ebb : Halfwidth Katakana Sa
0xa5b7, // 0x8ebc : Halfwidth Katakana Si
0xa5b9, // 0x8ebd : Halfwidth Katakana Su
0xa5bb, // 0x8ebe : Halfwidth Katakana Se
0xa5bd, // 0x8ebf : Halfwidth Katakana So
0xa5bf, // 0x8ec0 : Halfwidth Katakana Ta
0xa5c1, // 0x8ec1 : Halfwidth Katakana Ti
0xa5c4, // 0x8ec2 : Halfwidth Katakana Tu
0xa5c6, // 0x8ec3 : Halfwidth Katakana Te
0xa5c8, // 0x8ec4 : Halfwidth Katakana To
0xa5ca, // 0x8ec5 : Halfwidth Katakana Na
0xa5cb, // 0x8ec6 : Halfwidth Katakana Ni
0xa5cc, // 0x8ec7 : Halfwidth Katakana Nu
0xa5cd, // 0x8ec8 : Halfwidth Katakana Ne
0xa5ce, // 0x8ec9 : Halfwidth Katakana No
0xa5cf, // 0x8eca : Halfwidth Katakana Ha
0xa5d2, // 0x8ecb : Halfwidth Katakana Hi
0xa5d5, // 0x8ecc : Halfwidth Katakana Hu
0xa5d8, // 0x8ecd : Halfwidth Katakana He
0xa5db, // 0x8ece : Halfwidth Katakana Ho
0xa5de, // 0x8ecf : Halfwidth Katakana Ma
0xa5df, // 0x8ed0 : Halfwidth Katakana Mi
0xa5e0, // 0x8ed1 : Halfwidth Katakana Mu
0xa5e1, // 0x8ed2 : Halfwidth Katakana Me
0xa5e2, // 0x8ed3 : Halfwidth Katakana Mo
0xa5e4, // 0x8ed4 : Halfwidth Katakana Ya
0xa5e6, // 0x8ed5 : Halfwidth Katakana Yu
0xa5e8, // 0x8ed6 : Halfwidth Katakana Yo
0xa5e9, // 0x8ed7 : Halfwidth Katakana Ra
0xa5ea, // 0x8ed8 : Halfwidth Katakana Ri
0xa5eb, // 0x8ed9 : Halfwidth Katakana Ru
0xa5ec, // 0x8eda : Halfwidth Katakana Re
0xa5ed, // 0x8edb : Halfwidth Katakana Ro
0xa5ef, // 0x8edc : Halfwidth Katakana Wa
0xa5f3, // 0x8edd : Halfwidth Katakana N
0xa1ab, // 0x8ede : Halfwidth Katakana Voiced Sound Mark
0xa1ac // 0x8edf : Halfwidth Katakana Semi-Voiced Sound Mark
};
}
}
| 40.98794 | 162 | 0.447886 | [
"MIT"
] | belav/runtime | src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs | 84,968 | C# |
using System.ComponentModel;
namespace Transloadit
{
public class ApiRequestMethods
{
#region Public enums
/// <summary>
/// Available request methods
/// </summary>
public enum RequestMethod
{
/// <summary>
/// Used for GET requests
/// </summary>
Get,
/// <summary>
/// Used for POST requests
/// </summary>
Post,
/// <summary>
/// Used for PUT requests
/// </summary>
Put,
/// <summary>
/// Used for DELETE requests
/// </summary>
Delete,
/// <summary>
/// Used for PATCH requests
/// </summary>
Patch
}
#endregion
}
}
| 19.674419 | 40 | 0.408983 | [
"MIT"
] | igofed/transloadit-csharp-sdk | src/ApiRequestMethods.cs | 848 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using FileHelpers;
namespace ExamplesFx
{
//-> Name:Sort Big File with Record Class
//-> Runnable:false
//-> Description:Shows how to sort a big file using a record class
public class BigFileSort
: ExampleBase
{
//-> If you need to sort a really big file (20Mb and more) you have the BigFileSorter
//-> Implements <a href="http://en.wikipedia.org/wiki/External_sorting">External Sorting (wikipedia)</a>
//-> The Sorter will split the file in blocks, write them to temp files, and finally join all in a sorted file
public override void Run()
{
//-> File:SortingWithRecord.cs
// OrdersTab must be IComparable<OrdersTab>
// We recommend to split in blocks between 1 and 40 Mb
var sorter = new BigFileSorter<OrdersTab>(10*1024*1024); // 10 Mb blocks
sorter.Sort("unsorted.txt", "sorted.txt");
//-> /File
}
//-> File:OrdersTab.cs
[DelimitedRecord("\t")]
public class OrdersTab
: IComparable<OrdersTab>
{
public int OrderID;
public string CustomerID;
public int EmployeeID;
public DateTime OrderDate;
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime RequiredDate;
[FieldNullValue(typeof (DateTime), "2005-1-1")]
public DateTime ShippedDate;
public int ShipVia;
public decimal Freight;
#region IComparable<OrdersTab> Members
public int CompareTo(OrdersTab other)
{
return this.OrderID.CompareTo(other.OrderID);
}
#endregion
}
//-> /File
}
} | 26.575342 | 119 | 0.557732 | [
"MIT"
] | aim00ver/FileHelpers | FileHelpers.Examples/Examples/60.Sorting/10.SortBigFiles.cs | 1,942 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ShuffleiTunesPlaylist")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ShuffleiTunesPlaylist")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.446429 | 97 | 0.740629 | [
"MIT"
] | keedba65/ShuffleiTunesPlaylist | ShuffleiTunesPlaylist/Properties/AssemblyInfo.cs | 2,324 | C# |
using Hangfire;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMachine()
.AddMongoDataAccess(builder.Configuration.GetConnectionString("Mongo"))
.AddEngineOptions(builder.Configuration.GetSection("Engine"))
.AddServiceOptions(builder.Configuration.GetSection("Service"))
.AddMongoBackgroundJobClient(builder.Configuration.GetConnectionString("Hangfire"))
.AddBackgroundJobServer();
var app = builder.Build();
await app.UseMachineAsync();
app.UseHangfireDashboard();
app.Run();
| 26.894737 | 84 | 0.808219 | [
"MIT"
] | russellmorley/machine | src/SIL.Machine.WebApi.JobServer/Program.cs | 511 | C# |
/*
* MS 06-05-30 removed this code
*
*
*
*/
//using System;
//using System.Text;
//using System.Collections;
//namespace AjaxPro
//{
// /// <summary>
// /// The two directions AJAX will convert objects.
// /// </summary>
// internal enum JavaScriptConverterDirectionType
// {
// Serialize,
// Deserialize
// }
// /// <summary>
// /// Provides methods to get converters for JSON strings or .NET objects.
// /// </summary>
// public class JavaScriptConverter
// {
// /// <summary>
// /// Get a IJavaScriptConverter that will handle the serialization of the specified data type.
// /// </summary>
// /// <param name="t">The type to handle.</param>
// /// <returns>Returns an instance of an IJavaScriptConverter.</returns>
// public static IJavaScriptConverter GetSerializableConverter(Type t)
// {
// return Utility.Settings.JavaScriptConverters.GetConverter(t, JavaScriptConverterDirectionType.Serialize);
// }
// /// <summary>
// /// Get a IJavaScriptConverter that will handle the deserialization of the specified data type.
// /// </summary>
// /// <param name="t">The type to handle.</param>
// /// <returns>Returns an instance of an IJavaScriptConverter.</returns>
// public static IJavaScriptConverter GetDeserializableConverter(Type t)
// {
// return Utility.Settings.JavaScriptConverters.GetConverter(t, JavaScriptConverterDirectionType.Deserialize);
// }
// }
//} | 34.276596 | 122 | 0.602731 | [
"MIT"
] | SmartDev210/Ajax.NET-Professional | AjaxPro/JSON/JavaScriptConverter.cs | 1,611 | C# |
//
// PkzipClassic encryption
//
// Copyright 2004 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
//
using System;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.Silverlight.Checksums;
namespace ICSharpCode.SharpZipLib.Silverlight.Encryption
{
/// <summary>
/// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives.
/// While it has been superceded by more recent and more powerful algorithms, its still in use and
/// is viable for preventing casual snooping
/// </summary>
public abstract class PkzipClassic : SymmetricAlgorithm
{
/// <summary>
/// Generates new encryption keys based on given seed
/// </summary>
/// <param name="seed">The seed value to initialise keys with.</param>
/// <returns>A new key value.</returns>
public static byte[] GenerateKeys(byte[] seed)
{
if (seed == null)
{
throw new ArgumentNullException("seed");
}
if (seed.Length == 0)
{
throw new ArgumentException("Length is zero", "seed");
}
var newKeys = new uint[]{
0x12345678,
0x23456789,
0x34567890
};
for (var i = 0; i < seed.Length; ++i)
{
newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]);
newKeys[1] = newKeys[1] + (byte) newKeys[0];
newKeys[1] = newKeys[1]*134775813 + 1;
newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte) (newKeys[1] >> 24));
}
var result = new byte[12];
result[0] = (byte) (newKeys[0] & 0xff);
result[1] = (byte) ((newKeys[0] >> 8) & 0xff);
result[2] = (byte) ((newKeys[0] >> 16) & 0xff);
result[3] = (byte) ((newKeys[0] >> 24) & 0xff);
result[4] = (byte) (newKeys[1] & 0xff);
result[5] = (byte) ((newKeys[1] >> 8) & 0xff);
result[6] = (byte) ((newKeys[1] >> 16) & 0xff);
result[7] = (byte) ((newKeys[1] >> 24) & 0xff);
result[8] = (byte) (newKeys[2] & 0xff);
result[9] = (byte) ((newKeys[2] >> 8) & 0xff);
result[10] = (byte) ((newKeys[2] >> 16) & 0xff);
result[11] = (byte) ((newKeys[2] >> 24) & 0xff);
return result;
}
}
/// <summary>
/// PkzipClassicCryptoBase provides the low level facilities for encryption
/// and decryption using the PkzipClassic algorithm.
/// </summary>
internal class PkzipClassicCryptoBase
{
/// <summary>
/// Transform a single byte
/// </summary>
/// <returns>
/// The transformed value
/// </returns>
protected byte TransformByte()
{
var temp = ((keys[2] & 0xFFFF) | 2);
return (byte) ((temp*(temp ^ 1)) >> 8);
}
/// <summary>
/// Set the key schedule for encryption/decryption.
/// </summary>
/// <param name="keyData">The data use to set the keys from.</param>
protected void SetKeys(byte[] keyData)
{
if (keyData == null)
{
throw new ArgumentNullException("keyData");
}
if (keyData.Length != 12)
{
throw new InvalidOperationException("Key length is not valid");
}
keys = new uint[3];
keys[0] = (uint) ((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]);
keys[1] = (uint) ((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]);
keys[2] = (uint) ((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]);
}
/// <summary>
/// Update encryption keys
/// </summary>
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte) keys[0];
keys[1] = keys[1]*134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte) (keys[1] >> 24));
}
/// <summary>
/// Reset the internal state.
/// </summary>
protected void Reset()
{
keys[0] = 0;
keys[1] = 0;
keys[2] = 0;
}
#region Instance Fields
private uint[] keys;
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for encryption.
/// </summary>
internal class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicEncryptCryptoTransform"></see>
/// </summary>
/// <param name="keyBlock">The key block to use.</param>
internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
var result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer,
int outputOffset)
{
for (var i = inputOffset; i < inputOffset + inputCount; ++i)
{
var oldbyte = inputBuffer[i];
outputBuffer[outputOffset++] = (byte) (inputBuffer[i] ^ TransformByte());
UpdateKeys(oldbyte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform
{
get { return true; }
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize
{
get { return 1; }
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize
{
get { return 1; }
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks
{
get { return true; }
}
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for decryption.
/// </summary>
internal class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicDecryptCryptoTransform"></see>.
/// </summary>
/// <param name="keyBlock">The key block to decrypt with.</param>
internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
var result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer,
int outputOffset)
{
for (var i = inputOffset; i < inputOffset + inputCount; ++i)
{
var newByte = (byte) (inputBuffer[i] ^ TransformByte());
outputBuffer[outputOffset++] = newByte;
UpdateKeys(newByte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform
{
get { return true; }
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize
{
get { return 1; }
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize
{
get { return 1; }
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks
{
get { return true; }
}
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// Defines a wrapper object to access the Pkzip algorithm.
/// This class cannot be inherited.
/// </summary>
public sealed class PkzipClassicManaged : PkzipClassic
{
/// <summary>
/// Get / set the applicable block size in bits.
/// </summary>
/// <remarks>The only valid block size is 8.</remarks>
public override int BlockSize
{
get { return 8; }
set
{
if (value != 8)
{
throw new CryptographicException("Block size is invalid");
}
}
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">key sizes.</see>
/// </summary>
public override KeySizes[] LegalKeySizes
{
get
{
var keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(12*8, 12*8, 0);
return keySizes;
}
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">block sizes</see>.
/// </summary>
public override KeySizes[] LegalBlockSizes
{
get
{
var keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(1*8, 1*8, 0);
return keySizes;
}
}
/// <summary>
/// Get / set the key value applicable.
/// </summary>
public override byte[] Key
{
get
{
if (key_ == null)
{
GenerateKey();
}
return (byte[]) key_.Clone();
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Length != 12)
{
throw new CryptographicException("Key size is illegal");
}
key_ = (byte[]) value.Clone();
}
}
/// <summary>
/// Generate an initial vector.
/// </summary>
public override void GenerateIV()
{
// Do nothing.
}
/// <summary>
/// Generate a new random key.
/// </summary>
public override void GenerateKey()
{
key_ = new byte[12];
var rnd = new Random();
rnd.NextBytes(key_);
}
/// <summary>
/// Create an encryptor.
/// </summary>
/// <param name="rgbKey">The key to use for this encryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new encryptor.</param>
/// <returns>Returns a new PkzipClassic encryptor</returns>
public override ICryptoTransform CreateEncryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicEncryptCryptoTransform(Key);
}
/// <summary>
/// Create a decryptor.
/// </summary>
/// <param name="rgbKey">Keys to use for this new decryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new decryptor.</param>
/// <returns>Returns a new decryptor.</returns>
public override ICryptoTransform CreateDecryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicDecryptCryptoTransform(Key);
}
#region Instance Fields
private byte[] key_;
#endregion
}
} | 36.034765 | 119 | 0.527496 | [
"MIT"
] | BigBadChicago/hammock | src/net35/ICSharpCode.SharpZipLib.Silverlight/Encryption/PkzipClassic.cs | 17,621 | C# |
using System.Data;
namespace CloudNativeKit.Infrastructure.Data.Dapper
{
public interface ISqlConnectionFactory
{
IDbConnection GetOpenConnection();
}
}
| 17.4 | 51 | 0.735632 | [
"MIT"
] | HardikKSavaliya/coolstore-microservices | src/building-blocks/CloudNativeKit.Infrastructure.Data/Dapper/ISqlConnectionFactory.cs | 174 | C# |
using System;
using MassTransit;
// Ref from https://github.com/yesmarket/MassTransit.OpenTracing
namespace CRM.MassTransit.Tracing
{
public static class Extensions
{
public static void PropagateOpenTracingContext(this IBusFactoryConfigurator value)
{
value.ConfigurePublish(c => c.AddPipeSpecification(new OpenTracingPipeSpecification()));
value.AddPipeSpecification(new OpenTracingPipeSpecification());
}
public static string GetExchangeName(this Uri value)
{
var exchange = value.LocalPath;
var messageType = exchange.Substring(exchange.LastIndexOf('/') + 1);
return messageType;
}
}
}
| 30.913043 | 100 | 0.673699 | [
"MIT"
] | thangchung/crm | src/BuildingBlocks/CRM.MassTransit.Tracing/Extensions.cs | 711 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.DesignScript.Interfaces;
namespace Autodesk.DesignScript.Geometry
{
public class DSSurfaceCurvature : IDisplayable
{
#region DATA MEMBERS
private DSCoordinateSystem mCoordinateSystem;
private DSPoint mPointOnSurface;
private DSSurface mContextSurface;
#endregion
#region PROPERTIES
public DSCoordinateSystem CoordinateSystem
{
get { return mCoordinateSystem; }
}
public DSPoint PointOnSurface
{
get { return mPointOnSurface; }
}
public DSSurface ContextSurface
{
get { return mContextSurface; }
private set { value.AssignTo(ref mContextSurface); }
}
public DSVector FirstPrincipleCurvature { get; private set; }
public DSVector SecondPrincipleCurvature { get; private set; }
public double GaussianCurvature { get; private set; }
public double U { get; private set; }
public double V { get; private set; }
#endregion
private DSSurfaceCurvature(DSSurface contextSurface, double u, double v, ICoordinateSystemEntity coordinateSystemEntity)
{
FirstPrincipleCurvature = new DSVector(coordinateSystemEntity.XAxis);
SecondPrincipleCurvature = new DSVector(coordinateSystemEntity.YAxis);
GaussianCurvature = FirstPrincipleCurvature.Length * SecondPrincipleCurvature.Length;
mPointOnSurface = DSPoint.ToGeometry(coordinateSystemEntity.Origin, false, contextSurface) as DSPoint;
U = u;
V = v;
ContextSurface = contextSurface;
mCoordinateSystem = DSCoordinateSystem.ToCS(coordinateSystemEntity, false);
}
/// <summary>
///
/// </summary>
/// <param name="contextSurface"></param>
/// <param name="u"></param>
/// <param name="v"></param>
/// <returns></returns>
public static DSSurfaceCurvature BySurfaceParameters(DSSurface contextSurface, double u, double v)
{
if (contextSurface == null)
return null;
ISurfaceEntity host = contextSurface.GetSurfaceEntity();
if (host == null)
return null;
ICoordinateSystemEntity coordinateSystemEntity = host.CurvatureAtParameter(u, v);
if (null != coordinateSystemEntity)
{
DSSurfaceCurvature surfCurv = new DSSurfaceCurvature(contextSurface, u, v, coordinateSystemEntity);
return surfCurv;
}
return null;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(true);
}
private void Dispose(bool disposing)
{
if (disposing)
{
DSGeometryExtension.DisposeObject(ref mCoordinateSystem);
DSGeometryExtension.DisposeObject(ref mPointOnSurface);
DSGeometryExtension.DisposeObject(ref mContextSurface);
}
}
#region FROM_IDISPLAYATTRIBUTES
public bool Highlight(bool visibility)
{
return CoordinateSystem.Highlight(visibility);
}
private DSSurfaceCurvature SetVisibilityCore(bool visible)
{
CoordinateSystem.SetVisibility(visible);
this.Visible = visible;
return this;
}
public DSSurfaceCurvature SetVisibility(bool visible)
{
return SetVisibilityCore(visible);
}
IDisplayable IDisplayable.SetVisibility(bool visible)
{
return SetVisibilityCore(visible);
}
IDisplayable IDisplayable.SetColor(IColor color)
{
throw new NotImplementedException();
}
IColor IDisplayable.Color
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool Visible
{
get
{
return CoordinateSystem.Visible;
}
set
{
CoordinateSystem.Visible = value;
}
}
#endregion
}
}
| 31.751724 | 129 | 0.561685 | [
"Apache-2.0"
] | DynamoDS/designscript-archive | Libraries/DSProtoGeometry/Geometry/SurfaceCurvature.cs | 4,606 | C# |
using System;
namespace ProjectManager.ConsoleClient.Configs
{
public interface IConfigurationProvider
{
TimeSpan CacheDurationInSeconds { get; }
string LogFilePath { get; }
}
}
| 17.416667 | 48 | 0.688995 | [
"MIT"
] | SimeonGerginov/Telerik-Academy | 06. C# Design Patterns/Exams/2017-06-15/ProjectManager.ConsoleClient/Configs/IConfigurationProvider.cs | 211 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
namespace SharpVk
{
/// <summary>
///
/// </summary>
[System.Flags]
public enum PipelineCacheCreateFlags
{
/// <summary>
///
/// </summary>
None = 0,
}
}
| 37.282051 | 81 | 0.713893 | [
"MIT"
] | FacticiusVir/SharpVk | src/SharpVk/PipelineCacheCreateFlags.gen.cs | 1,454 | C# |
using System.Linq;
using Elsa.Activities.Workflows;
using Elsa.Contracts;
namespace Elsa.Dsl.Interpreters;
public partial class WorkflowDefinitionBuilderInterpreter
{
public override IWorkflowDefinitionBuilder VisitProgram(ElsaParser.ProgramContext context)
{
var stats = context.stat();
var rootSequence = new Sequence();
// Push a sequence to allow multiple activities declared in sequence.
_containerStack.Push(rootSequence);
// Interpret child nodes.
VisitChildren(context);
// Extract activities from child nodes.
var activities = stats.Select(x => _expressionValue.Get(x) as IActivity).Where(x => x != null).Select(x => x!).ToList();
if (activities.Count == 1)
{
// We only have one activity, so we can use it as the root and discard the root sequence.
_workflowDefinitionBuilder.WithRoot(activities.Single());
}
else
{
// Assign the collected child activities to the root sequence.
rootSequence.Activities = activities.ToList();
_workflowDefinitionBuilder.WithRoot(rootSequence);
}
return DefaultResult;
}
} | 32.810811 | 128 | 0.659802 | [
"MIT"
] | elsa-workflows/experimental | src/dsl/Elsa.Dsl/Interpreters/WorkflowDefinitionBuilderInterpreter/VisitFile.cs | 1,216 | C# |
using UnityEngine;
#pragma warning disable CS0649
namespace WraithavenGames.FirstSight
{
public class MouseController : MonoBehaviour
{
[Header("Dependencies")]
[SerializeField] private Transform cam;
[SerializeField] private InputSettings inputSettings;
[Tooltip("Optional Field")]
[SerializeField] private ScreenShake shake;
private float yaw;
private float pitch;
private float LookX { get { return inputSettings == null ? 0f : inputSettings.LookX; } }
private float LookY { get { return inputSettings == null ? 0f : inputSettings.LookY; } }
private void OnEnable()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void OnDisable()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
private void Update()
{
if (cam == null)
return;
yaw += LookX * Time.unscaledDeltaTime;
pitch -= LookY * Time.unscaledDeltaTime;
yaw %= 360f;
pitch = Mathf.Clamp(pitch, -89f, 89f);
transform.localRotation = Quaternion.Euler(0f, yaw, 0f);
cam.localRotation = Quaternion.Euler(pitch, 0f, 0f);
if (shake != null)
shake.ShakeCamera(cam);
}
}
}
| 27.679245 | 97 | 0.551466 | [
"MIT"
] | TheDudeFromCI/FirstSight | Packages/net.wraithavengames.firstsight/Runtime/Scripts/Controls/MouseController.cs | 1,467 | C# |
// Copyright (c) Aurora Studio. All rights reserved.
//
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Aurora.Music.Core.Extension;
using Aurora.Music.Core.Models;
using Aurora.Shared.MVVM;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
namespace Aurora.Music.ViewModels
{
class PodcastMarketViewModel : ViewModelBase
{
public ObservableCollection<GenericMusicItemViewModel> TopList { get; set; }
public ObservableCollection<PodcastGroup> Genres { get; set; }
/// <summary>
/// <see cref="https://affiliate.itunes.apple.com/resources/documentation/genre-mapping/"/>
/// </summary>
private static readonly List<KeyValuePair<string, string>> genres =
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Arts", "1301"),
new KeyValuePair<string, string>("Comedy", "1303"),
new KeyValuePair<string, string>("Education", "1304"),
new KeyValuePair<string, string>("Kids & Family", "1305"),
new KeyValuePair<string, string>("Health", "1307"),
new KeyValuePair<string, string>("TV & Film", "1309"),
new KeyValuePair<string, string>("Music", "1310"),
new KeyValuePair<string, string>("News & Politics", "1311"),
new KeyValuePair<string, string>("Religion & Spirituality", "1314"),
new KeyValuePair<string, string>("Science & Medicine", "1315"),
new KeyValuePair<string, string>("Sports & Recreation", "1316"),
new KeyValuePair<string, string>("Technology", "1318"),
new KeyValuePair<string, string>("Business", "1321"),
new KeyValuePair<string, string>("Games & Hobbies", "1323"),
new KeyValuePair<string, string>("Society & Culture", "1324"),
new KeyValuePair<string, string>("Government & Organizations", "1325")
};
public PodcastMarketViewModel()
{
TopList = new ObservableCollection<GenericMusicItemViewModel>();
Genres = new ObservableCollection<PodcastGroup>();
}
public void Fetch()
{
Task.Run(async () =>
{
var res = await Podcast.GetiTunesTop(15);
await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
{
TopList.Clear();
foreach (var item in res)
{
TopList.Add(new GenericMusicItemViewModel(item));
}
});
});
Task.Run(async () =>
{
foreach (var g in genres)
{
await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () =>
{
var p = new PodcastGroup
{
Title = g.Key,
GenreID = g.Value
};
Genres.Add(p);
await p.GetItems(15);
});
}
});
}
}
internal class PodcastGroup : ViewModelBase
{
public ObservableCollection<GenericMusicItemViewModel> Items { get; set; }
public string Title { get; set; }
public string GenreID { get; internal set; }
public PodcastGroup()
{
Items = new ObservableCollection<GenericMusicItemViewModel>();
}
internal async Task GetItems(int m)
{
var res = await ITunesSearcher.TopGenres(GenreID, m);
foreach (var a in res.feed.entry)
{
Items.Add(new GenericMusicItemViewModel()
{
Title = a.Name.label,
Description = a.Summary?.label,
Addtional = a.Artist.label,
OnlineAlbumID = a.ID.attributes["im:id"],
Artwork = new Uri(a.Image[2].label)
});
}
}
}
}
| 37.294118 | 127 | 0.535376 | [
"MIT"
] | Lolle2000la/Aurora.Music | Source/Aurora.Music/ViewModels/PodcastMarketViewModel.cs | 4,440 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("1.5.17")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("1.5.17")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("d441913e-a2a4-4d72-ba91-a883382ca651")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 24.833333 | 56 | 0.700224 | [
"MIT"
] | xuxu66/Algorithms-4th-Edition-in-Csharp | 1 Fundamental/1.5/1.5.17/Properties/AssemblyInfo.cs | 1,235 | C# |
/*
Copyright 2016 James Craig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Collections.Concurrent;
using System.ComponentModel;
namespace BigBook
{
/// <summary>
/// ConcurrentDictionary extensions
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ConcurrentDictionaryExtensions
{
/// <summary>
/// Copies the dictionary to another dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="target">The target dictionary.</param>
/// <returns>This</returns>
public static ConcurrentDictionary<TKey, TValue> CopyTo<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, ConcurrentDictionary<TKey, TValue> target)
{
dictionary ??= new ConcurrentDictionary<TKey, TValue>();
if (target is null)
return dictionary;
foreach (var x in dictionary)
{
target.SetValue(x.Key, x.Value);
}
return dictionary;
}
/// <summary>
/// Gets the value from a dictionary or the default value if it isn't found
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="dictionary">Dictionary to get the value from</param>
/// <param name="key">Key to look for</param>
/// <param name="defaultValue">Default value if the key is not found</param>
/// <returns>
/// The value associated with the key or the default value if the key is not found
/// </returns>
public static TValue GetValue<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default)
{
if (dictionary is null || key is null)
{
return defaultValue;
}
return dictionary.TryGetValue(key, out var ReturnValue) ? ReturnValue : defaultValue;
}
/// <summary>
/// Sets the value in a dictionary
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="dictionary">Dictionary to set the value in</param>
/// <param name="key">Key to look for</param>
/// <param name="value">Value to add</param>
/// <returns>The dictionary</returns>
public static ConcurrentDictionary<TKey, TValue> SetValue<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary is null || key is null)
{
return new ConcurrentDictionary<TKey, TValue>();
}
dictionary.AddOrUpdate(key, value, (_, __) => value);
return dictionary;
}
}
} | 40.932584 | 173 | 0.607741 | [
"Apache-2.0"
] | JaCraig/BigBookOfDataTypes | src/BigBook/ExtensionMethods/ConcurrentDictionaryExtensions.cs | 3,645 | C# |
/* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Tizen.NUI.Components
{
/// <summary>
/// [Draft] Defalt adapter for RecyclerView.
/// Managing RecycleItem and Data for RecyclerView.
/// </summary>
/// <since_tizen> 8 </since_tizen>
/// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
[EditorBrowsable(EditorBrowsableState.Never)]
public class RecycleAdapter
{
private List<object> mData = new List<object>();
/// <summary>
/// Create recycle item for RecyclerView.
/// RecyclerView will make its children using this api.
/// </summary>
/// <returns>Item for RecyclerView</returns>
/// <since_tizen> 8 </since_tizen>
/// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual RecycleItem CreateRecycleItem()
{
return new RecycleItem();
}
/// <summary>
/// Bind data with recycler item.
/// This function is called when RecyclerItem is used again with new data.
/// Can update content of recycle item with new data at DataIndex of item.
/// </summary>
/// <param name="item">Reused RecycleItem which needs data binding.</param>
/// <since_tizen> 8 </since_tizen>
/// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void BindData(RecycleItem item)
{
}
/// <summary>
/// Notify when data of adapter is changed.
/// </summary>
/// <since_tizen> 8 </since_tizen>
/// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
[EditorBrowsable(EditorBrowsableState.Never)]
public void Notify()
{
OnDataChanged?.Invoke(this, new EventArgs());
}
/// <summary>
/// Triggered when user called Notify().
/// </summary>
/// <since_tizen> 8 </since_tizen>
/// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
[EditorBrowsable(EditorBrowsableState.Never)]
public event EventHandler<EventArgs> OnDataChanged;
/// <summary>
/// Triggered when user called Notify().
/// </summary>
/// <since_tizen> 8 </since_tizen>
/// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
[EditorBrowsable(EditorBrowsableState.Never)]
public List<object> Data{
get
{
return mData;
}
set
{
mData = value;
Notify();
}
}
}
} | 37.371134 | 111 | 0.621241 | [
"Apache-2.0",
"MIT"
] | Ali-Alzyoud/TizenFX | src/Tizen.NUI.Components/Controls/RecyclerView/RecycleAdapter.cs | 3,625 | C# |
/*
* Funds API For Digital Portals
*
* Search for mutual funds and ETFs using one single consolidated API, including a criteria-based screener. The API provides also base data, key figures, and holdings. A separate endpoint returns the possible values and value range for the parameters that the endpoint /fund/notation/screener/search accepts: Application developers can request the values and value range only for a restricted set of notations that match predefined parameters. This functionality may be used to pre-fill the values and value ranges of the parameters of the /fund/notation/screener/search endpoint so that performing a search always leads to a non-empty set of notations. This API is fully integrated with the corresponding Quotes API, allowing access to detailed price and performance information of instruments, as well as basic security identifier cross-reference. For direct access to price histories, please refer to the Time Series API for Digital Portals. Similar criteria based screener APIs exist for equity instruments and securitized derivatives: See the Stocks API and the Securitized Derivatives API for details.
*
* The version of the OpenAPI document: 2
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.FundsAPIforDigitalPortals.Client.OpenAPIDateConverter;
namespace FactSet.SDK.FundsAPIforDigitalPortals.Model
{
/// <summary>
/// Third level of classification.
/// </summary>
[DataContract(Name = "inline_response_200_4_fund_strategy_level3")]
public partial class InlineResponse2004FundStrategyLevel3 : IEquatable<InlineResponse2004FundStrategyLevel3>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="InlineResponse2004FundStrategyLevel3" /> class.
/// </summary>
/// <param name="id">Identifier of a category..</param>
/// <param name="name">Name of the category..</param>
public InlineResponse2004FundStrategyLevel3(decimal id = default(decimal), string name = default(string))
{
this.Id = id;
this.Name = name;
}
/// <summary>
/// Identifier of a category.
/// </summary>
/// <value>Identifier of a category.</value>
[DataMember(Name = "id", EmitDefaultValue = false)]
public decimal Id { get; set; }
/// <summary>
/// Name of the category.
/// </summary>
/// <value>Name of the category.</value>
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class InlineResponse2004FundStrategyLevel3 {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as InlineResponse2004FundStrategyLevel3);
}
/// <summary>
/// Returns true if InlineResponse2004FundStrategyLevel3 instances are equal
/// </summary>
/// <param name="input">Instance of InlineResponse2004FundStrategyLevel3 to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InlineResponse2004FundStrategyLevel3 input)
{
if (input == null)
{
return false;
}
return
(
this.Id == input.Id ||
this.Id.Equals(input.Id)
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = (hashCode * 59) + this.Id.GetHashCode();
if (this.Name != null)
{
hashCode = (hashCode * 59) + this.Name.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 41.17931 | 1,110 | 0.621839 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/FundsAPIforDigitalPortals/v2/src/FactSet.SDK.FundsAPIforDigitalPortals/Model/InlineResponse2004FundStrategyLevel3.cs | 5,971 | C# |
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Symbology;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace ArcGISRuntimeSDKDotNet_DesktopSamples.Samples
{
/// <summary>
/// This sample demonstrates use of the GeometryEngine to calculate a buffer. To use the sample, click a point on the map. The click point and a buffer of 5 miles around the point will be shown.
/// </summary>
/// <title>Buffer</title>
/// <category>Geometry</category>
public partial class BufferSample : UserControl
{
private const double MILES_TO_METERS = 1609.34;
private PictureMarkerSymbol _pinSymbol;
private SimpleFillSymbol _bufferSymbol;
/// <summary>Construct Buffer sample control</summary>
public BufferSample()
{
InitializeComponent();
mapView.Map.InitialExtent = new Envelope(-10863035.970, 3838021.340, -10744801.344, 3887145.299);
var task = SetupSymbols();
}
private void mapView_MouseDown(object sender, MouseButtonEventArgs e)
{
try
{
graphicsLayer.Graphics.Clear();
// Convert screen point to map point
var point = mapView.ScreenToLocation(e.GetPosition(mapView));
var buffer = GeometryEngine.Buffer(point, 5 * MILES_TO_METERS);
//show geometries on map
if (graphicsLayer != null)
{
var pointGraphic = new Graphic { Geometry = point, Symbol = _pinSymbol };
graphicsLayer.Graphics.Add(pointGraphic);
var bufferGraphic = new Graphic { Geometry = buffer, Symbol = _bufferSymbol };
graphicsLayer.Graphics.Add(bufferGraphic);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Geometry Engine Failed!");
}
}
private async Task SetupSymbols()
{
_pinSymbol = new PictureMarkerSymbol() { Width = 48, Height = 48, YOffset = 24 };
await _pinSymbol.SetSourceAsync(new Uri("pack://application:,,,/ArcGISRuntimeSDKDotNet_DesktopSamples;component/Assets/RedStickpin.png"));
_bufferSymbol = layoutGrid.Resources["BufferSymbol"] as SimpleFillSymbol;
}
}
}
| 36.376812 | 198 | 0.624701 | [
"Apache-2.0"
] | boonyachengdu/arcgis-runtime-samples-dotnet | src/Desktop/ArcGISRuntimeSDKDotNet_DesktopSamples/Samples/Geometry/BufferSample.xaml.cs | 2,512 | C# |
// Copyright 2016 MaterialUI for Unity http://materialunity.com
// Please see license file for terms and conditions of use, and more information.
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
namespace MaterialUI
{
[CustomEditor(typeof(CircularProgressIndicator))]
public class CircularProgressIndicatorEditor : MaterialBaseEditor
{
private SerializedProperty m_CurrentProgress;
private SerializedProperty m_BaseObjectOverride;
private SerializedProperty m_CircleRectTransform;
private SerializedProperty m_StartsIndeterminate;
private SerializedProperty m_StartsHidden;
void OnEnable()
{
OnBaseEnable();
m_CurrentProgress = serializedObject.FindProperty("m_CurrentProgress");
m_BaseObjectOverride = serializedObject.FindProperty("m_BaseObjectOverride");
m_CircleRectTransform = serializedObject.FindProperty("m_CircleRectTransform");
m_StartsIndeterminate = serializedObject.FindProperty("m_StartsIndeterminate");
m_StartsHidden = serializedObject.FindProperty("m_StartsHidden");
}
void OnDisable()
{
OnBaseDisable();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(m_CurrentProgress);
EditorGUILayout.PropertyField(m_StartsIndeterminate);
EditorGUILayout.PropertyField(m_StartsHidden);
DrawFoldoutExternalProperties(ExternalPropertiesSection);
DrawFoldoutComponents(ComponentSection);
serializedObject.ApplyModifiedProperties();
}
private bool ExternalPropertiesSection()
{
RectTransform circleRectTransformValue = m_CircleRectTransform.objectReferenceValue as RectTransform;
if (circleRectTransformValue == null) return false;
if (circleRectTransformValue.childCount == 0) return false;
return InspectorFields.GraphicColorField("Circle", circleRectTransformValue.GetChild(0).GetComponent<Graphic>());
}
private void ComponentSection()
{
EditorGUILayout.PropertyField(m_CircleRectTransform);
EditorGUILayout.PropertyField(m_BaseObjectOverride);
}
}
} | 36.787879 | 126 | 0.679572 | [
"Apache-2.0"
] | Ianmaster231/tabekana | Tabekana/Assets/MaterialUI/Editor/Custom Inspectors/CircularProgressIndicatorEditor.cs | 2,430 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type UserExportDeviceAndAppManagementDataRequest.
/// </summary>
public partial class UserExportDeviceAndAppManagementDataRequest : BaseRequest, IUserExportDeviceAndAppManagementDataRequest
{
/// <summary>
/// Constructs a new UserExportDeviceAndAppManagementDataRequest.
/// </summary>
public UserExportDeviceAndAppManagementDataRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Issues the GET request.
/// </summary>
public System.Threading.Tasks.Task<DeviceAndAppManagementData> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Issues the GET request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<DeviceAndAppManagementData> GetAsync(
CancellationToken cancellationToken)
{
this.Method = "GET";
return this.SendAsync<DeviceAndAppManagementData>(null, cancellationToken);
}
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name="deviceandappmanagementdata">The DeviceAndAppManagementData object set with the properties to update.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<DeviceAndAppManagementData> PatchAsync(DeviceAndAppManagementData deviceandappmanagementdata)
{
return this.PatchAsync(deviceandappmanagementdata, CancellationToken.None);
}
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name="deviceandappmanagementdata">The DeviceAndAppManagementData object set with the properties to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<DeviceAndAppManagementData> PatchAsync(DeviceAndAppManagementData deviceandappmanagementdata,
CancellationToken cancellationToken)
{
this.Method = "PATCH";
return this.SendAsync<DeviceAndAppManagementData>(deviceandappmanagementdata, cancellationToken);
}
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name="deviceandappmanagementdata">The DeviceAndAppManagementData object to update.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<DeviceAndAppManagementData> PutAsync(DeviceAndAppManagementData deviceandappmanagementdata)
{
return this.PutAsync(deviceandappmanagementdata, CancellationToken.None);
}
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name="deviceandappmanagementdata">The DeviceAndAppManagementData object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<DeviceAndAppManagementData> PutAsync(DeviceAndAppManagementData deviceandappmanagementdata,
CancellationToken cancellationToken)
{
this.Method = "PUT";
return this.SendAsync<DeviceAndAppManagementData>(deviceandappmanagementdata, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IUserExportDeviceAndAppManagementDataRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IUserExportDeviceAndAppManagementDataRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 42.862903 | 153 | 0.629915 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/UserExportDeviceAndAppManagementDataRequest.cs | 5,315 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list of conditions
// and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// - Neither the name of Daniel Kollmann nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using Brainiac.Design.Nodes;
using Brainiac.Design.Attributes;
namespace Brainiac.Design.Exporters
{
public class ExporterCsUseParameters : ExporterCs
{
public ExporterCsUseParameters(BehaviorNode node, string outputFolder, string filename) : base(node, outputFolder, filename)
{
}
protected override void ExportConstructorAndProperties(System.IO.StreamWriter file, Node node, string indent, string nodeName, string classname)
{
// get all the properties that need to be exported
IList<DesignerPropertyInfo> properties= node.GetDesignerProperties();
// generate the list of parameters
string parameters= string.Empty;
for(int p= 0; p <properties.Count; ++p)
{
if(!properties[p].Attribute.HasFlags(DesignerProperty.DesignerFlags.NoExport))
parameters+= properties[p].GetExportValue(node) +", ";
}
// remove the comma
if(parameters !=string.Empty)
parameters= parameters.Substring(0, parameters.Length -2);
// create a new instance of the node
file.Write( string.Format("{0}\t{2} {1} = new {2}({3});\r\n", indent, nodeName, classname, parameters) );
}
}
}
| 45.96875 | 146 | 0.707002 | [
"MIT"
] | MattFiler/TextAdventure | Story Tool/Source/Brainiac Designer/Brainiac Designer Base/Exporters/ExporterCsUseParameters.cs | 2,942 | C# |
using Inlämning_3_WebbShop.Views;
using MyFirstEntityframProject;
using System;
namespace Inlämning_3_WebbShop
{
class Program
{
static void Main(string[] args)
{
var utils = new Utils.Utils();
utils.Menu();
}
}
}
| 16.421053 | 42 | 0.528846 | [
"MIT"
] | marcusjobb/NET20D | OOPA/WebbshopProjekt/Yulia/Inlämning_3/Inlämning_3_WebbShop/Inlämning_3_WebbShop/Program.cs | 316 | C# |
using System;
using System.Collections.Generic;
namespace PowerBIRestDemo.Models
{
// Models returned by AccountController actions.
public class ExternalLoginViewModel
{
public string Name { get; set; }
public string Url { get; set; }
public string State { get; set; }
}
public class ManageInfoViewModel
{
public string LocalLoginProvider { get; set; }
public string Email { get; set; }
public IEnumerable<UserLoginInfoViewModel> Logins { get; set; }
public IEnumerable<ExternalLoginViewModel> ExternalLoginProviders { get; set; }
}
public class UserInfoViewModel
{
public string Email { get; set; }
public bool HasRegistered { get; set; }
public string LoginProvider { get; set; }
}
public class UserLoginInfoViewModel
{
public string LoginProvider { get; set; }
public string ProviderKey { get; set; }
}
}
| 22.045455 | 87 | 0.639175 | [
"MIT"
] | Azure/azure-stream-analytics | Samples/SensorDataAnalytics/SourceCode/Archived/PowerBIRestDemo-master/PowerBIRestDemo/Models/AccountViewModels.cs | 972 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace DataLayer.Migrations
{
public partial class Kur : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "StudentAddresses",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Street = table.Column<string>(nullable: true),
City = table.Column<string>(nullable: true),
ZipCode = table.Column<int>(nullable: false),
Country = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_StudentAddresses", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Students",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
FirstName = table.Column<string>(maxLength: 50, nullable: false),
LastName = table.Column<string>(nullable: true),
DateOfBirth = table.Column<DateTime>(nullable: false),
AddressId = table.Column<int>(nullable: false),
CourseId = table.Column<int>(nullable: true),
MarkId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Students", x => x.Id);
table.ForeignKey(
name: "FK_Students_StudentAddresses_AddressId",
column: x => x.AddressId,
principalTable: "StudentAddresses",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Subjects",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true),
StudentId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Subjects", x => x.Id);
table.ForeignKey(
name: "FK_Subjects_Students_StudentId",
column: x => x.StudentId,
principalTable: "Students",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Marks",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true),
SubjectId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Marks", x => x.Id);
table.ForeignKey(
name: "FK_Marks_Subjects_SubjectId",
column: x => x.SubjectId,
principalTable: "Subjects",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Teacher",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
FirstName = table.Column<string>(nullable: true),
LastName = table.Column<string>(nullable: true),
SubjectId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teacher", x => x.Id);
table.ForeignKey(
name: "FK_Teacher_Subjects_SubjectId",
column: x => x.SubjectId,
principalTable: "Subjects",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Courses",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CourseName = table.Column<string>(nullable: true),
MarkId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Courses", x => x.Id);
table.ForeignKey(
name: "FK_Courses_Marks_MarkId",
column: x => x.MarkId,
principalTable: "Marks",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Courses_MarkId",
table: "Courses",
column: "MarkId");
migrationBuilder.CreateIndex(
name: "IX_Marks_SubjectId",
table: "Marks",
column: "SubjectId");
migrationBuilder.CreateIndex(
name: "IX_Students_AddressId",
table: "Students",
column: "AddressId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Students_CourseId",
table: "Students",
column: "CourseId");
migrationBuilder.CreateIndex(
name: "IX_Students_MarkId",
table: "Students",
column: "MarkId");
migrationBuilder.CreateIndex(
name: "IX_Subjects_StudentId",
table: "Subjects",
column: "StudentId");
migrationBuilder.CreateIndex(
name: "IX_Teacher_SubjectId",
table: "Teacher",
column: "SubjectId");
migrationBuilder.AddForeignKey(
name: "FK_Students_Marks_MarkId",
table: "Students",
column: "MarkId",
principalTable: "Marks",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Students_Courses_CourseId",
table: "Students",
column: "CourseId",
principalTable: "Courses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Courses_Marks_MarkId",
table: "Courses");
migrationBuilder.DropForeignKey(
name: "FK_Students_Marks_MarkId",
table: "Students");
migrationBuilder.DropTable(
name: "Teacher");
migrationBuilder.DropTable(
name: "Marks");
migrationBuilder.DropTable(
name: "Subjects");
migrationBuilder.DropTable(
name: "Students");
migrationBuilder.DropTable(
name: "StudentAddresses");
migrationBuilder.DropTable(
name: "Courses");
}
}
}
| 39.860465 | 122 | 0.486464 | [
"MIT"
] | tedycholakova/StudentSystem | DataLayerr/Migrations/20190123074046_Kur.cs | 8,572 | C# |
using Microsoft.EntityFrameworkCore;
namespace EShop.DataLayer.Context;
public interface IUnitOfWork : IDisposable
{
DbSet<TEntity> Set<TEntity>() where TEntity : class;
void MarkAsDeleted<TEntity>(TEntity entity);
int SaveChanges();
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
| 22.2 | 78 | 0.762763 | [
"MIT"
] | pShariiati/EShop | src/EShop.DataLayer/Context/IUnitOfWork.cs | 335 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.FSx")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.103.11")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 51.610169 | 232 | 0.777011 | [
"Apache-2.0"
] | dorki/aws-sdk-net | sdk/src/Services/FSx/Properties/AssemblyInfo.cs | 3,045 | C# |
using EventBusRabbitMQ;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using POC.OpenTelemetry.API.Helpers;
namespace POC.OpenTelemetry.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("poc-opentelemetry");
services
.AddControllers()
.Services
.AddSingleton<MessageSender>()
.AddDatabaseContext(connectionString)
.AddCustomSwagger()
.AddCustomOpenTelemetry(); // Open Telemetry configuration
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime hostApplicationLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "POC.OpenTelemetry.API v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 29.545455 | 129 | 0.610462 | [
"MIT"
] | jesuscorral/poc-opentelemetry | POC.OpenTelemetry.API/Startup.cs | 1,625 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace System.Data.Cobber
{
/// <summary>
/// 应用文件配置
/// </summary>
public abstract class AppConfigJsonFile
{
/// <summary>
/// 资源字典
/// </summary>
public ConcurrentDictionary<string, string> ResDic { get; } = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 文件监听
/// </summary>
protected FileSystemWatcher FileWatcher { get; }
/// <summary>
/// 文件路径
/// </summary>
protected string FilePath { get; }
/// <summary>
/// 安全码
/// </summary>
protected string SecurityKey { get; }
/// <summary>
/// 不加密构造
/// </summary>
/// <param name="filePath"></param>
protected AppConfigJsonFile(string filePath) : this(filePath, string.Empty) { }
/// <summary>
/// 构造
/// </summary>
protected AppConfigJsonFile(string filePath,string securityKey)
{
FilePath = filePath;
SecurityKey = securityKey;
var fileWatcher = new FileSystemWatcher();
try
{
//初始化监听
fileWatcher.BeginInit();
//设置监听的路径
fileWatcher.Path = System.IO.Path.GetDirectoryName(filePath);
//设置监听文件类型
fileWatcher.Filter = System.IO.Path.GetFileName(filePath);
//设置是否监听子目录
fileWatcher.IncludeSubdirectories = false;
//设置是否启用监听?
fileWatcher.EnableRaisingEvents = true;
//设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
fileWatcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
//注册创建文件或目录时的监听事件
//watcher.Created += new FileSystemEventHandler(watch_created);
//注册当指定目录的文件或者目录发生改变的时候的监听事件
fileWatcher.Changed += new FileSystemEventHandler((sender, e) => LoadConfigFile());
//注册当删除目录的文件或者目录的时候的监听事件
fileWatcher.Deleted += new FileSystemEventHandler((sender, e) => TrySave());
//当指定目录的文件或者目录发生重命名的时候的监听事件
//fileWatcher.Renamed += new RenamedEventHandler((sender, e) =>
//{
// if (!File.Exists(FilePath)) { Save(); }
//});
//结束初始化
fileWatcher.EndInit();
}
catch (Exception ex) { Console.WriteLine(ex); }
FileWatcher = fileWatcher;
LoadingDefault();
LoadConfigFile();
}
/// <summary>
/// 加载默认
/// </summary>
protected virtual void LoadingDefault()
{
var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (var prop in properties)
{
try
{
ResDic[prop.Name] = prop.GetValue(null, null).ToString();
}
catch { }
}
}
/// <summary>
/// 加载配置
/// </summary>
protected virtual void LoadConfigFile()
{
if (!System.IO.File.Exists(FilePath))
{
TrySave();
return;
}
try
{
var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(FilePath));
var isEncrypt = !string.IsNullOrEmpty(SecurityKey);
var type = GetType();
foreach (var item in dic)
{
try
{
var prop = type.GetProperty(item.Key);
if (prop != null && prop.CanWrite)
{
var value = item.Value;
if (isEncrypt)
{
value = UserCrypto.GetAesDecrypt(item.Value, SecurityKey);
}
prop.SetValue(null, value, null);
ResDic[item.Key] = value;
}
}
catch (Exception) { }
}
}
catch (Exception ex) { Console.WriteLine(ex); }
}
/// <summary>
/// 保存到文件
/// </summary>
public virtual void TrySave()
{
try
{
FileWatcher.EnableRaisingEvents = false;
File.WriteAllText(FilePath, ResDic.GetJsonFormatString());
FileWatcher.EnableRaisingEvents = true;
}
catch (Exception ex) { Console.WriteLine(ex); }
}
/// <summary>
/// 获取字典值
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
protected virtual string Get(string property)
{
if (ResDic.TryGetValue(property, out string value))
{
return value;
}
return property ?? string.Empty;
}
/// <summary>
/// 获取字典值
/// </summary>
/// <param name="content"></param>
/// <param name="args"></param>
/// <returns></returns>
protected virtual String Get(string content, params string[] args)
{
return Get(string.Format(content, args));
}
}
}
| 34.840237 | 251 | 0.4893 | [
"MIT"
] | erikzhouxin/NDabber | src/Cobber/Crypto/AppConfigJsonFile.cs | 6,328 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCT.NUI.Core;
namespace CCT.NUI.HandTracking.Mouse
{
public interface ICursorMode
{
bool HasPoint(HandCollection handData);
Point GetPoint(HandCollection handData);
CursorMode EnumValue { get; }
}
}
| 18.388889 | 48 | 0.706949 | [
"BSD-3-Clause"
] | an83/KinectTouch2 | CCT.NUI.HandTracking/Mouse/ICursorMode.cs | 333 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Dematt.Airy.ApplicationInsights.Sample.Areas.HelpPage.ModelDescriptions
{
public class ParameterDescription
{
public ParameterDescription()
{
Annotations = new Collection<ParameterAnnotation>();
}
public Collection<ParameterAnnotation> Annotations { get; private set; }
public string Documentation { get; set; }
public string Name { get; set; }
public ModelDescription TypeDescription { get; set; }
}
} | 27.095238 | 81 | 0.68717 | [
"MIT"
] | MatthewRudolph/Airy-ApplicationInsights-Owin | samples/Dematt.Airy.ApplicationInsights.Sample/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs | 569 | C# |
using System;
using System.Threading.Tasks;
using Template10.Mvvm;
using Windows.UI.Xaml;
namespace HamburgerUI.ViewModels
{
public class AboutPartViewModel : ViewModelBase
{
public string DisplayName => Windows.ApplicationModel.Package.Current.DisplayName;
public Uri Logo => Windows.ApplicationModel.Package.Current.Logo;
public string Publisher => Windows.ApplicationModel.Package.Current.PublisherDisplayName;
public Uri RateMe => new Uri("http://aka.ms/template10");
public string Version
{
get
{
var v = Windows.ApplicationModel.Package.Current.Id.Version;
return $"{v.Major}.{v.Minor}.{v.Build}.{v.Revision}";
}
}
}
public class SettingsPageViewModel : ViewModelBase
{
public AboutPartViewModel AboutPartViewModel { get; } = new AboutPartViewModel();
public SettingsPartViewModel SettingsPartViewModel { get; } = new SettingsPartViewModel();
}
public class SettingsPartViewModel : ViewModelBase
{
private string _BusyText = "Please wait...";
private Services.SettingsServices.SettingsService _settings;
private DelegateCommand _ShowBusyCommand;
public SettingsPartViewModel()
{
if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
// designtime
}
else
{
_settings = Services.SettingsServices.SettingsService.Instance;
}
}
public string BusyText
{
get { return _BusyText; }
set
{
Set(ref _BusyText, value);
_ShowBusyCommand.RaiseCanExecuteChanged();
}
}
public bool IsFullScreen
{
get { return _settings.IsFullScreen; }
set
{
_settings.IsFullScreen = value;
base.RaisePropertyChanged();
if (value)
{
ShowHamburgerButton = false;
}
else
{
ShowHamburgerButton = true;
}
}
}
public DelegateCommand ShowBusyCommand
=> _ShowBusyCommand ?? (_ShowBusyCommand = new DelegateCommand(async () =>
{
Views.Busy.SetBusy(true, _BusyText);
await Task.Delay(5000);
Views.Busy.SetBusy(false);
}, () => !string.IsNullOrEmpty(BusyText)));
public bool ShowHamburgerButton
{
get { return _settings.ShowHamburgerButton; }
set { _settings.ShowHamburgerButton = value; base.RaisePropertyChanged(); }
}
public bool UseLightThemeButton
{
get { return _settings.AppTheme.Equals(ApplicationTheme.Light); }
set { _settings.AppTheme = value ? ApplicationTheme.Light : ApplicationTheme.Dark; base.RaisePropertyChanged(); }
}
public bool UseShellBackButton
{
get { return _settings.UseShellBackButton; }
set { _settings.UseShellBackButton = value; base.RaisePropertyChanged(); }
}
}
} | 31.304762 | 125 | 0.567995 | [
"MIT"
] | McFunston/FileCatalogUI | HamburgerUI/ViewModels/SettingsPageViewModel.cs | 3,287 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using AdventureWorks.BaseDomain.Enums;
using AdventureWorks.BaseDomain.Interfaces;
using AdventureWorks.BaseDomain.CustomTypes;
using AdventureWorks.BaseDomain.Entities.Production;
namespace AdventureWorks.Domain.Entities.Production
{
public partial class ProductCostHistory : BaseProductCostHistory, ILogging
{
[Required]
[StringLength(200)]
public string ModifiedBy { get; set; }
[Column(TypeName = "datetime")]
public DateTime ModifiedAt { get; set; }
#region Navigation Properties
public Product Product { get; set; }
#endregion
}
} | 26.344828 | 78 | 0.736911 | [
"Unlicense"
] | CodeSwifterGit/adventure-works | src/AdventureWorks.Domain/Entities/Production/ProductCostHistory.cs | 764 | C# |
// Copyright (c) Amer Koleci and contributors.
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
namespace Vortice.Graphics
{
/// <summary>
/// Describes the front-facing or back-facing stencil operations of <see cref="DepthStencilDescriptor"/>.
/// </summary>
public struct DepthStencilOperationDescriptor
{
/// <summary>
/// A <see cref="StencilOperation"/> value that identifies the stencil operation to perform when stencil testing fails.
/// </summary>
public StencilOperation StencilFailOperation;
/// <summary>
/// A <see cref="StencilOperation"/> value that identifies the stencil operation to perform when stencil testing passes and depth testing fails.
/// </summary>
public StencilOperation StencilDepthFailOperation;
/// <summary>
/// A <see cref="StencilOperation"/> value that identifies the stencil operation to perform when stencil testing and depth testing both pass.
/// </summary>
public StencilOperation StencilPassOperation;
/// <summary>
/// A <see cref="CompareFunction"/> value that identifies the function that compares stencil data against existing stencil data.
/// </summary>
public CompareFunction StencilCompareFunction;
/// <summary>
/// A built-in description with default values.
/// </summary>
public static readonly DepthStencilOperationDescriptor Default = new DepthStencilOperationDescriptor(
StencilOperation.Keep, StencilOperation.Keep, StencilOperation.Keep, CompareFunction.Always);
/// <summary>
/// Initializes a new instance of the <see cref="DepthStencilOperationDescriptor"/> struct.
/// </summary>
/// <param name="stencilFailOperation">A <see cref="StencilOperation"/> value that identifies the stencil operation to perform when stencil testing fails.</param>
/// <param name="stencilDepthFailOperation">A <see cref="StencilOperation"/> value that identifies the stencil operation to perform when stencil testing passes and depth testing fails.</param>
/// <param name="stencilPassOperation">A <see cref="StencilOperation"/> value that identifies the stencil operation to perform when stencil testing and depth testing both pass.</param>
/// <param name="stencilCompareFunction">A <see cref="CompareFunction"/> value that identifies the function that compares stencil data against existing stencil data.</param>
public DepthStencilOperationDescriptor(
StencilOperation stencilFailOperation,
StencilOperation stencilDepthFailOperation,
StencilOperation stencilPassOperation,
CompareFunction stencilCompareFunction)
{
StencilFailOperation = stencilFailOperation;
StencilDepthFailOperation = stencilDepthFailOperation;
StencilPassOperation = stencilPassOperation;
StencilCompareFunction = stencilCompareFunction;
}
}
}
| 54.280702 | 200 | 0.700711 | [
"MIT"
] | cagr301/engine | src/engine/Vortice.Graphics/DepthStencilOperationDescriptor.cs | 3,096 | C# |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Models.Markov.Hybrid
{
using System;
using Accord.Math;
/// <summary>
/// General Markov function for arbitrary state-emission density definitions.
/// </summary>
///
/// <param name="previous">The previous state index.</param>
/// <param name="observation">The observation at the current state.</param>
/// <returns>An array containing the values for the observations in each next possible state.</returns>
///
public delegate double[] GeneralMarkovFunction(int previous, double[] observation);
/// <summary>
/// Hybrid Markov model for arbitrary state-observation functions.
/// </summary>
///
/// <remarks>
/// This class can be used to implement HMM hybrids such as ANN-HMM
/// or SVM-HMMs through the specification of a custom <see cref="GeneralMarkovFunction"/>.
/// </remarks>
///
public class HybridMarkovModel
{
/// <summary>
/// Gets the Markov function, which takes the previous state, the
/// next state and a observation and produces a probability value.
/// </summary>
///
public GeneralMarkovFunction Function { get; private set; }
/// <summary>
/// Gets the number of states in the model.
/// </summary>
///
public int States { get; private set; }
/// <summary>
/// Gets the number of dimensions of the
/// observations handled by this model.
/// </summary>
///
public int Dimension { get; private set; }
/// <summary>
/// Gets or sets an user-defined object associated with this model.
/// </summary>
///
public object Tag { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="HybridMarkovModel"/> class.
/// </summary>
///
/// <param name="function">A function specifying a probability for a transition-emission pair.</param>
/// <param name="states">The number of states in the model.</param>
/// <param name="dimension">The number of dimensions in the model.</param>
///
public HybridMarkovModel(GeneralMarkovFunction function, int states, int dimension)
{
this.Function = function;
this.States = states;
this.Dimension = dimension;
}
/// <summary>
/// Calculates the most likely sequence of hidden states
/// that produced the given observation sequence.
/// </summary>
/// <remarks>
/// Decoding problem. Given the HMM M = (A, B, pi) and the observation sequence
/// O = {o1,o2, ..., oK}, calculate the most likely sequence of hidden states Si
/// that produced this observation sequence O. This can be computed efficiently
/// using the Viterbi algorithm.
/// </remarks>
/// <param name="observations">
/// A sequence of observations.</param>
/// <param name="logLikelihood">
/// The state optimized probability.</param>
/// <returns>
/// The sequence of states that most likely produced the sequence.
/// </returns>
///
public int[] Decode(double[][] observations, out double logLikelihood)
{
if (observations == null)
throw new ArgumentNullException("observations");
if (observations.Length == 0)
{
logLikelihood = Double.NegativeInfinity;
return new int[0];
}
// Viterbi-forward algorithm.
int T = observations.Length;
int states = States;
int maxState;
double maxWeight;
double weight;
int[,] s = new int[states, T];
double[,] lnFwd = new double[states, T];
double[][] output = new double[states][];
// Base
output[0] = Function(-1, observations[0]);
for (int i = 0; i < states; i++)
lnFwd[i, 0] = output[0][i];
// Induction
for (int t = 1; t < T; t++)
{
double[] observation = observations[t];
for (int i = 0; i < States; i++)
output[i] = Function(i, observation);
for (int j = 0; j < states; j++)
{
maxState = 0;
maxWeight = lnFwd[0, t - 1] + output[0][j];
for (int i = 1; i < states; i++)
{
weight = lnFwd[i, t - 1] + output[i][j];
if (weight > maxWeight)
{
maxState = i;
maxWeight = weight;
}
}
lnFwd[j, t] = maxWeight;
s[j, t] = maxState;
}
}
// Find maximum value for time T-1
maxState = 0;
maxWeight = lnFwd[0, T - 1];
for (int i = 1; i < states; i++)
{
if (lnFwd[i, T - 1] > maxWeight)
{
maxState = i;
maxWeight = lnFwd[i, T - 1];
}
}
// Trackback
int[] path = new int[T];
path[T - 1] = maxState;
for (int t = T - 2; t >= 0; t--)
path[t] = s[path[t + 1], t + 1];
// Returns the sequence probability as an out parameter
logLikelihood = maxWeight;
// Returns the most likely (Viterbi path) for the given sequence
return path;
}
/// <summary>
/// Calculates the probability that this model has generated the given sequence.
/// </summary>
/// <remarks>
/// Evaluation problem. Given the HMM M = (A, B, pi) and the observation
/// sequence O = {o1, o2, ..., oK}, calculate the probability that model
/// M has generated sequence O. This can be computed efficiently using the
/// Forward algorithm. </remarks>
/// <param name="observations">
/// A sequence of observations. </param>
/// <returns>
/// The probability that the given sequence has been generated by this model.
/// </returns>
///
public double Evaluate(double[][] observations)
{
int T = observations.Length;
double[,] lnFwd = new double[States, T];
double[][] output = new double[States][];
// 1. Initialization
output[0] = Function(-1, observations[0]);
for (int i = 0; i < States; i++)
lnFwd[0, i] = Math.Log(output[0][i]);
// 2. Induction
for (int t = 1; t < T; t++)
{
double[] x = observations[t];
for (int i = 0; i < States; i++)
output[i] = Function(i, x);
for (int i = 0; i < States; i++)
{
double sum = Double.NegativeInfinity;
for (int j = 0; j < States; j++)
sum = Special.LogSum(sum, lnFwd[t - 1, j] + output[j][i]);
lnFwd[t, i] = sum;
}
}
double logLikelihood = Double.NegativeInfinity;
for (int i = 0; i < States; i++)
logLikelihood = Special.LogSum(logLikelihood, lnFwd[T - 1, i]);
return logLikelihood;
}
}
}
| 35.6 | 111 | 0.499213 | [
"MIT"
] | kpandya3/WakeUpWithKinect | Accord.NET projects/Accord.Statistics/Models/Markov/Hybrid/HybridMarkovModel.cs | 8,904 | C# |
using System;
using Microsoft.AspNet.Identity;
using essentialMix.Web.Mvc.Controllers;
namespace essentialMix.Web.Mvc.Views;
public abstract class WebViewPage<TModel, TKey, TUser, TUserManager, TController> : System.Web.Mvc.WebViewPage<TModel>
where TKey : IEquatable<TKey>
where TUser : class, IUser<TKey>
where TUserManager : UserManager<TUser, TKey>
where TController : Controller<TKey, TUser, TUserManager>
{
protected WebViewPage()
{
}
//public override void InitHelpers()
//{
// base.InitHelpers();
// // initialize any helpers here
//}
public TController Controller => (TController)ViewContext.Controller;
public bool IsRightToLeft => Controller.IsRightToLeft;
}
public abstract class WebViewPage<TModel, TUser, TUserManager, TController> : WebViewPage<TModel, string, TUser, TUserManager, TController>
where TUser : class, IUser<string>
where TUserManager : UserManager<TUser>
where TController : Controller<TUser, TUserManager>
{
protected WebViewPage() { }
}
public abstract class WebViewPage<TModel, TUserManager, TController> : WebViewPage<TModel, IUser<string>, TUserManager, TController>
where TUserManager : UserManager<IUser<string>>
where TController : Controller<TUserManager>
{
protected WebViewPage() { }
}
public abstract class WebViewPage<TModel, TController> : WebViewPage<TModel, UserManager<IUser<string>>, TController>
where TController : Controller<UserManager<IUser<string>>>
{
protected WebViewPage() { }
}
public abstract class WebViewPage<TModel> : WebViewPage<TModel, Controller>
{
protected WebViewPage() { }
}
public abstract class WebViewPage : WebViewPage<object>
{
protected WebViewPage() { }
} | 29.245614 | 139 | 0.770846 | [
"MIT"
] | asm2025/essentialMix | Framework/essentialMix.Web.Mvc/Views/WebViewPage.cs | 1,669 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slime : GenericMonster {
public Sprite[] sprites;
private int tickCounter;
private int previousSlimeTile = 0;
private int newSlimeTile = 0;
private SpriteRenderer sr;
private bool isAttacking = false;
// Use this for initialization
void Start ()
{
SetHealth(5);
sr = GetComponent<SpriteRenderer>();
tickCounter = SetMonsterTickCounter();
}
void OnTick()
{
tickCounter++;
switch (tickCounter)
{
case -1:
case 0:
sr.sprite = sprites[0];
break;
case 1:
sr.sprite = sprites[1];
break;
case 2:
sr.sprite = sprites[2];
SpawnProjectile();
break;
case 3:
case 4:
sr.sprite = sprites[0];
break;
case 5:
sr.sprite = sprites[1];
break;
case 6:
sr.sprite = sprites[2];
SpawnProjectile();
break;
case 7:
sr.sprite = sprites[0];
tickCounter = -1;
break;
}
}
void SpawnProjectile()
{
GameObject projectile = (GameObject)Instantiate(Resources.Load("Slime Projectile"));
projectile.transform.parent = GameObject.Find("World").transform;
projectile.transform.position = transform.position;
projectile.GetComponent<SpriteRenderer>().color = GetComponent<SpriteRenderer>().color;
FindSlimeTile();
projectile.GetComponent<SlimeProjectile>().FireSlime(GameObject.Find("Floor Tile " + newSlimeTile));
previousSlimeTile = newSlimeTile;
}
void FindSlimeTile()
{
newSlimeTile = Random.Range(0, 11);
if (newSlimeTile == previousSlimeTile)
{
FindSlimeTile();
}
else
{
GameObject.Find("Floor Tile " + newSlimeTile).GetComponent<TileChangeListener>().Warn("Magic");
}
}
void MonsterDeath()
{
monsterDeathVal.UpdateMonsterPoints("Slime");
stats.AddToMonstersDefeated(1);
}
}
| 25.472527 | 108 | 0.534944 | [
"MIT"
] | Caseyfam/Rhythm-Project | Assets/Scripts/InGame/Monster Entities/Slime/Slime.cs | 2,320 | C# |
using UnityEngine;
[System.Serializable]
public class Wave {
public Transform enemy;
public int count;
public float rate;
// public int health;
} | 13.818182 | 24 | 0.743421 | [
"Unlicense"
] | Dark3nforce/TowerDefenseSurvival | Assets/Scripts/Wave.cs | 152 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
public partial class CouchbaseLinkedService : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
if (Optional.IsDefined(ConnectVia))
{
writer.WritePropertyName("connectVia");
writer.WriteObjectValue(ConnectVia);
}
if (Optional.IsDefined(Description))
{
writer.WritePropertyName("description");
writer.WriteStringValue(Description);
}
if (Optional.IsCollectionDefined(Parameters))
{
writer.WritePropertyName("parameters");
writer.WriteStartObject();
foreach (var item in Parameters)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
if (Optional.IsCollectionDefined(Annotations))
{
writer.WritePropertyName("annotations");
writer.WriteStartArray();
foreach (var item in Annotations)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
writer.WritePropertyName("typeProperties");
writer.WriteStartObject();
if (Optional.IsDefined(ConnectionString))
{
writer.WritePropertyName("connectionString");
writer.WriteObjectValue(ConnectionString);
}
if (Optional.IsDefined(CredString))
{
writer.WritePropertyName("credString");
writer.WriteObjectValue(CredString);
}
if (Optional.IsDefined(EncryptedCredential))
{
writer.WritePropertyName("encryptedCredential");
writer.WriteObjectValue(EncryptedCredential);
}
writer.WriteEndObject();
foreach (var item in AdditionalProperties)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
internal static CouchbaseLinkedService DeserializeCouchbaseLinkedService(JsonElement element)
{
string type = default;
Optional<IntegrationRuntimeReference> connectVia = default;
Optional<string> description = default;
Optional<IDictionary<string, ParameterSpecification>> parameters = default;
Optional<IList<object>> annotations = default;
Optional<object> connectionString = default;
Optional<AzureKeyVaultSecretReference> credString = default;
Optional<object> encryptedCredential = default;
IDictionary<string, object> additionalProperties = default;
Dictionary<string, object> additionalPropertiesDictionary = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("connectVia"))
{
connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value);
continue;
}
if (property.NameEquals("description"))
{
description = property.Value.GetString();
continue;
}
if (property.NameEquals("parameters"))
{
Dictionary<string, ParameterSpecification> dictionary = new Dictionary<string, ParameterSpecification>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value));
}
parameters = dictionary;
continue;
}
if (property.NameEquals("annotations"))
{
List<object> array = new List<object>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(item.GetObject());
}
annotations = array;
continue;
}
if (property.NameEquals("typeProperties"))
{
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("connectionString"))
{
connectionString = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("credString"))
{
credString = AzureKeyVaultSecretReference.DeserializeAzureKeyVaultSecretReference(property0.Value);
continue;
}
if (property0.NameEquals("encryptedCredential"))
{
encryptedCredential = property0.Value.GetObject();
continue;
}
}
continue;
}
additionalPropertiesDictionary ??= new Dictionary<string, object>();
additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
}
additionalProperties = additionalPropertiesDictionary;
return new CouchbaseLinkedService(type, connectVia.Value, description.Value, Optional.ToDictionary(parameters), Optional.ToList(annotations), additionalProperties, connectionString.Value, credString.Value, encryptedCredential.Value);
}
}
}
| 41.929936 | 245 | 0.532888 | [
"MIT"
] | amolagar5/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/CouchbaseLinkedService.Serialization.cs | 6,583 | C# |
/*
Problem 7. Quotes in Strings
• Declare two string variables and assign them with following value: The "use" of quotations causes difficulties.
• Do the above in two different ways - with and without using quoted strings.
• Print the variables to ensure that their value was correctly defined.
*/
using System;
class QuotesInStrings
{
static void Main()
{
string withQuotes = @"The ""use"" of quotations causes difficulties.";
Console.WriteLine(withQuotes);
string withOutQuotes = "The \"use\" of quotations causes difficulties.";
Console.WriteLine(withOutQuotes);
}
} | 33.263158 | 120 | 0.696203 | [
"MIT"
] | mpenchev86/Telerik-Academy | CSharp-Part1/Primitive-Data-Types-And-Variables-Homework/07-QuotesInStrings/QuotesInStrings.cs | 640 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringArgs : Pulumi.ResourceArgs
{
public WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringArgs()
{
}
}
}
| 34.45 | 165 | 0.791001 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringArgs.cs | 689 | C# |
namespace DecoratorExample
{
public class Footballer: ISport
{
public virtual int Run()
{
return 1;
}
}
} | 15.4 | 35 | 0.506494 | [
"MIT"
] | andreidana/DecoratorPattern | DecoratorExample/Footballer.cs | 156 | C# |
using Relo;
using SageBinaryData;
public static partial class Marshaler
{
public static unsafe void Marshal(Node node, BeamTargetModuleData* objT, Tracker state)
{
if (node is null)
{
return;
}
Marshal(node, (BehaviorModuleData*)objT, state);
}
}
| 20.333333 | 91 | 0.622951 | [
"MIT"
] | Qibbi/BinaryAssetBuilder | source/BinaryAssetBuilder.XmlCompiler/Marshaler.ModulesBeamTargetModule.cs | 307 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
namespace fastJSON
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
internal class JsonParser
{
private const int TOKEN_NONE = 0;
private const int TOKEN_CURLY_OPEN = 1;
private const int TOKEN_CURLY_CLOSE = 2;
private const int TOKEN_SQUARED_OPEN = 3;
private const int TOKEN_SQUARED_CLOSE = 4;
private const int TOKEN_COLON = 5;
private const int TOKEN_COMMA = 6;
private const int TOKEN_STRING = 7;
private const int TOKEN_NUMBER = 8;
private const int TOKEN_TRUE = 9;
private const int TOKEN_FALSE = 10;
private const int TOKEN_NULL = 11;
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a dictionary, a double, a string, null, true, or false</returns>
internal static object JsonDecode(string json)
{
bool success = true;
return JsonDecode(json, ref success);
}
/// <summary>
/// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
/// </summary>
/// <param name="json">A JSON string.</param>
/// <param name="success">Successful parse?</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
private static object JsonDecode(string json, ref bool success)
{
success = true;
if (json != null) {
char[] charArray = json.ToCharArray();
int index = 0;
object value = ParseValue(charArray, ref index, ref success);
return value;
} else {
return null;
}
}
protected static Dictionary<string,object> ParseObject(char[] json, ref int index, ref bool success)
{
Dictionary<string,object> table = new Dictionary<string, object>();
int token;
// {
NextToken(json, ref index);
bool done = false;
while (!done) {
token = LookAhead(json, index);
if (token == TOKEN_NONE) {
success = false;
return null;
} else if (token == TOKEN_COMMA) {
NextToken(json, ref index);
} else if (token == TOKEN_CURLY_CLOSE) {
NextToken(json, ref index);
return table;
} else {
// name
string name = ParseString(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != TOKEN_COLON) {
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
protected static ArrayList ParseArray(char[] json, ref int index, ref bool success)
{
ArrayList array = new ArrayList();
NextToken(json, ref index);
bool done = false;
while (!done) {
int token = LookAhead(json, index);
if (token == TOKEN_NONE) {
success = false;
return null;
} else if (token == TOKEN_COMMA) {
NextToken(json, ref index);
} else if (token == TOKEN_SQUARED_CLOSE) {
NextToken(json, ref index);
break;
} else {
object value = ParseValue(json, ref index, ref success);
if (!success) {
return null;
}
array.Add(value);
}
}
return array;
}
protected static object ParseValue(char[] json, ref int index, ref bool success)
{
switch (LookAhead(json, index)) {
case TOKEN_NUMBER:
return ParseNumber(json, ref index, ref success);
case TOKEN_STRING:
return ParseString(json, ref index, ref success);
case TOKEN_CURLY_OPEN:
return ParseObject(json, ref index, ref success);
case TOKEN_SQUARED_OPEN:
return ParseArray(json, ref index, ref success);
case TOKEN_TRUE:
NextToken(json, ref index);
return true;
case TOKEN_FALSE:
NextToken(json, ref index);
return false;
case TOKEN_NULL:
NextToken(json, ref index);
return null;
case TOKEN_NONE:
break;
}
success = false;
return null;
}
protected static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder();
char c;
EatWhitespace(json, ref index);
// "
c = json[index++];
bool complete = false;
while (!complete) {
if (index == json.Length) {
break;
}
c = json[index++];
if (c == '"') {
complete = true;
break;
} else if (c == '\\') {
if (index == json.Length) {
break;
}
c = json[index++];
if (c == '"') {
s.Append('"');
} else if (c == '\\') {
s.Append('\\');
} else if (c == '/') {
s.Append('/');
} else if (c == 'b') {
s.Append('\b');
} else if (c == 'f') {
s.Append('\f');
} else if (c == 'n') {
s.Append('\n');
} else if (c == 'r') {
s.Append('\r');
} else if (c == 't') {
s.Append('\t');
} else if (c == 'u') {
int remainingLength = json.Length - index;
if (remainingLength >= 4) {
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) {
return "";
}
// convert the integer codepoint to a unicode char and add to string
s.Append(Char.ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
} else {
break;
}
}
} else {
s.Append(c);
}
}
if (!complete) {
success = false;
return null;
}
return s.ToString();
}
protected static string ParseNumber(char[] json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
string number = new string(json,index,charLength);
success = true;
index = lastIndex + 1;
return number;
}
protected static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++) {
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) {
break;
}
}
return lastIndex - 1;
}
protected static void EatWhitespace(char[] json, ref int index)
{
for (; index < json.Length; index++) {
if (" \t\n\r".IndexOf(json[index]) == -1) {
break;
}
}
}
protected static int LookAhead(char[] json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
protected static int NextToken(char[] json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length) {
return TOKEN_NONE;
}
char c = json[index];
index++;
switch (c) {
case '{':
return TOKEN_CURLY_OPEN;
case '}':
return TOKEN_CURLY_CLOSE;
case '[':
return TOKEN_SQUARED_OPEN;
case ']':
return TOKEN_SQUARED_CLOSE;
case ',':
return TOKEN_COMMA;
case '"':
return TOKEN_STRING;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '-':
return TOKEN_NUMBER;
case ':':
return TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5) {
if (json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e') {
index += 5;
return TOKEN_FALSE;
}
}
// true
if (remainingLength >= 4) {
if (json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e') {
index += 4;
return TOKEN_TRUE;
}
}
// null
if (remainingLength >= 4) {
if (json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l') {
index += 4;
return TOKEN_NULL;
}
}
return TOKEN_NONE;
}
protected static bool SerializeValue(object value, StringBuilder builder)
{
bool success = true;
if (value is string) {
success = SerializeString((string)value, builder);
} else if (value is Hashtable) {
success = SerializeObject((Hashtable)value, builder);
} else if (value is ArrayList) {
success = SerializeArray((ArrayList)value, builder);
} else if (IsNumeric(value)) {
success = SerializeNumber(Convert.ToDouble(value), builder);
} else if ((value is Boolean) && ((Boolean)value == true)) {
builder.Append("true");
} else if ((value is Boolean) && ((Boolean)value == false)) {
builder.Append("false");
} else if (value == null) {
builder.Append("null");
} else {
success = false;
}
return success;
}
protected static bool SerializeObject(Hashtable anObject, StringBuilder builder)
{
builder.Append("{");
IDictionaryEnumerator e = anObject.GetEnumerator();
bool first = true;
while (e.MoveNext()) {
string key = e.Key.ToString();
object value = e.Value;
if (!first) {
builder.Append(", ");
}
SerializeString(key, builder);
builder.Append(":");
if (!SerializeValue(value, builder)) {
return false;
}
first = false;
}
builder.Append("}");
return true;
}
protected static bool SerializeArray(ArrayList anArray, StringBuilder builder)
{
builder.Append("[");
bool first = true;
for (int i = 0; i < anArray.Count; i++) {
object value = anArray[i];
if (!first) {
builder.Append(", ");
}
if (!SerializeValue(value, builder)) {
return false;
}
first = false;
}
builder.Append("]");
return true;
}
protected static bool SerializeString(string aString, StringBuilder builder)
{
builder.Append("\"");
char[] charArray = aString.ToCharArray();
for (int i = 0; i < charArray.Length; i++) {
char c = charArray[i];
if (c == '"') {
builder.Append("\\\"");
} else if (c == '\\') {
builder.Append("\\\\");
} else if (c == '\b') {
builder.Append("\\b");
} else if (c == '\f') {
builder.Append("\\f");
} else if (c == '\n') {
builder.Append("\\n");
} else if (c == '\r') {
builder.Append("\\r");
} else if (c == '\t') {
builder.Append("\\t");
} else {
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
}
}
builder.Append("\"");
return true;
}
protected static bool SerializeNumber(double number, StringBuilder builder)
{
builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture));
return true;
}
protected static bool IsNumeric(object o)
{
double result;
return (o == null) ? false : Double.TryParse(o.ToString(), out result);
}
}
}
| 24.609959 | 140 | 0.560614 | [
"MIT"
] | rogeralsing/linq-to-sqlxml | Source/fastJSON/JsonParser.cs | 11,862 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Resources {
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class IdentityServiceResource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal IdentityServiceResource() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Resources.IdentityServiceResource", typeof(IdentityServiceResource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Error.
/// </summary>
internal static string IdentityErrorKey {
get {
return ResourceManager.GetString("IdentityErrorKey", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role claim with id {0} doesn't exist.
/// </summary>
internal static string RoleClaimDoesNotExist {
get {
return ResourceManager.GetString("RoleClaimDoesNotExist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role Claims creating failed.
/// </summary>
internal static string RoleClaimsCreateFailed {
get {
return ResourceManager.GetString("RoleClaimsCreateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role Claims deleting failed.
/// </summary>
internal static string RoleClaimsDeleteFailed {
get {
return ResourceManager.GetString("RoleClaimsDeleteFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role creating failed.
/// </summary>
internal static string RoleCreateFailed {
get {
return ResourceManager.GetString("RoleCreateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role deleting failed.
/// </summary>
internal static string RoleDeleteFailed {
get {
return ResourceManager.GetString("RoleDeleteFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role with id {0} doesn't exist.
/// </summary>
internal static string RoleDoesNotExist {
get {
return ResourceManager.GetString("RoleDoesNotExist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role updating failed.
/// </summary>
internal static string RoleUpdateFailed {
get {
return ResourceManager.GetString("RoleUpdateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Change Password failed.
/// </summary>
internal static string UserChangePasswordFailed {
get {
return ResourceManager.GetString("UserChangePasswordFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User claim with id {0} doesn't exist.
/// </summary>
internal static string UserClaimDoesNotExist {
get {
return ResourceManager.GetString("UserClaimDoesNotExist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Claims creating failed.
/// </summary>
internal static string UserClaimsCreateFailed {
get {
return ResourceManager.GetString("UserClaimsCreateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Claims deleting failed.
/// </summary>
internal static string UserClaimsDeleteFailed {
get {
return ResourceManager.GetString("UserClaimsDeleteFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User creating failed.
/// </summary>
internal static string UserCreateFailed {
get {
return ResourceManager.GetString("UserCreateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User deleting failed.
/// </summary>
internal static string UserDeleteFailed {
get {
return ResourceManager.GetString("UserDeleteFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User with id {0} doesn't exist.
/// </summary>
internal static string UserDoesNotExist {
get {
return ResourceManager.GetString("UserDoesNotExist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Provider deleting failed.
/// </summary>
internal static string UserProviderDeleteFailed {
get {
return ResourceManager.GetString("UserProviderDeleteFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User provider with id {0} doesn't exist.
/// </summary>
internal static string UserProviderDoesNotExist {
get {
return ResourceManager.GetString("UserProviderDoesNotExist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Role creating failed.
/// </summary>
internal static string UserRoleCreateFailed {
get {
return ResourceManager.GetString("UserRoleCreateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Role deleting failed.
/// </summary>
internal static string UserRoleDeleteFailed {
get {
return ResourceManager.GetString("UserRoleDeleteFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User updating failed.
/// </summary>
internal static string UserUpdateFailed {
get {
return ResourceManager.GetString("UserUpdateFailed", resourceCulture);
}
}
}
}
| 38.676349 | 245 | 0.57172 | [
"MIT"
] | Abhith/IdentityServer4.Admin | src/Skoruba.IdentityServer4.Admin.BusinessLogic.Identity/Resources/IdentityServiceResource.Designer.cs | 9,323 | C# |
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.Reflection;
using Stride.Core.Quantum;
namespace Stride.Core.Presentation.Quantum.Presenters
{
public class MemberNodePresenter : NodePresenterBase
{
protected readonly IMemberNode Member;
private readonly List<Attribute> memberAttributes = new List<Attribute>();
public MemberNodePresenter([NotNull] INodePresenterFactoryInternal factory, IPropertyProviderViewModel propertyProvider, [NotNull] INodePresenter parent, [NotNull] IMemberNode member)
: base(factory, propertyProvider, parent)
{
if (factory == null) throw new ArgumentNullException(nameof(factory));
if (parent == null) throw new ArgumentNullException(nameof(parent));
Member = member ?? throw new ArgumentNullException(nameof(member));
Name = member.Name;
CombineKey = Name;
DisplayName = Name;
IsReadOnly = !Member.MemberDescriptor.HasSet;
memberAttributes.AddRange(TypeDescriptorFactory.Default.AttributeRegistry.GetAttributes(member.MemberDescriptor.MemberInfo));
member.ValueChanging += OnMemberChanging;
member.ValueChanged += OnMemberChanged;
if (member.Target != null)
{
member.Target.ItemChanging += OnItemChanging;
member.Target.ItemChanged += OnItemChanged;
}
var displayAttribute = memberAttributes.OfType<DisplayAttribute>().FirstOrDefault();
Order = displayAttribute?.Order ?? member.MemberDescriptor.Order;
AttachCommands();
}
public override void Dispose()
{
base.Dispose();
Member.ValueChanging -= OnMemberChanging;
Member.ValueChanged -= OnMemberChanged;
if (Member.Target != null)
{
Member.Target.ItemChanging -= OnItemChanging;
Member.Target.ItemChanged -= OnItemChanged;
}
}
public override Type Type => Member.Type;
public override bool IsEnumerable => Member.Target?.IsEnumerable ?? false;
public override NodeIndex Index => NodeIndex.Empty;
[NotNull]
public override ITypeDescriptor Descriptor => Member.Descriptor;
public override object Value => Member.Retrieve();
[NotNull]
public IMemberDescriptor MemberDescriptor => Member.MemberDescriptor;
public IReadOnlyList<Attribute> MemberAttributes => memberAttributes;
protected override IObjectNode ParentingNode => Member.Target;
public override void UpdateValue(object newValue)
{
try
{
Member.Update(newValue);
}
catch (Exception e)
{
throw new NodePresenterException("An error occurred while updating the value of the node, see the inner exception for more information.", e);
}
}
public override void AddItem(object value)
{
if (Member.Target == null || !Member.Target.IsEnumerable)
throw new NodePresenterException($"{nameof(MemberNodePresenter)}.{nameof(AddItem)} cannot be invoked on members that are not collection.");
try
{
Member.Target.Add(value);
}
catch (Exception e)
{
throw new NodePresenterException("An error occurred while adding an item to the node, see the inner exception for more information.", e);
}
}
public override void AddItem(object value, NodeIndex index)
{
if (Member.Target == null || !Member.Target.IsEnumerable)
throw new NodePresenterException($"{nameof(MemberNodePresenter)}.{nameof(AddItem)} cannot be invoked on members that are not collection.");
try
{
Member.Target.Add(value, index);
}
catch (Exception e)
{
throw new NodePresenterException("An error occurred while adding an item to the node, see the inner exception for more information.", e);
}
}
public override void RemoveItem(object value, NodeIndex index)
{
if (Member.Target == null || !Member.Target.IsEnumerable)
throw new NodePresenterException($"{nameof(MemberNodePresenter)}.{nameof(RemoveItem)} cannot be invoked on members that are not collection.");
try
{
Member.Target.Remove(value, index);
}
catch (Exception e)
{
throw new NodePresenterException("An error occurred while removing an item to the node, see the inner exception for more information.", e);
}
}
public override NodeAccessor GetNodeAccessor()
{
return new NodeAccessor(Member, NodeIndex.Empty);
}
private void OnMemberChanging(object sender, MemberNodeChangeEventArgs e)
{
RaiseValueChanging(Value);
if (Member.Target != null)
{
Member.Target.ItemChanging -= OnItemChanging;
Member.Target.ItemChanged -= OnItemChanged;
}
}
private void OnMemberChanged(object sender, MemberNodeChangeEventArgs e)
{
Refresh();
if (Member.Target != null)
{
Member.Target.ItemChanging += OnItemChanging;
Member.Target.ItemChanged += OnItemChanged;
}
RaiseValueChanged(Value);
}
private void OnItemChanging(object sender, ItemChangeEventArgs e)
{
RaiseValueChanging(Value);
}
private void OnItemChanged(object sender, ItemChangeEventArgs e)
{
Refresh();
RaiseValueChanged(Value);
}
}
}
| 37.201183 | 191 | 0.609512 | [
"MIT"
] | Aggror/Stride | sources/presentation/Stride.Core.Presentation.Quantum/Presenters/MemberNodePresenter.cs | 6,287 | C# |
namespace BookShop.DataProcessor.ImportDto
{
public class AuthorBookDTO
{
public int Id { get; set; }
}
} | 18 | 43 | 0.634921 | [
"MIT"
] | amartinn/SoftUni | C# DB May 2020/Entity Framework Core/exams/C# DB Advanced Exam - 13 Dec 2019/BookShop/DataProcessor/ImportDto/AuthorBookDTO.cs | 128 | C# |
// Copyright (C) 2003-2013 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
| 29 | 56 | 0.762931 | [
"MIT"
] | SergeiPavlov/dataobjects-net | Xtensive.Orm.Weaver/Properties/AssemblyInfo.cs | 234 | C# |
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace AdventureWorksModel
{
public class SalesOrderDetailMap : EntityTypeConfiguration<SalesOrderDetail>
{
public SalesOrderDetailMap()
{
// Primary Key
HasKey(t => new { t.SalesOrderID, t.SalesOrderDetailID });
//Ignores
Ignore(t => t.Product);
// Properties
Property(t => t.SalesOrderID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(t => t.SalesOrderDetailID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.CarrierTrackingNumber)
.HasMaxLength(25);
// Table & Column Mappings
ToTable("SalesOrderDetail", "Sales");
Property(t => t.SalesOrderID).HasColumnName("SalesOrderID");
Property(t => t.SalesOrderDetailID).HasColumnName("SalesOrderDetailID");
Property(t => t.CarrierTrackingNumber).HasColumnName("CarrierTrackingNumber");
Property(t => t.OrderQty).HasColumnName("OrderQty");
Property(t => t.ProductID).HasColumnName("ProductID");
Property(t => t.SpecialOfferID).HasColumnName("SpecialOfferID");
Property(t => t.UnitPrice).HasColumnName("UnitPrice");
Property(t => t.UnitPriceDiscount).HasColumnName("UnitPriceDiscount");
Property(t => t.LineTotal).HasColumnName("LineTotal").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Property(t => t.rowguid).HasColumnName("rowguid");
Property(t => t.ModifiedDate).HasColumnName("ModifiedDate").IsConcurrencyToken(false);
// Relationships
HasRequired(t => t.SalesOrderHeader)
.WithMany(t => t.Details)
.HasForeignKey(d => d.SalesOrderID);
HasRequired(t => t.SpecialOfferProduct).WithMany().HasForeignKey(t => new { t.SpecialOfferID, t.ProductID });
}
}
}
| 42.510204 | 127 | 0.631781 | [
"Apache-2.0"
] | Giovanni-Russo-Boscoli/NakedObjectsFramework | Samples/AWFunctional/Mapping/SalesOrderDetailMap.cs | 2,083 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class CosmosValueConverterCompensatingExpressionVisitor : ExpressionVisitor
{
private readonly ISqlExpressionFactory _sqlExpressionFactory;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public CosmosValueConverterCompensatingExpressionVisitor(
ISqlExpressionFactory sqlExpressionFactory)
{
_sqlExpressionFactory = sqlExpressionFactory;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExtension(Expression extensionExpression)
=> extensionExpression switch
{
ShapedQueryExpression shapedQueryExpression => VisitShapedQueryExpression(shapedQueryExpression),
ReadItemExpression readItemExpression => readItemExpression,
SelectExpression selectExpression => VisitSelect(selectExpression),
SqlConditionalExpression sqlConditionalExpression => VisitSqlConditional(sqlConditionalExpression),
_ => base.VisitExtension(extensionExpression)
};
private Expression VisitShapedQueryExpression(ShapedQueryExpression shapedQueryExpression)
{
var selectExpression = shapedQueryExpression.QueryExpression;
var updatedSelectExpression = Visit(selectExpression);
return updatedSelectExpression != selectExpression
? shapedQueryExpression.Update(
updatedSelectExpression,
ReplacingExpressionVisitor.Replace(
selectExpression, updatedSelectExpression, shapedQueryExpression.ShaperExpression))
: shapedQueryExpression;
}
private Expression VisitSelect(SelectExpression selectExpression)
{
var changed = false;
var projections = new List<ProjectionExpression>();
foreach (var item in selectExpression.Projection)
{
var updatedProjection = (ProjectionExpression)Visit(item);
projections.Add(updatedProjection);
changed |= updatedProjection != item;
}
var fromExpression = (RootReferenceExpression)Visit(selectExpression.FromExpression);
changed |= fromExpression != selectExpression.FromExpression;
var predicate = TryCompensateForBoolWithValueConverter((SqlExpression)Visit(selectExpression.Predicate));
changed |= predicate != selectExpression.Predicate;
var orderings = new List<OrderingExpression>();
foreach (var ordering in selectExpression.Orderings)
{
var orderingExpression = (SqlExpression)Visit(ordering.Expression);
changed |= orderingExpression != ordering.Expression;
orderings.Add(ordering.Update(orderingExpression));
}
var limit = (SqlExpression)Visit(selectExpression.Limit);
var offset = (SqlExpression)Visit(selectExpression.Offset);
return changed
? selectExpression.Update(projections, fromExpression, predicate, orderings, limit, offset)
: selectExpression;
}
private Expression VisitSqlConditional(SqlConditionalExpression sqlConditionalExpression)
{
var test = TryCompensateForBoolWithValueConverter((SqlExpression)Visit(sqlConditionalExpression.Test));
var ifTrue = (SqlExpression)Visit(sqlConditionalExpression.IfTrue);
var ifFalse = (SqlExpression)Visit(sqlConditionalExpression.IfFalse);
return sqlConditionalExpression.Update(test, ifTrue, ifFalse);
}
private SqlExpression TryCompensateForBoolWithValueConverter(SqlExpression sqlExpression)
{
if (sqlExpression is KeyAccessExpression keyAccessExpression
&& keyAccessExpression.TypeMapping!.ClrType == typeof(bool)
&& keyAccessExpression.TypeMapping!.Converter != null)
{
return _sqlExpressionFactory.Equal(
sqlExpression,
_sqlExpressionFactory.Constant(true, sqlExpression.TypeMapping));
}
if (sqlExpression is SqlUnaryExpression sqlUnaryExpression)
{
return sqlUnaryExpression.Update(
TryCompensateForBoolWithValueConverter(sqlUnaryExpression.Operand));
}
if (sqlExpression is SqlBinaryExpression sqlBinaryExpression
&& (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso
|| sqlBinaryExpression.OperatorType == ExpressionType.OrElse))
{
return sqlBinaryExpression.Update(
TryCompensateForBoolWithValueConverter(sqlBinaryExpression.Left),
TryCompensateForBoolWithValueConverter(sqlBinaryExpression.Right));
}
return sqlExpression;
}
}
| 47.9375 | 113 | 0.713331 | [
"MIT"
] | ChaseKnowlden/efcore | src/EFCore.Cosmos/Query/Internal/CosmosValueConverterCompensatingExpressionVisitor.cs | 6,138 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web;
namespace DocumentDbCourse.Extensions
{
public static class StringExtensions
{
public static SecureString ToSecureString(this string _self)
{
SecureString knox = new SecureString();
char[] chars = _self.ToCharArray();
foreach (char c in chars)
{
knox.AppendChar(c);
}
return knox;
}
}
} | 23.636364 | 68 | 0.594231 | [
"MIT"
] | mrahulshakya/DocumentDbPoc | DocumentDbCourse/Extensions/StringExtensions.cs | 522 | C# |
using MediatR;
namespace Teacher.Website.Feature.Interview.Question.Create
{
public class Query : IRequest<ViewModel>
{
}
} | 17.125 | 59 | 0.715328 | [
"MIT"
] | PiotrWandycz/Teacher | Teacher/Teacher.Website/Feature/Interview/Question/Create/Query.cs | 139 | C# |
/*
Scenario for use Builder:
We have a final product that will be builded following particular characteristics, as
a stratocaster guitar and telecaster guitar
For better reference, please visit https://www.dofactory.com/net/design-patterns
*/
using System;
using System.Collections.Generic;
namespace brunoedsm.creational.console
{
public static class BuilderPlayer
{
public static void PlayExample()
{
StratocasterBuilder sb = new StratocasterBuilder();
TelecasterBuilder tb = new TelecasterBuilder();
Manufacturer m = new Manufacturer();
m.Construct(sb);
m.Construct(tb);
var product1 = sb.GetResult();
var product2 = tb.GetResult();
product1.Show();
product2.Show();
}
}
// Abstracts
abstract class Builder
{
public abstract void AddModel();
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
// Concretes
class Manufacturer{
public void Construct(Builder builder)
{
builder.AddModel();
builder.BuildPartA();
builder.BuildPartB();
}
}
class StratocasterBuilder : Builder
{
private Product _product = new Product();
public override void AddModel()
{
_product.Add("Stratocaster Default");
}
public override void BuildPartA()
{
_product.Add("Alnico Bridge and Neck PickUps");
}
public override void BuildPartB()
{
_product.Add("Alnico Medium PickUp");
}
public override Product GetResult()
{
return _product;
}
}
class TelecasterBuilder : Builder
{
private Product _product = new Product();
public override void AddModel()
{
_product.Add("Telecaster Default");
}
public override void BuildPartA()
{
_product.Add("Vintage Bridge PickUp");
}
public override void BuildPartB()
{
_product.Add("Gloss Neck PickUp");
}
public override Product GetResult()
{
return _product;
}
}
class Product
{
private List<string> _parts = new List<string>();
public void Add(string part)
{
_parts.Add(part);
}
public void Show()
{
Console.WriteLine("\nGuitar Picks -------");
foreach (string part in _parts)
Console.WriteLine(part);
}
}
}
| 24.321429 | 90 | 0.553231 | [
"Apache-2.0"
] | brunoedsm/c-sharp-resources | design-patterns/creational/brunoedsm.creational.console/BuilderPlayer.cs | 2,724 | C# |
namespace PaulasCadenza.HabboNetwork.Models
{
public interface ICommReadObjectDelegate
{
CommReadObject DeriveCommReadObject(ushort sendType);
}
}
| 19.125 | 55 | 0.823529 | [
"MIT"
] | sonicmouse/PaulasCadenza | PaulasCadenza.HabboNetwork/Models/ICommReadObjectDelegate.cs | 155 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.ApplicationModel.Configuration.Tests
{
[Category("Live")]
public class ConfigurationLiveTests
{
static readonly ConfigurationSetting s_testSetting = new ConfigurationSetting(
string.Concat("key-", Guid.NewGuid().ToString("N")),
"test_value"
)
{
Label = "test_label",
ContentType = "test_content_type",
Tags = new Dictionary<string, string>
{
{ "tag1", "value1" },
{ "tag2", "value2" }
}
};
private static bool TagsEqual(IDictionary<string, string> expected, IDictionary<string, string> actual)
{
if (expected == null && actual == null) return true;
if (expected?.Count != actual?.Count) return false;
foreach (var pair in expected)
{
if (!actual.TryGetValue(pair.Key, out string value)) return false;
if (!string.Equals(value, pair.Value, StringComparison.Ordinal)) return false;
}
return true;
}
private async Task<string> SetMultipleKeys(ConfigurationClient service, int expectedEvents)
{
string key = string.Concat("key-", Guid.NewGuid().ToString("N"));
/*
* The configuration store contains a KV with the Key
* that represents {expectedEvents} data points.
* If not set, create the {expectedEvents} data points and the "BatchKey"
*/
const string batchKey = "BatchKey";
try
{
var responseGet = await service.GetAsync(batchKey);
key = responseGet.Value.Value;
responseGet.Dispose();
}
catch
{
for (int i = 0; i < expectedEvents; i++)
{
await service.AddAsync(new ConfigurationSetting(key, "test_value", $"{i.ToString()}"));
}
await service.SetAsync(new ConfigurationSetting(batchKey, key));
}
return key;
}
[Test]
public async Task DeleteSettingNotFound()
{
ConfigurationClient service = TestEnvironment.GetClient();
var response = await service.DeleteAsync(s_testSetting.Key);
Assert.AreEqual(204, response.Status);
response.Dispose();
}
[Test]
public async Task DeleteSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
// Prepare environment
var testSettingDiff = s_testSetting.Clone();
testSettingDiff.Label = null;
await service.SetAsync(s_testSetting);
await service.SetAsync(testSettingDiff);
// Test
await service.DeleteAsync(testSettingDiff.Key);
//Try to get the non-existing setting
var e = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.GetAsync(testSettingDiff.Key);
});
Assert.AreEqual(404, e.Status);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task DeleteSettingWithLabel()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
// Prepare environment
var testSettingDiff = s_testSetting.Clone();
testSettingDiff.Label = "test_label_diff";
await service.SetAsync(s_testSetting);
await service.SetAsync(testSettingDiff);
// Test
await service.DeleteAsync(testSettingDiff.Key, testSettingDiff.Label);
//Try to get the non-existing setting
var e = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.GetAsync(testSettingDiff.Key, testSettingDiff.Label);
});
Assert.AreEqual(404, e.Status);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task DeleteSettingWithETag()
{
ConfigurationClient service = TestEnvironment.GetClient();
// Prepare environment
await service.SetAsync(s_testSetting);
ConfigurationSetting setting = await service.GetAsync(s_testSetting.Key, s_testSetting.Label);
// Test
await service.DeleteAsync(setting.Key, setting.Label, setting.ETag, CancellationToken.None);
//Try to get the non-existing setting
var e = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.GetAsync(s_testSetting.Key, s_testSetting.Label);
});
Assert.AreEqual(404, e.Status);
}
[Test]
public async Task SetSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
ConfigurationSetting setting = await service.SetAsync(s_testSetting);
Assert.AreEqual(s_testSetting, setting);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task SetExistingSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.AddAsync(s_testSetting);
ConfigurationSetting setting = await service.SetAsync(s_testSetting);
Assert.AreEqual(s_testSetting, setting);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task SetKeyValue()
{
ConfigurationClient service = TestEnvironment.GetClient();
string key = string.Concat("key-", Guid.NewGuid().ToString("N"));
try
{
string value = "my_value";
ConfigurationSetting setting = await service.SetAsync(key, value);
Assert.AreEqual(key, setting.Key);
Assert.AreEqual(value, setting.Value);
}
finally
{
await service.DeleteAsync(key);
}
}
[Test]
public async Task SetKeyValueLabel()
{
ConfigurationClient service = TestEnvironment.GetClient();
string key = string.Concat("key-", Guid.NewGuid().ToString("N"));
string value = "my_value";
string label = "my_label";
try
{
ConfigurationSetting setting = await service.SetAsync(key, value, label);
Assert.AreEqual(key, setting.Key);
Assert.AreEqual(value, setting.Value);
Assert.AreEqual(label, setting.Label);
}
finally
{
await service.DeleteAsync(key, label);
}
}
[Test]
public async Task GetRequestId()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
Response<ConfigurationSetting> response = await service.SetAsync(s_testSetting);
response.TryGetHeader("x-ms-client-request-id", out string requestId);
Assert.IsNotEmpty(requestId);
response.Dispose();
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task AddExistingSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.AddAsync(s_testSetting);
var exception = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.AddAsync(s_testSetting);
});
Assert.AreEqual(412, exception.Status);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task AddSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
ConfigurationSetting setting = await service.AddAsync(s_testSetting);
Assert.AreEqual(s_testSetting, setting);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task AddSettingNoLabel()
{
ConfigurationClient service = TestEnvironment.GetClient();
var testSettingNoLabel = s_testSetting.Clone();
testSettingNoLabel.Label = null;
try
{
ConfigurationSetting setting = await service.AddAsync(testSettingNoLabel);
Assert.AreEqual(testSettingNoLabel, setting);
}
finally
{
await service.DeleteAsync(s_testSetting.Key);
}
}
[Test]
public async Task AddKeyValue()
{
ConfigurationClient service = TestEnvironment.GetClient();
string key = string.Concat("key-", Guid.NewGuid().ToString("N"));
try
{
string value = "my_value";
ConfigurationSetting setting = await service.AddAsync(key, value);
Assert.AreEqual(key, setting.Key);
Assert.AreEqual(value, setting.Value);
}
finally
{
await service.DeleteAsync(key);
}
}
[Test]
public async Task AddKeyValueLabel()
{
ConfigurationClient service = TestEnvironment.GetClient();
string key = string.Concat("key-", Guid.NewGuid().ToString("N"));
string value = "my_value";
string label = "my_label";
try
{
ConfigurationSetting setting = await service.AddAsync(key, value, label);
Assert.AreEqual(key, setting.Key);
Assert.AreEqual(value, setting.Value);
Assert.AreEqual(label, setting.Label);
}
finally
{
await service.DeleteAsync(key, label);
}
}
[Test]
public async Task UpdateKeyValue()
{
ConfigurationClient service = TestEnvironment.GetClient();
string key = string.Concat("key-", Guid.NewGuid().ToString("N"));
await service.SetAsync(key, "my_value");
try
{
string value = "my_value2";
ConfigurationSetting responseSetting = await service.UpdateAsync(key, value);
Assert.AreEqual(key, responseSetting.Key);
Assert.AreEqual(value, responseSetting.Value);
}
finally
{
await service.DeleteAsync(key);
}
}
[Test]
public async Task UpdateSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
var testSettingDiff = s_testSetting.Clone();
testSettingDiff.Label = "test_label_diff";
var testSettingUpdate = s_testSetting.Clone();
testSettingUpdate.Value = "test_value_update";
try
{
await service.SetAsync(s_testSetting);
await service.SetAsync(testSettingDiff);
ConfigurationSetting responseSetting = await service.UpdateAsync(testSettingUpdate, CancellationToken.None);
Assert.AreEqual(testSettingUpdate, responseSetting);
}
finally
{
await service.DeleteAsync(testSettingUpdate.Key, testSettingUpdate.Label);
await service.DeleteAsync(testSettingDiff.Key, testSettingDiff.Label);
}
}
[Test]
public void UpdateNoExistingSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
var exception = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.UpdateAsync(s_testSetting);
});
Assert.AreEqual(412, exception.Status);
}
[Test]
public async Task UpdateSettingIfETag()
{
ConfigurationClient service = TestEnvironment.GetClient();
await service.SetAsync(s_testSetting);
ConfigurationSetting responseGet = await service.GetAsync(s_testSetting.Key, s_testSetting.Label);
try
{
responseGet.Value = "test_value_diff";
ConfigurationSetting responseSetting = await service.UpdateAsync(responseGet, CancellationToken.None);
Assert.AreNotEqual(responseGet, responseSetting);
}
finally
{
await service.DeleteAsync(responseGet.Key, responseGet.Label);
}
}
[Test]
public async Task UpdateSettingTags()
{
ConfigurationClient service = TestEnvironment.GetClient();
await service.SetAsync(s_testSetting);
ConfigurationSetting responseGet = await service.GetAsync(s_testSetting.Key, s_testSetting.Label);
try
{
// Different tags
var testSettingDiff = responseGet.Clone();
var settingTags = testSettingDiff.Tags;
if (settingTags.ContainsKey("tag1")) settingTags["tag1"] = "value-updated";
settingTags.Add("tag3", "test_value3");
testSettingDiff.Tags = settingTags;
ConfigurationSetting responseSetting = await service.UpdateAsync(testSettingDiff, CancellationToken.None);
Assert.AreEqual(testSettingDiff, responseSetting);
// No tags
var testSettingNoTags = responseGet.Clone();
testSettingNoTags.Tags = null;
responseSetting = await service.UpdateAsync(testSettingNoTags, CancellationToken.None);
Assert.AreEqual(testSettingNoTags, responseSetting);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task GetRevisions()
{
ConfigurationClient service = TestEnvironment.GetClient();
//Prepare environment
ConfigurationSetting setting = s_testSetting;
setting.Key = string.Concat("key-", Guid.NewGuid().ToString("N"));
var testSettingUpdate = setting.Clone();
testSettingUpdate.Label = "test_label_update";
int expectedEvents = 2;
try
{
await service.SetAsync(setting);
await service.SetAsync(testSettingUpdate);
// Test
var selector = new SettingSelector(setting.Key);
selector.AsOf = DateTimeOffset.MaxValue;
SettingBatch batch = await service.GetRevisionsAsync(selector, CancellationToken.None);
int resultsReturned = 0;
for (int i = 0; i < batch.Count; i++)
{
var value = batch[i];
if (value.Label.Contains("update"))
{
Assert.AreEqual(value, testSettingUpdate);
}
else
{
Assert.AreEqual(value, setting);
}
resultsReturned++;
}
Assert.AreEqual(expectedEvents, resultsReturned);
}
finally
{
await service.DeleteAsync(setting.Key, setting.Label);
await service.DeleteAsync(testSettingUpdate.Key, testSettingUpdate.Label);
}
}
[Test]
public async Task GetSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
// Prepare environment
var testSettingNoLabel = s_testSetting.Clone();
testSettingNoLabel.Label = null;
try
{
await service.SetAsync(testSettingNoLabel);
// Test
ConfigurationSetting setting = await service.GetAsync(testSettingNoLabel.Key);
Assert.AreEqual(testSettingNoLabel, setting);
}
finally
{
await service.DeleteAsync(testSettingNoLabel.Key);
}
}
[Test]
public void GetSettingNotFound()
{
ConfigurationClient service = TestEnvironment.GetClient();
var exception = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.GetAsync(s_testSetting.Key);
});
Assert.AreEqual(404, exception.Status);
}
[Test]
public async Task GetSettingWithLabel()
{
ConfigurationClient service = TestEnvironment.GetClient();
// Prepare environment
var testSettingNoLabel = s_testSetting.Clone();
testSettingNoLabel.Label = null;
try
{
await service.SetAsync(testSettingNoLabel);
await service.SetAsync(s_testSetting);
// Test
ConfigurationSetting responseSetting = await service.GetAsync(s_testSetting.Key, s_testSetting.Label);
Assert.AreEqual(s_testSetting, responseSetting);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
await service.DeleteAsync(testSettingNoLabel.Key);
}
}
[Test]
public async Task GetWithAcceptDateTime()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.SetAsync(s_testSetting);
// Test
ConfigurationSetting responseSetting = await service.GetAsync(s_testSetting.Key, s_testSetting.Label, DateTimeOffset.MaxValue);
Assert.AreEqual(s_testSetting, responseSetting);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task GetBatchSettingPagination()
{
ConfigurationClient service = TestEnvironment.GetClient();
const int expectedEvents = 105;
var key = await SetMultipleKeys(service, expectedEvents);
int resultsReturned = 0;
SettingSelector selector = new SettingSelector(key);
while (true)
{
using (Response<SettingBatch> response = await service.GetBatchAsync(selector, CancellationToken.None))
{
SettingBatch batch = response.Value;
resultsReturned += batch.Count;
var nextBatch = batch.NextBatch;
if (nextBatch == null) break;
selector = nextBatch;
}
}
Assert.AreEqual(expectedEvents, resultsReturned);
}
[Test]
public async Task GetBatchSettingAny()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.SetAsync(s_testSetting);
var selector = new SettingSelector();
Assert.AreEqual(selector.Keys.First(), "*");
Assert.AreEqual(selector.Labels.First(), "*");
SettingBatch batch = await service.GetBatchAsync(selector, CancellationToken.None);
int resultsReturned = batch.Count;
//At least there should be one key available
Assert.GreaterOrEqual(resultsReturned, 1);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task GetBatchSettingKeyLabel()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.SetAsync(s_testSetting);
var selector = new SettingSelector(s_testSetting.Key, s_testSetting.Label);
SettingBatch batch = await service.GetBatchAsync(selector, CancellationToken.None);
Assert.AreEqual(batch.Count, 1);
Assert.AreEqual(batch[0].Key, s_testSetting.Key);
Assert.AreEqual(batch[0].Label, s_testSetting.Label);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task GetBatchSettingOnlyKey()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.SetAsync(s_testSetting);
var selector = new SettingSelector(s_testSetting.Key);
SettingBatch batch = await service.GetBatchAsync(selector, CancellationToken.None);
Assert.AreEqual(batch.Count, 1);
Assert.AreEqual(batch[0].Key, s_testSetting.Key);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task GetBatchSettingOnlyLabel()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.SetAsync(s_testSetting);
var selector = new SettingSelector(null, s_testSetting.Label);
Assert.AreEqual(selector.Keys.First(), "*");
SettingBatch batch = await service.GetBatchAsync(selector, CancellationToken.None);
int resultsReturned = batch.Count;
//At least there should be one key available
Assert.GreaterOrEqual(resultsReturned, 1);
Assert.AreEqual(batch[0].Label, s_testSetting.Label);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task GetBatchSettingWithFields()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
await service.SetAsync(s_testSetting);
SettingSelector selector = new SettingSelector()
{
Fields = SettingFields.Key | SettingFields.Label | SettingFields.Value,
};
SettingBatch batch = await service.GetBatchAsync(selector, CancellationToken.None);
int resultsReturned = batch.Count;
//At least there should be one key available
Assert.GreaterOrEqual(resultsReturned, 1);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public async Task LockUnlockSetting()
{
ConfigurationClient service = TestEnvironment.GetClient();
try
{
// Prepare environment
await service.SetAsync(s_testSetting);
// Test Lock
ConfigurationSetting responseLockSetting = await service.LockAsync(s_testSetting.Key, s_testSetting.Label, CancellationToken.None);
//Test update
var testSettingUpdate = s_testSetting.Clone();
testSettingUpdate.Value = "test_value_update";
var exception = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.UpdateAsync(testSettingUpdate);
});
Assert.AreEqual(409, exception.Status);
// Test Unlock
ConfigurationSetting responseUnlockSetting = await service.UnlockAsync(s_testSetting.Key, s_testSetting.Label, CancellationToken.None);
await service.UpdateAsync(testSettingUpdate);
}
finally
{
await service.DeleteAsync(s_testSetting.Key, s_testSetting.Label);
}
}
[Test]
public void LockSettingNotFound()
{
ConfigurationClient service = TestEnvironment.GetClient();
var exception = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.LockAsync(s_testSetting.Key, s_testSetting.Label, CancellationToken.None);
});
Assert.AreEqual(404, exception.Status);
}
[Test]
public void UnlockSettingNotFound()
{
ConfigurationClient service = TestEnvironment.GetClient();
var exception = Assert.ThrowsAsync<RequestFailedException>(async () =>
{
await service.UnlockAsync(s_testSetting.Key, s_testSetting.Label, CancellationToken.None);
});
Assert.AreEqual(404, exception.Status);
}
}
public static class ConfigurationSettingExtensions
{
public static ConfigurationSetting Clone(this ConfigurationSetting setting)
{
Dictionary<string, string> tags = new Dictionary<string, string>();
foreach (string key in setting.Tags.Keys)
{
tags.Add(key, setting.Tags[key]);
}
return new ConfigurationSetting(setting.Key, setting.Value)
{
Label = setting.Label,
ContentType = setting.ContentType,
Tags = tags
};
}
}
}
| 32.945718 | 151 | 0.543241 | [
"MIT"
] | sjh37/aznetsdk | src/SDKs/Azure.ApplicationModel.Configuration/data-plane/Azure.ApplicationModel.Configuration.Tests/ConfigurationLiveTests.cs | 27,314 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using BusterWood.Data;
using System.Text;
namespace BusterWood.Csv
{
class ToXml
{
public static Relation Run(List<string> args, Relation input)
{
try
{
if (args.Remove("--help")) Help();
var all = args.Remove("--all");
string format = BuildLineFormat(input.Schema);
Console.WriteLine($@"<relation name=""{input.Schema.Name}"">");
var vals = new object[input.Schema.Count];
foreach (var row in input.Distinct(!all))
{
int i = 0;
foreach (var nv in row)
vals[i++] = nv.Value;
Console.WriteLine(format, vals);
}
Console.WriteLine("</relation>");
}
catch (Exception ex)
{
StdErr.Warning(ex.Message);
Help();
}
return null; // should not be used as input
}
private static string BuildLineFormat(Schema schema)
{
var sb = new StringBuilder();
sb.Append(@" <row ");
int i = 0;
foreach (var col in schema)
{
sb.Append(col.Name).Append(@"=""");
if (Equals(col.Type, typeof(DateTime)) || Equals(col.Type, typeof(DateTimeOffset)))
sb.Append("{").Append(i).Append(@":u}");
else
sb.Append("{").Append(i).Append(@"}");
sb.Append(@""" ");
i++;
}
sb.Length -= 1; // trailing space
sb.Append("/>");
return sb.ToString();
}
static void Help()
{
Console.Error.WriteLine($"csv tojson [--all] [--in file]");
Console.Error.WriteLine($"Outputs rows of the input CSV printed as a JSON array ");
Console.Error.WriteLine($"\t--all do NOT remove duplicates from the result");
Programs.Exit(1);
}
}
}
| 31.289855 | 99 | 0.459935 | [
"Apache-2.0"
] | busterwood/Data | csv/ToXml.cs | 2,161 | C# |
/*
The MIT License (MIT)
Copyright (c) 2013 yamamura tatsuhiko
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using UnityEngine;
using System.Collections;
using UnityEngine.Assertions;
public class Fade : MonoBehaviour
{
IFade fade;
void Start ()
{
Init ();
fade.Range = cutoutRange;
}
float cutoutRange;
void Init ()
{
fade = GetComponent<IFade> ();
}
void OnValidate ()
{
Init ();
fade.Range = cutoutRange;
}
IEnumerator FadeoutCoroutine (float time, System.Action action)
{
float endTime = Time.timeSinceLevelLoad + time * (cutoutRange);
var endFrame = new WaitForEndOfFrame ();
while (Time.timeSinceLevelLoad <= endTime) {
cutoutRange = (endTime - Time.timeSinceLevelLoad) / time;
fade.Range = cutoutRange;
yield return endFrame;
}
cutoutRange = 0;
fade.Range = cutoutRange;
if (action != null) {
action ();
}
}
IEnumerator FadeinCoroutine (float time, System.Action action)
{
float endTime = Time.timeSinceLevelLoad + time * (1 - cutoutRange);
var endFrame = new WaitForEndOfFrame ();
while (Time.timeSinceLevelLoad <= endTime) {
cutoutRange = 1 - ((endTime - Time.timeSinceLevelLoad) / time);
fade.Range = cutoutRange;
yield return endFrame;
}
cutoutRange = 1;
fade.Range = cutoutRange;
if (action != null) {
action ();
}
}
public Coroutine FadeOut (float time, System.Action action)
{
StopAllCoroutines ();
return StartCoroutine (FadeoutCoroutine (time, action));
}
public Coroutine FadeOut (float time)
{
return FadeOut (time, null);
}
public Coroutine FadeIn (float time, System.Action action)
{
StopAllCoroutines ();
return StartCoroutine (FadeinCoroutine (time, action));
}
public Coroutine FadeIn (float time)
{
return FadeIn (time, null);
}
} | 25.583333 | 80 | 0.730004 | [
"MIT"
] | ShuheiOi/AdolescenceNovel | Assets/Sources/Novel/FadeScript/Fade.cs | 2,765 | C# |
namespace BlogWeb.Domain.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class PostTextLengthChanged : DbMigration
{
public override void Up()
{
AlterColumn("dbo.Posts", "ShortDescription", c => c.String(nullable: false, maxLength: 500));
AlterColumn("dbo.Posts", "Text", c => c.String(nullable: false));
}
public override void Down()
{
AlterColumn("dbo.Posts", "Text", c => c.String(nullable: false, maxLength: 700));
AlterColumn("dbo.Posts", "ShortDescription", c => c.String(nullable: false, maxLength: 300));
}
}
}
| 32.428571 | 105 | 0.590308 | [
"MIT"
] | AliMecidzade/WebAppBlog | WebAppBlog/BlogWeb/BlogWeb.Domain/Migrations/202108061551299_PostTextLengthChanged.cs | 683 | C# |
namespace Notes.Services.Models.User
{
using Notes.Common.AutoMapping;
using Notes.Models;
public class LoggedInUserModel : IMapWith<User>
{
public int Id { get; set; }
public string Username { get; set; }
}
}
| 19.153846 | 51 | 0.634538 | [
"MIT"
] | msotiroff/Softuni-learning | C# Web Module/CSharp-Web-Development-Basics/09.WorkShop/NotesApplication/Notes.Services/Models/User/LoggedInUserModel.cs | 251 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LocalizationSample.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string Culture {
get {
return ((string)(this["Culture"]));
}
set {
this["Culture"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string UICulture {
get {
return ((string)(this["UICulture"]));
}
set {
this["UICulture"] = value;
}
}
}
}
| 38.45098 | 152 | 0.54615 | [
"MIT"
] | DotNetUz/waf | src/System.Waf/Samples/Localization/LocalizationSample/Properties/Settings.Designer.cs | 1,963 | C# |
namespace NBitcoinBTG
{
public class PrecomputedTransactionData
{
public PrecomputedTransactionData(Transaction tx)
{
HashOutputs = Script.GetHashOutputs(tx);
HashSequence = Script.GetHashSequence(tx);
HashPrevouts = Script.GetHashPrevouts(tx);
}
public uint256 HashPrevouts
{
get;
set;
}
public uint256 HashSequence
{
get;
set;
}
public uint256 HashOutputs
{
get;
set;
}
}
}
| 15.392857 | 51 | 0.689095 | [
"MIT"
] | LykkeCity/NBitcoinBTG | NBitcoin/PrecomputedTransactionData.cs | 433 | C# |
namespace TimeKeeper
{
partial class frmTimeKeeper
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmTimeKeeper));
this.btnSave = new System.Windows.Forms.Button();
this.timInterval = new System.Windows.Forms.Timer(this.components);
this.niTimeKeeper = new System.Windows.Forms.NotifyIcon(this.components);
this.cmsNotifyIcon = new System.Windows.Forms.ContextMenuStrip(this.components);
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.timFlasher = new System.Windows.Forms.Timer(this.components);
this.timOpened = new System.Windows.Forms.Timer(this.components);
this.lblMinutes = new System.Windows.Forms.Label();
this.lblName = new System.Windows.Forms.Label();
this.dispName = new System.Windows.Forms.Label();
this.lblProject = new System.Windows.Forms.Label();
this.lblTime = new System.Windows.Forms.Label();
this.lblDescription = new System.Windows.Forms.Label();
this.cdButtonColor = new System.Windows.Forms.ColorDialog();
this.dispMinutes = new System.Windows.Forms.Label();
this.msMain = new System.Windows.Forms.MenuStrip();
this.timeKeeperToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.projectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.reportsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.detailReportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.summaryReportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dailySummaryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.resetTimeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pauseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.minutes15ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.minutes30ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.hour1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.hour2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.hour8ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearPauseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prompToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prompt5ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prompt10ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prompt15ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prompt30ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prompt60ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowTransparencyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.trans0StripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.trans25StripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.trans50StripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.trans75StripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonColorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.nameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.llDiscardTime = new System.Windows.Forms.LinkLabel();
this.timeBox7 = new System.Windows.Forms.TextBox();
this.timeBox6 = new System.Windows.Forms.TextBox();
this.timeBox5 = new System.Windows.Forms.TextBox();
this.timeBox4 = new System.Windows.Forms.TextBox();
this.timeBox3 = new System.Windows.Forms.TextBox();
this.timeBox2 = new System.Windows.Forms.TextBox();
this.descriptionBox7 = new System.Windows.Forms.TextBox();
this.descriptionBox6 = new System.Windows.Forms.TextBox();
this.descriptionBox5 = new System.Windows.Forms.TextBox();
this.descriptionBox4 = new System.Windows.Forms.TextBox();
this.descriptionBox3 = new System.Windows.Forms.TextBox();
this.descriptionBox2 = new System.Windows.Forms.TextBox();
this.descriptionBox1 = new System.Windows.Forms.TextBox();
this.timeBox1 = new System.Windows.Forms.TextBox();
this.projectBox7 = new GroupedComboBox();
this.projectBox6 = new GroupedComboBox();
this.projectBox5 = new GroupedComboBox();
this.projectBox4 = new GroupedComboBox();
this.projectBox3 = new GroupedComboBox();
this.projectBox2 = new GroupedComboBox();
this.projectBox1 = new GroupedComboBox();
this.deleteBtn1 = new System.Windows.Forms.Label();
this.deleteBtn2 = new System.Windows.Forms.Label();
this.deleteBtn3 = new System.Windows.Forms.Label();
this.deleteBtn4 = new System.Windows.Forms.Label();
this.deleteBtn5 = new System.Windows.Forms.Label();
this.deleteBtn6 = new System.Windows.Forms.Label();
this.deleteBtn7 = new System.Windows.Forms.Label();
this.removeUnusedRowsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cmsNotifyIcon.SuspendLayout();
this.msMain.SuspendLayout();
this.SuspendLayout();
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(399, 210);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(75, 28);
this.btnSave.TabIndex = 37;
this.btnSave.Text = "Save";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// timInterval
//
this.timInterval.Interval = 10000;
this.timInterval.Tick += new System.EventHandler(this.timInterval_Tick);
//
// niTimeKeeper
//
this.niTimeKeeper.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
this.niTimeKeeper.BalloonTipText = "Keeping Time";
this.niTimeKeeper.BalloonTipTitle = "Time Keeper";
this.niTimeKeeper.ContextMenuStrip = this.cmsNotifyIcon;
this.niTimeKeeper.Icon = ((System.Drawing.Icon)(resources.GetObject("niTimeKeeper.Icon")));
this.niTimeKeeper.Text = "TimeKeeper";
this.niTimeKeeper.Visible = true;
this.niTimeKeeper.BalloonTipClicked += new System.EventHandler(this.niTimeKeeper_DoubleClick);
this.niTimeKeeper.DoubleClick += new System.EventHandler(this.niTimeKeeper_DoubleClick);
//
// cmsNotifyIcon
//
this.cmsNotifyIcon.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.exitToolStripMenuItem});
this.cmsNotifyIcon.Name = "cmsNotifyIcon";
this.cmsNotifyIcon.Size = new System.Drawing.Size(104, 48);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.openToolStripMenuItem.Text = "&Open";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// timFlasher
//
this.timFlasher.Interval = 10;
this.timFlasher.Tick += new System.EventHandler(this.timFlasher_Tick);
//
// timOpened
//
this.timOpened.Interval = 15000;
this.timOpened.Tick += new System.EventHandler(this.timOpened_Tick);
//
// lblMinutes
//
this.lblMinutes.AutoSize = true;
this.lblMinutes.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblMinutes.Location = new System.Drawing.Point(16, 206);
this.lblMinutes.Name = "lblMinutes";
this.lblMinutes.Size = new System.Drawing.Size(55, 13);
this.lblMinutes.TabIndex = 32;
this.lblMinutes.Text = "Minutes:";
//
// lblName
//
this.lblName.AutoSize = true;
this.lblName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblName.Location = new System.Drawing.Point(16, 225);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(43, 13);
this.lblName.TabIndex = 34;
this.lblName.Text = "Name:";
//
// dispName
//
this.dispName.AutoSize = true;
this.dispName.Location = new System.Drawing.Point(77, 225);
this.dispName.Name = "dispName";
this.dispName.Size = new System.Drawing.Size(53, 13);
this.dispName.TabIndex = 35;
this.dispName.Text = "Unknown";
//
// lblProject
//
this.lblProject.AutoSize = true;
this.lblProject.Location = new System.Drawing.Point(16, 34);
this.lblProject.Name = "lblProject";
this.lblProject.Size = new System.Drawing.Size(40, 13);
this.lblProject.TabIndex = 1;
this.lblProject.Text = "Project";
//
// lblTime
//
this.lblTime.AutoSize = true;
this.lblTime.Location = new System.Drawing.Point(226, 34);
this.lblTime.Name = "lblTime";
this.lblTime.Size = new System.Drawing.Size(30, 13);
this.lblTime.TabIndex = 2;
this.lblTime.Text = "Time";
//
// lblDescription
//
this.lblDescription.AutoSize = true;
this.lblDescription.Location = new System.Drawing.Point(275, 34);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(60, 13);
this.lblDescription.TabIndex = 3;
this.lblDescription.Text = "Description";
//
// cdButtonColor
//
this.cdButtonColor.AnyColor = true;
this.cdButtonColor.Color = System.Drawing.Color.LightCyan;
this.cdButtonColor.FullOpen = true;
//
// dispMinutes
//
this.dispMinutes.AutoSize = true;
this.dispMinutes.Location = new System.Drawing.Point(77, 206);
this.dispMinutes.Name = "dispMinutes";
this.dispMinutes.Size = new System.Drawing.Size(57, 17);
this.dispMinutes.TabIndex = 33;
this.dispMinutes.TabStop = true;
this.dispMinutes.Text = "0 m of 0 m";
this.dispMinutes.UseCompatibleTextRendering = true;
//
// msMain
//
this.msMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.timeKeeperToolStripMenuItem,
this.reportsToolStripMenuItem,
this.toolsToolStripMenuItem,
this.settingsToolStripMenuItem});
this.msMain.Location = new System.Drawing.Point(0, 0);
this.msMain.Name = "msMain";
this.msMain.Size = new System.Drawing.Size(494, 24);
this.msMain.TabIndex = 0;
this.msMain.Text = "Menu";
//
// timeKeeperToolStripMenuItem
//
this.timeKeeperToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.projectToolStripMenuItem,
this.aboutToolStripMenuItem,
this.exitToolStripMenuItem1});
this.timeKeeperToolStripMenuItem.Name = "timeKeeperToolStripMenuItem";
this.timeKeeperToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.timeKeeperToolStripMenuItem.Text = "&File";
//
// projectToolStripMenuItem
//
this.projectToolStripMenuItem.Name = "projectToolStripMenuItem";
this.projectToolStripMenuItem.Size = new System.Drawing.Size(125, 22);
this.projectToolStripMenuItem.Text = "&Projects...";
this.projectToolStripMenuItem.Click += new System.EventHandler(this.newProjectToolStripMenuItem_Click);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(125, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// exitToolStripMenuItem1
//
this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1";
this.exitToolStripMenuItem1.Size = new System.Drawing.Size(125, 22);
this.exitToolStripMenuItem1.Text = "E&xit";
this.exitToolStripMenuItem1.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// reportsToolStripMenuItem
//
this.reportsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.detailReportToolStripMenuItem,
this.summaryReportToolStripMenuItem,
this.dailySummaryToolStripMenuItem});
this.reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
this.reportsToolStripMenuItem.Size = new System.Drawing.Size(59, 20);
this.reportsToolStripMenuItem.Text = "Reports";
//
// detailReportToolStripMenuItem
//
this.detailReportToolStripMenuItem.Name = "detailReportToolStripMenuItem";
this.detailReportToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.detailReportToolStripMenuItem.Text = "Log Detail...";
this.detailReportToolStripMenuItem.Click += new System.EventHandler(this.detailReportToolStripMenuItem_Click);
//
// summaryReportToolStripMenuItem
//
this.summaryReportToolStripMenuItem.Name = "summaryReportToolStripMenuItem";
this.summaryReportToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.summaryReportToolStripMenuItem.Text = "Project Summary...";
this.summaryReportToolStripMenuItem.Click += new System.EventHandler(this.summaryReportToolStripMenuItem_Click);
//
// dailySummaryToolStripMenuItem
//
this.dailySummaryToolStripMenuItem.Name = "dailySummaryToolStripMenuItem";
this.dailySummaryToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.dailySummaryToolStripMenuItem.Text = "Daily Summary...";
this.dailySummaryToolStripMenuItem.Click += new System.EventHandler(this.dailySummaryToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.resetTimeToolStripMenuItem,
this.pauseToolStripMenuItem,
this.clearToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(46, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// resetTimeToolStripMenuItem
//
this.resetTimeToolStripMenuItem.Name = "resetTimeToolStripMenuItem";
this.resetTimeToolStripMenuItem.Size = new System.Drawing.Size(165, 22);
this.resetTimeToolStripMenuItem.Text = "&Reset Time";
this.resetTimeToolStripMenuItem.Click += new System.EventHandler(this.btnDiscard_Click);
//
// pauseToolStripMenuItem
//
this.pauseToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.minutes15ToolStripMenuItem,
this.minutes30ToolStripMenuItem,
this.hour1ToolStripMenuItem,
this.hour2ToolStripMenuItem,
this.hour8ToolStripMenuItem,
this.clearPauseToolStripMenuItem});
this.pauseToolStripMenuItem.Name = "pauseToolStripMenuItem";
this.pauseToolStripMenuItem.Size = new System.Drawing.Size(165, 22);
this.pauseToolStripMenuItem.Text = "&Pause Prompting";
//
// minutes15ToolStripMenuItem
//
this.minutes15ToolStripMenuItem.Name = "minutes15ToolStripMenuItem";
this.minutes15ToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.minutes15ToolStripMenuItem.Text = "15 &minutes";
this.minutes15ToolStripMenuItem.Click += new System.EventHandler(this.pauseToolStripMenuItem_Click);
//
// minutes30ToolStripMenuItem
//
this.minutes30ToolStripMenuItem.Name = "minutes30ToolStripMenuItem";
this.minutes30ToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.minutes30ToolStripMenuItem.Text = "&30 minutes";
this.minutes30ToolStripMenuItem.Click += new System.EventHandler(this.pauseToolStripMenuItem_Click);
//
// hour1ToolStripMenuItem
//
this.hour1ToolStripMenuItem.Name = "hour1ToolStripMenuItem";
this.hour1ToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.hour1ToolStripMenuItem.Text = "&1 hour";
this.hour1ToolStripMenuItem.Click += new System.EventHandler(this.pauseToolStripMenuItem_Click);
//
// hour2ToolStripMenuItem
//
this.hour2ToolStripMenuItem.Name = "hour2ToolStripMenuItem";
this.hour2ToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.hour2ToolStripMenuItem.Text = "&2 hours";
this.hour2ToolStripMenuItem.Click += new System.EventHandler(this.pauseToolStripMenuItem_Click);
//
// hour8ToolStripMenuItem
//
this.hour8ToolStripMenuItem.Name = "hour8ToolStripMenuItem";
this.hour8ToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.hour8ToolStripMenuItem.Text = "&8 hours";
this.hour8ToolStripMenuItem.Click += new System.EventHandler(this.pauseToolStripMenuItem_Click);
//
// clearPauseToolStripMenuItem
//
this.clearPauseToolStripMenuItem.Name = "clearPauseToolStripMenuItem";
this.clearPauseToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.clearPauseToolStripMenuItem.Text = "&Resume Prompting";
this.clearPauseToolStripMenuItem.Click += new System.EventHandler(this.pauseToolStripMenuItem_Click);
//
// clearToolStripMenuItem
//
this.clearToolStripMenuItem.Name = "clearToolStripMenuItem";
this.clearToolStripMenuItem.Size = new System.Drawing.Size(165, 22);
this.clearToolStripMenuItem.Text = "&Clear Entries";
this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click);
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.prompToolStripMenuItem,
this.windowTransparencyToolStripMenuItem,
this.buttonColorToolStripMenuItem,
this.nameToolStripMenuItem,
this.removeUnusedRowsToolStripMenuItem});
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(61, 20);
this.settingsToolStripMenuItem.Text = "&Settings";
//
// prompToolStripMenuItem
//
this.prompToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.prompt5ToolStripMenuItem,
this.prompt10ToolStripMenuItem,
this.prompt15ToolStripMenuItem,
this.prompt30ToolStripMenuItem,
this.prompt60ToolStripMenuItem});
this.prompToolStripMenuItem.Name = "prompToolStripMenuItem";
this.prompToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.prompToolStripMenuItem.Text = "&Prompt Every";
//
// prompt5ToolStripMenuItem
//
this.prompt5ToolStripMenuItem.Name = "prompt5ToolStripMenuItem";
this.prompt5ToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
this.prompt5ToolStripMenuItem.Text = "&5 minutes";
this.prompt5ToolStripMenuItem.Click += new System.EventHandler(this.promptToolStripMenuItem_Click);
//
// prompt10ToolStripMenuItem
//
this.prompt10ToolStripMenuItem.Name = "prompt10ToolStripMenuItem";
this.prompt10ToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
this.prompt10ToolStripMenuItem.Text = "&10 minutes";
this.prompt10ToolStripMenuItem.Click += new System.EventHandler(this.promptToolStripMenuItem_Click);
//
// prompt15ToolStripMenuItem
//
this.prompt15ToolStripMenuItem.Name = "prompt15ToolStripMenuItem";
this.prompt15ToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
this.prompt15ToolStripMenuItem.Text = "15 &minutes";
this.prompt15ToolStripMenuItem.Click += new System.EventHandler(this.promptToolStripMenuItem_Click);
//
// prompt30ToolStripMenuItem
//
this.prompt30ToolStripMenuItem.Name = "prompt30ToolStripMenuItem";
this.prompt30ToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
this.prompt30ToolStripMenuItem.Text = "&30 minutes";
this.prompt30ToolStripMenuItem.Click += new System.EventHandler(this.promptToolStripMenuItem_Click);
//
// prompt60ToolStripMenuItem
//
this.prompt60ToolStripMenuItem.Name = "prompt60ToolStripMenuItem";
this.prompt60ToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
this.prompt60ToolStripMenuItem.Text = "1 &hour";
this.prompt60ToolStripMenuItem.Click += new System.EventHandler(this.promptToolStripMenuItem_Click);
//
// windowTransparencyToolStripMenuItem
//
this.windowTransparencyToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.trans0StripMenuItem,
this.trans25StripMenuItem,
this.trans50StripMenuItem,
this.trans75StripMenuItem});
this.windowTransparencyToolStripMenuItem.Name = "windowTransparencyToolStripMenuItem";
this.windowTransparencyToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.windowTransparencyToolStripMenuItem.Text = "&Window Transparency";
//
// trans0StripMenuItem
//
this.trans0StripMenuItem.Name = "trans0StripMenuItem";
this.trans0StripMenuItem.Size = new System.Drawing.Size(96, 22);
this.trans0StripMenuItem.Text = "&0%";
this.trans0StripMenuItem.Click += new System.EventHandler(this.transToolStripMenuItem_Click);
//
// trans25StripMenuItem
//
this.trans25StripMenuItem.Name = "trans25StripMenuItem";
this.trans25StripMenuItem.Size = new System.Drawing.Size(96, 22);
this.trans25StripMenuItem.Text = "&25%";
this.trans25StripMenuItem.Click += new System.EventHandler(this.transToolStripMenuItem_Click);
//
// trans50StripMenuItem
//
this.trans50StripMenuItem.Name = "trans50StripMenuItem";
this.trans50StripMenuItem.Size = new System.Drawing.Size(96, 22);
this.trans50StripMenuItem.Text = "&50%";
this.trans50StripMenuItem.Click += new System.EventHandler(this.transToolStripMenuItem_Click);
//
// trans75StripMenuItem
//
this.trans75StripMenuItem.Name = "trans75StripMenuItem";
this.trans75StripMenuItem.Size = new System.Drawing.Size(96, 22);
this.trans75StripMenuItem.Text = "&75%";
this.trans75StripMenuItem.Click += new System.EventHandler(this.transToolStripMenuItem_Click);
//
// buttonColorToolStripMenuItem
//
this.buttonColorToolStripMenuItem.Name = "buttonColorToolStripMenuItem";
this.buttonColorToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.buttonColorToolStripMenuItem.Text = "&Button Color...";
this.buttonColorToolStripMenuItem.Click += new System.EventHandler(this.btnColor_Click);
//
// nameToolStripMenuItem
//
this.nameToolStripMenuItem.Name = "nameToolStripMenuItem";
this.nameToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.nameToolStripMenuItem.Text = "&Name...";
this.nameToolStripMenuItem.Click += new System.EventHandler(this.nameToolStripMenuItem_Click);
//
// llDiscardTime
//
this.llDiscardTime.AutoSize = true;
this.llDiscardTime.Location = new System.Drawing.Point(324, 218);
this.llDiscardTime.Name = "llDiscardTime";
this.llDiscardTime.Size = new System.Drawing.Size(69, 13);
this.llDiscardTime.TabIndex = 36;
this.llDiscardTime.TabStop = true;
this.llDiscardTime.Text = "Discard Time";
this.llDiscardTime.Click += new System.EventHandler(this.btnDiscard_Click);
//
// timeBox7
//
this.timeBox7.Location = new System.Drawing.Point(221, 170);
this.timeBox7.Name = "timeBox7";
this.timeBox7.Size = new System.Drawing.Size(45, 20);
this.timeBox7.TabIndex = 29;
//
// timeBox6
//
this.timeBox6.Location = new System.Drawing.Point(221, 150);
this.timeBox6.Name = "timeBox6";
this.timeBox6.Size = new System.Drawing.Size(45, 20);
this.timeBox6.TabIndex = 25;
//
// timeBox5
//
this.timeBox5.Location = new System.Drawing.Point(221, 130);
this.timeBox5.Name = "timeBox5";
this.timeBox5.Size = new System.Drawing.Size(45, 20);
this.timeBox5.TabIndex = 21;
//
// timeBox4
//
this.timeBox4.Location = new System.Drawing.Point(221, 110);
this.timeBox4.Name = "timeBox4";
this.timeBox4.Size = new System.Drawing.Size(45, 20);
this.timeBox4.TabIndex = 17;
//
// timeBox3
//
this.timeBox3.Location = new System.Drawing.Point(221, 90);
this.timeBox3.Name = "timeBox3";
this.timeBox3.Size = new System.Drawing.Size(45, 20);
this.timeBox3.TabIndex = 13;
//
// timeBox2
//
this.timeBox2.Location = new System.Drawing.Point(221, 70);
this.timeBox2.Name = "timeBox2";
this.timeBox2.Size = new System.Drawing.Size(45, 20);
this.timeBox2.TabIndex = 9;
//
// descriptionBox7
//
this.descriptionBox7.Location = new System.Drawing.Point(265, 170);
this.descriptionBox7.Name = "descriptionBox7";
this.descriptionBox7.Size = new System.Drawing.Size(194, 20);
this.descriptionBox7.TabIndex = 30;
//
// descriptionBox6
//
this.descriptionBox6.Location = new System.Drawing.Point(265, 150);
this.descriptionBox6.Name = "descriptionBox6";
this.descriptionBox6.Size = new System.Drawing.Size(194, 20);
this.descriptionBox6.TabIndex = 26;
//
// descriptionBox5
//
this.descriptionBox5.Location = new System.Drawing.Point(265, 130);
this.descriptionBox5.Name = "descriptionBox5";
this.descriptionBox5.Size = new System.Drawing.Size(194, 20);
this.descriptionBox5.TabIndex = 22;
//
// descriptionBox4
//
this.descriptionBox4.Location = new System.Drawing.Point(265, 110);
this.descriptionBox4.Name = "descriptionBox4";
this.descriptionBox4.Size = new System.Drawing.Size(194, 20);
this.descriptionBox4.TabIndex = 18;
//
// descriptionBox3
//
this.descriptionBox3.Location = new System.Drawing.Point(265, 90);
this.descriptionBox3.Name = "descriptionBox3";
this.descriptionBox3.Size = new System.Drawing.Size(194, 20);
this.descriptionBox3.TabIndex = 14;
//
// descriptionBox2
//
this.descriptionBox2.Location = new System.Drawing.Point(265, 70);
this.descriptionBox2.Name = "descriptionBox2";
this.descriptionBox2.Size = new System.Drawing.Size(194, 20);
this.descriptionBox2.TabIndex = 10;
//
// descriptionBox1
//
this.descriptionBox1.Location = new System.Drawing.Point(265, 50);
this.descriptionBox1.Name = "descriptionBox1";
this.descriptionBox1.Size = new System.Drawing.Size(194, 20);
this.descriptionBox1.TabIndex = 6;
//
// timeBox1
//
this.timeBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.timeBox1.Location = new System.Drawing.Point(221, 50);
this.timeBox1.Name = "timeBox1";
this.timeBox1.Size = new System.Drawing.Size(45, 20);
this.timeBox1.TabIndex = 5;
//
// projectBox7
//
this.projectBox7.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.projectBox7.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.projectBox7.DataSource = null;
this.projectBox7.DisplayMember = "Name";
this.projectBox7.DropDownHeight = 500;
this.projectBox7.DropDownWidth = 350;
this.projectBox7.FormattingEnabled = true;
this.projectBox7.GroupMember = "Department";
this.projectBox7.IntegralHeight = false;
this.projectBox7.Location = new System.Drawing.Point(12, 170);
this.projectBox7.Name = "projectBox7";
this.projectBox7.Size = new System.Drawing.Size(210, 21);
this.projectBox7.TabIndex = 28;
this.projectBox7.ValueMember = "ProjectID";
//
// projectBox6
//
this.projectBox6.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.projectBox6.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.projectBox6.DataSource = null;
this.projectBox6.DisplayMember = "Name";
this.projectBox6.DropDownHeight = 500;
this.projectBox6.DropDownWidth = 350;
this.projectBox6.FormattingEnabled = true;
this.projectBox6.GroupMember = "Department";
this.projectBox6.IntegralHeight = false;
this.projectBox6.Location = new System.Drawing.Point(12, 150);
this.projectBox6.Name = "projectBox6";
this.projectBox6.Size = new System.Drawing.Size(210, 21);
this.projectBox6.TabIndex = 24;
this.projectBox6.ValueMember = "ProjectID";
//
// projectBox5
//
this.projectBox5.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.projectBox5.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.projectBox5.DataSource = null;
this.projectBox5.DisplayMember = "Name";
this.projectBox5.DropDownHeight = 500;
this.projectBox5.DropDownWidth = 350;
this.projectBox5.FormattingEnabled = true;
this.projectBox5.GroupMember = "Department";
this.projectBox5.IntegralHeight = false;
this.projectBox5.Location = new System.Drawing.Point(12, 130);
this.projectBox5.Name = "projectBox5";
this.projectBox5.Size = new System.Drawing.Size(210, 21);
this.projectBox5.TabIndex = 20;
this.projectBox5.ValueMember = "ProjectID";
//
// projectBox4
//
this.projectBox4.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.projectBox4.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.projectBox4.DataSource = null;
this.projectBox4.DisplayMember = "Name";
this.projectBox4.DropDownHeight = 500;
this.projectBox4.DropDownWidth = 350;
this.projectBox4.FormattingEnabled = true;
this.projectBox4.GroupMember = "Department";
this.projectBox4.IntegralHeight = false;
this.projectBox4.Location = new System.Drawing.Point(12, 110);
this.projectBox4.Name = "projectBox4";
this.projectBox4.Size = new System.Drawing.Size(210, 21);
this.projectBox4.TabIndex = 16;
this.projectBox4.ValueMember = "ProjectID";
//
// projectBox3
//
this.projectBox3.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.projectBox3.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.projectBox3.DataSource = null;
this.projectBox3.DisplayMember = "Name";
this.projectBox3.DropDownHeight = 500;
this.projectBox3.DropDownWidth = 350;
this.projectBox3.FormattingEnabled = true;
this.projectBox3.GroupMember = "Department";
this.projectBox3.IntegralHeight = false;
this.projectBox3.Location = new System.Drawing.Point(12, 90);
this.projectBox3.Name = "projectBox3";
this.projectBox3.Size = new System.Drawing.Size(210, 21);
this.projectBox3.TabIndex = 12;
this.projectBox3.ValueMember = "ProjectID";
//
// projectBox2
//
this.projectBox2.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.projectBox2.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.projectBox2.DataSource = null;
this.projectBox2.DisplayMember = "Name";
this.projectBox2.DropDownHeight = 500;
this.projectBox2.DropDownWidth = 350;
this.projectBox2.FormattingEnabled = true;
this.projectBox2.GroupMember = "Department";
this.projectBox2.IntegralHeight = false;
this.projectBox2.Location = new System.Drawing.Point(12, 70);
this.projectBox2.Name = "projectBox2";
this.projectBox2.Size = new System.Drawing.Size(210, 21);
this.projectBox2.TabIndex = 8;
this.projectBox2.ValueMember = "ProjectID";
//
// projectBox1
//
this.projectBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.projectBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.projectBox1.DataSource = null;
this.projectBox1.DisplayMember = "Name";
this.projectBox1.DropDownHeight = 500;
this.projectBox1.DropDownWidth = 350;
this.projectBox1.FormattingEnabled = true;
this.projectBox1.GroupMember = "Department";
this.projectBox1.IntegralHeight = false;
this.projectBox1.Location = new System.Drawing.Point(12, 50);
this.projectBox1.Name = "projectBox1";
this.projectBox1.Size = new System.Drawing.Size(210, 21);
this.projectBox1.TabIndex = 4;
this.projectBox1.ValueMember = "ProjectID";
//
// deleteBtn1
//
this.deleteBtn1.BackColor = System.Drawing.Color.Transparent;
this.deleteBtn1.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteBtn1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.deleteBtn1.ForeColor = System.Drawing.Color.DarkRed;
this.deleteBtn1.Location = new System.Drawing.Point(460, 50);
this.deleteBtn1.Name = "deleteBtn1";
this.deleteBtn1.Size = new System.Drawing.Size(20, 20);
this.deleteBtn1.TabIndex = 7;
this.deleteBtn1.Text = "❌";
this.deleteBtn1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// deleteBtn2
//
this.deleteBtn2.BackColor = System.Drawing.Color.Transparent;
this.deleteBtn2.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteBtn2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.deleteBtn2.ForeColor = System.Drawing.Color.DarkRed;
this.deleteBtn2.Location = new System.Drawing.Point(460, 70);
this.deleteBtn2.Name = "deleteBtn2";
this.deleteBtn2.Size = new System.Drawing.Size(20, 20);
this.deleteBtn2.TabIndex = 11;
this.deleteBtn2.Text = "❌";
this.deleteBtn2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// deleteBtn3
//
this.deleteBtn3.BackColor = System.Drawing.Color.Transparent;
this.deleteBtn3.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteBtn3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.deleteBtn3.ForeColor = System.Drawing.Color.DarkRed;
this.deleteBtn3.Location = new System.Drawing.Point(460, 90);
this.deleteBtn3.Name = "deleteBtn3";
this.deleteBtn3.Size = new System.Drawing.Size(20, 20);
this.deleteBtn3.TabIndex = 15;
this.deleteBtn3.Text = "❌";
this.deleteBtn3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// deleteBtn4
//
this.deleteBtn4.BackColor = System.Drawing.Color.Transparent;
this.deleteBtn4.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteBtn4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.deleteBtn4.ForeColor = System.Drawing.Color.DarkRed;
this.deleteBtn4.Location = new System.Drawing.Point(460, 110);
this.deleteBtn4.Name = "deleteBtn4";
this.deleteBtn4.Size = new System.Drawing.Size(20, 20);
this.deleteBtn4.TabIndex = 19;
this.deleteBtn4.Text = "❌";
this.deleteBtn4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// deleteBtn5
//
this.deleteBtn5.BackColor = System.Drawing.Color.Transparent;
this.deleteBtn5.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteBtn5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.deleteBtn5.ForeColor = System.Drawing.Color.DarkRed;
this.deleteBtn5.Location = new System.Drawing.Point(460, 130);
this.deleteBtn5.Name = "deleteBtn5";
this.deleteBtn5.Size = new System.Drawing.Size(20, 20);
this.deleteBtn5.TabIndex = 23;
this.deleteBtn5.Text = "❌";
this.deleteBtn5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// deleteBtn6
//
this.deleteBtn6.BackColor = System.Drawing.Color.Transparent;
this.deleteBtn6.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteBtn6.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.deleteBtn6.ForeColor = System.Drawing.Color.DarkRed;
this.deleteBtn6.Location = new System.Drawing.Point(460, 150);
this.deleteBtn6.Name = "deleteBtn6";
this.deleteBtn6.Size = new System.Drawing.Size(20, 20);
this.deleteBtn6.TabIndex = 27;
this.deleteBtn6.Text = "❌";
this.deleteBtn6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// deleteBtn7
//
this.deleteBtn7.BackColor = System.Drawing.Color.Transparent;
this.deleteBtn7.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteBtn7.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.deleteBtn7.ForeColor = System.Drawing.Color.DarkRed;
this.deleteBtn7.Location = new System.Drawing.Point(460, 170);
this.deleteBtn7.Name = "deleteBtn7";
this.deleteBtn7.Size = new System.Drawing.Size(20, 20);
this.deleteBtn7.TabIndex = 31;
this.deleteBtn7.Text = "❌";
this.deleteBtn7.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// removeUnusedRowsToolStripMenuItem
//
this.removeUnusedRowsToolStripMenuItem.CheckOnClick = true;
this.removeUnusedRowsToolStripMenuItem.Name = "removeUnusedRowsToolStripMenuItem";
this.removeUnusedRowsToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.removeUnusedRowsToolStripMenuItem.Text = "&Remove Unused Rows";
this.removeUnusedRowsToolStripMenuItem.Visible = false;
this.removeUnusedRowsToolStripMenuItem.Click += new System.EventHandler(this.removeUnusedRowsToolStripMenuItem_Click);
//
// frmTimeKeeper
//
this.AcceptButton = this.btnSave;
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(494, 247);
this.Controls.Add(this.deleteBtn7);
this.Controls.Add(this.deleteBtn6);
this.Controls.Add(this.deleteBtn5);
this.Controls.Add(this.deleteBtn4);
this.Controls.Add(this.deleteBtn3);
this.Controls.Add(this.deleteBtn2);
this.Controls.Add(this.deleteBtn1);
this.Controls.Add(this.descriptionBox1);
this.Controls.Add(this.timeBox7);
this.Controls.Add(this.timeBox6);
this.Controls.Add(this.timeBox5);
this.Controls.Add(this.timeBox4);
this.Controls.Add(this.timeBox3);
this.Controls.Add(this.timeBox2);
this.Controls.Add(this.descriptionBox7);
this.Controls.Add(this.descriptionBox6);
this.Controls.Add(this.descriptionBox5);
this.Controls.Add(this.descriptionBox4);
this.Controls.Add(this.descriptionBox3);
this.Controls.Add(this.descriptionBox2);
this.Controls.Add(this.timeBox1);
this.Controls.Add(this.projectBox7);
this.Controls.Add(this.projectBox6);
this.Controls.Add(this.projectBox5);
this.Controls.Add(this.projectBox4);
this.Controls.Add(this.projectBox3);
this.Controls.Add(this.projectBox2);
this.Controls.Add(this.projectBox1);
this.Controls.Add(this.llDiscardTime);
this.Controls.Add(this.msMain);
this.Controls.Add(this.dispMinutes);
this.Controls.Add(this.lblDescription);
this.Controls.Add(this.lblTime);
this.Controls.Add(this.lblProject);
this.Controls.Add(this.dispName);
this.Controls.Add(this.lblName);
this.Controls.Add(this.lblMinutes);
this.Controls.Add(this.btnSave);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.HelpButton = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MainMenuStrip = this.msMain;
this.MaximizeBox = false;
this.Name = "frmTimeKeeper";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Time Keeper";
this.Activated += new System.EventHandler(this.frmTimeKeeper_Activated);
this.Deactivate += new System.EventHandler(this.frmTimeKeeper_Deactivate);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmTimeKeeper_FormClosing);
this.Load += new System.EventHandler(this.frmTimeKeeper_Load);
this.cmsNotifyIcon.ResumeLayout(false);
this.msMain.ResumeLayout(false);
this.msMain.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Timer timInterval;
private System.Windows.Forms.NotifyIcon niTimeKeeper;
private System.Windows.Forms.ContextMenuStrip cmsNotifyIcon;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Timer timFlasher;
private System.Windows.Forms.Timer timOpened;
private System.Windows.Forms.Label lblMinutes;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.Label dispName;
private System.Windows.Forms.Label lblProject;
private System.Windows.Forms.Label lblTime;
private System.Windows.Forms.Label lblDescription;
private System.Windows.Forms.ColorDialog cdButtonColor;
private System.Windows.Forms.Label dispMinutes;
private System.Windows.Forms.MenuStrip msMain;
private System.Windows.Forms.ToolStripMenuItem timeKeeperToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prompToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prompt5ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prompt10ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prompt15ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prompt30ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prompt60ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem windowTransparencyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem trans0StripMenuItem;
private System.Windows.Forms.ToolStripMenuItem trans25StripMenuItem;
private System.Windows.Forms.ToolStripMenuItem trans50StripMenuItem;
private System.Windows.Forms.ToolStripMenuItem trans75StripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem resetTimeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pauseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem minutes15ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem minutes30ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem hour1ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem hour2ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem hour8ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearPauseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearToolStripMenuItem;
private System.Windows.Forms.LinkLabel llDiscardTime;
private System.Windows.Forms.ToolStripMenuItem buttonColorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem detailReportToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem summaryReportToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem nameToolStripMenuItem;
private System.Windows.Forms.TextBox timeBox7;
private System.Windows.Forms.TextBox timeBox6;
private System.Windows.Forms.TextBox timeBox5;
private System.Windows.Forms.TextBox timeBox4;
private System.Windows.Forms.TextBox timeBox3;
private System.Windows.Forms.TextBox timeBox2;
private System.Windows.Forms.TextBox descriptionBox7;
private System.Windows.Forms.TextBox descriptionBox6;
private System.Windows.Forms.TextBox descriptionBox5;
private System.Windows.Forms.TextBox descriptionBox4;
private System.Windows.Forms.TextBox descriptionBox3;
private System.Windows.Forms.TextBox descriptionBox2;
private System.Windows.Forms.TextBox descriptionBox1;
private System.Windows.Forms.TextBox timeBox1;
private GroupedComboBox projectBox7;
private GroupedComboBox projectBox6;
private GroupedComboBox projectBox5;
private GroupedComboBox projectBox4;
private GroupedComboBox projectBox3;
private GroupedComboBox projectBox2;
private GroupedComboBox projectBox1;
private System.Windows.Forms.ToolStripMenuItem projectToolStripMenuItem;
private System.Windows.Forms.Label deleteBtn1;
private System.Windows.Forms.Label deleteBtn2;
private System.Windows.Forms.Label deleteBtn3;
private System.Windows.Forms.Label deleteBtn4;
private System.Windows.Forms.Label deleteBtn5;
private System.Windows.Forms.Label deleteBtn6;
private System.Windows.Forms.Label deleteBtn7;
private System.Windows.Forms.ToolStripMenuItem dailySummaryToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem reportsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem removeUnusedRowsToolStripMenuItem;
}
}
| 47.724346 | 162 | 0.736245 | [
"MIT"
] | gyphie/time-keeper | time-keeper/MainForm.Designer.cs | 47,454 | C# |
using System;
using UnityEngine;
namespace XCharts
{
/// <summary>
/// </summary>
[Serializable]
public class LineArrow
{
public enum Position
{
/// <summary>
/// 末端箭头
/// </summary>
End,
/// <summary>
/// 头端箭头
/// </summary>
Start
}
[SerializeField] private bool m_Show;
[SerializeField] Position m_Position;
[SerializeField] private float m_Width = 10;
[SerializeField] private float m_Height = 15;
[SerializeField] private float m_Offset = 0;
[SerializeField] private float m_Dent = 3;
/// <summary>
/// Whether to show the arrow.
/// 是否显示箭头。
/// </summary>
public bool show { get { return m_Show; } set { m_Show = value; } }
/// <summary>
/// The position of arrow.
/// 箭头位置。
/// </summary>
public Position position { get { return m_Position; } set { m_Position = value; } }
/// <summary>
/// The widht of arrow.
/// 箭头宽。
/// </summary>
public float width { get { return m_Width; } set { m_Width = value; } }
/// <summary>
/// The height of arrow.
/// 箭头高。
/// </summary>
public float height { get { return m_Height; } set { m_Height = value; } }
/// <summary>
/// The offset of arrow.
/// 箭头偏移。
/// </summary>
public float offset { get { return m_Offset; } set { m_Offset = value; } }
/// <summary>
/// The dent of arrow.
/// 箭头的凹度。
/// </summary>
public float dent { get { return m_Dent; } set { m_Dent = value; } }
}
} | 29.316667 | 91 | 0.486072 | [
"MIT"
] | insominx/unity-ugui-XCharts | Scripts/UI/Internal/LineArrow.cs | 1,837 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DurableTask.TypedProxy;
using KeyVault.Acmebot.Contracts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace KeyVault.Acmebot
{
public class GetDnsZonesFunctions
{
[FunctionName(nameof(GetDnsZones))]
public async Task<IList<string>> GetDnsZones([OrchestrationTrigger] IDurableOrchestrationContext context)
{
var activity = context.CreateActivityProxy<ISharedFunctions>();
var zones = await activity.GetZones();
return zones.Select(x => x.Name).ToArray();
}
[FunctionName(nameof(GetDnsZones_HttpStart))]
public async Task<IActionResult> GetDnsZones_HttpStart(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "get-dns-zones")] HttpRequest req,
[DurableClient] IDurableClient starter,
ILogger log)
{
if (!req.HttpContext.User.Identity.IsAuthenticated)
{
return new UnauthorizedObjectResult("Need to activate EasyAuth.");
}
// Function input comes from the request content.
string instanceId = await starter.StartNewAsync(nameof(GetDnsZones), null);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
return await starter.WaitForCompletionOrCreateCheckStatusResponseAsync(req, instanceId, TimeSpan.FromMinutes(1));
}
}
} | 34 | 125 | 0.692353 | [
"Apache-2.0"
] | adamgoodbar/keyvault-acmebot | KeyVault.Acmebot/GetDnsZonesFunctions.cs | 1,700 | C# |
using System;
namespace AxSoft.TemplateEmail
{
public static class TypeHelper
{
public static bool IsSimpleOrNullableType(Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
type = Nullable.GetUnderlyingType(type);
}
return IsSimpleType(type);
}
public static bool IsSimpleType(Type type)
{
if (type == null) throw new ArgumentNullException("type");
return type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(Decimal) || type == typeof(DateTime) || type == typeof(Guid);
}
}
} | 26.958333 | 147 | 0.689335 | [
"MIT"
] | blockworks-com/vstsStatusReport | StatusReport.Service/TypeHelper.cs | 649 | C# |
#region license
// Copyright 2004-2012 Castle Project, Henrik Feldt &contributors - https://github.com/castleproject
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.IO;
using Castle.IO.Tests.TestClasses;
using NUnit.Framework;
using SharpTestsEx;
namespace Castle.IO.Tests.copying_files
{
[TestFixture(typeof (TestInMemoryFileSystem))]
[TestFixture(typeof (TestLocalFileSystem))]
public class locked_file<T> : files<T> where T : IFileSystem, new()
{
[TestCase(FileShare.None)]
[TestCase(FileShare.Write)]
[TestCase(FileShare.Delete)]
public void cannot_be_copied(FileShare fileShare)
{
var tempFile = FileSystem.CreateTempFile();
using (tempFile.Open(FileMode.Append, FileAccess.Write, fileShare))
{
((Action) (
() => tempFile.CopyTo(tempFile.Parent.GetFile(Path.GetRandomFileName()))))
.Should().Throw<IOException>();
}
}
}
} | 32.108696 | 101 | 0.7109 | [
"Apache-2.0"
] | Huddle/Castle.Transactions | src/Castle.IO.Tests/copying_files/locked_file.cs | 1,479 | C# |
using System;
using System.Linq.Expressions;
using System.Reflection;
using static Towel.Syntax;
namespace Towel
{
/// <summary>Contains generic static numerical constant values.</summary>
/// <typeparam name="T">The generic numeric type of the constants.</typeparam>
public static class Constant<T>
{
/// <summary>Zero [0]</summary>
public static readonly T Zero = Convert<int, T>(0);
/// <summary>One [1]</summary>
public static readonly T One = Convert<int, T>(1);
/// <summary>Two [2]</summary>
public static readonly T Two = Convert<int, T>(2);
/// <summary>Three [3]</summary>
public static readonly T Three = Convert<int, T>(3);
/// <summary>Four [4]</summary>
public static readonly T Four = Convert<int, T>(4);
/// <summary>Ten [10]</summary>
public static readonly T Ten = Convert<int, T>(10);
/// <summary>Negative One [-1]</summary>
public static readonly T NegativeOne = Convert<int, T>(-1);
/// <summary>π [3.14...]</summary>
public static readonly T Pi = ComputePi();
/// <summary>π [3.14...]</summary>
public static readonly T π = Pi;
/// <summary>2π [6.28...]</summary>
public static readonly T Pi2 = Multiplication(Two, Pi);
/// <summary>2π [6.28...]</summary>
public static readonly T π2 = Pi2;
/// <summary>π / 2</summary>
public static readonly T PiOver2 = Division(Pi, Two);
/// <summary>π / 2</summary>
public static readonly T πOver2 = PiOver2;
/// <summary>3π/2</summary>
public static readonly T Pi3Over2 = Division(Multiplication(Three, Pi), Two);
/// <summary>3π/2</summary>
public static readonly T π3Over2 = Pi3Over2;
/// <summary>4/(π^2)</summary>
public static readonly T FourOverPiSquared = Division(Multiplication(Three, Pi), Two);
/// <summary>4/(π^2)</summary>
public static readonly T FourOverπSquared = FourOverPiSquared;
/// <summary>-4/(π^2)</summary>
public static readonly T Negative4OverPiSquared = Negation(FourOverPiSquared);
/// <summary>-4/(π^2)</summary>
public static readonly T Negative4OverπSquared = Negative4OverPiSquared;
#region Pi
/// <summary>Computes the value of pi for the provided generic type.</summary>
/// <param name="predicate">The cancellation token for cutting off computation.</param>
/// <returns>The computed value of pi.</returns>
public static T ComputePi(Predicate<T> predicate = null)
{
// Series: PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))
// more terms in computation inproves accuracy
if (predicate is null)
{
int iterations = 0;
predicate = PI => ++iterations < 100;
}
T pi = Constant<T>.One;
T previous = Constant<T>.Zero;
for (int i = 1; InequalTo(previous, pi) && predicate(pi); i++)
{
previous = pi;
pi = Constant<T>.One;
for (int j = i; j >= 1; j--)
{
#region Without Custom Runtime Compilation
//T J = FromInt32<T>(j);
//T a = Add(Multiply(Constant<T>.Two, J), Constant<T>.One);
//T b = Divide(J, a);
//T c = Multiply(b, pi);
//T d = Add(Constant<T>.One, c);
//pi = d;
#endregion
pi = AddMultiplyDivideAddImplementation.Function(Convert<int, T>(j), pi);
}
pi = Multiplication(Constant<T>.Two, pi);
}
// this is necessary because user's classes may not contain <, >, etc. operators, but they shouldn't be required
// to define them to work with, say, matrices
if (!(typeof(T).GetMethod("op_GreaterThanOrEqual", BindingFlags.Static | BindingFlags.Public) is null) || typeof(T) == typeof(int))
pi = Maximum(pi, Constant<T>.Three);
return pi;
}
internal static class AddMultiplyDivideAddImplementation
{
internal static Func<T, T, T> Function = (j, pi) =>
{
ParameterExpression J = Expression.Parameter(typeof(T));
ParameterExpression PI = Expression.Parameter(typeof(T));
Expression BODY = Expression.Add(
Expression.Constant(One),
Expression.Multiply(
PI,
Expression.Divide(
J,
Expression.Add(
Expression.Multiply(
Expression.Constant(Two),
J),
Expression.Constant(One)))));
Function = Expression.Lambda<Func<T, T, T>>(BODY, J, PI).Compile();
return Function(j, pi);
};
}
#endregion
#region Golden Ratio
#if false
/// <summary>GoldenRatio [(1 + SquareRoot(5)) / 2]</summary>
//public static readonly T GoldenRatio = Symbolics.ParseAndSimplifyToConstant<T>("(1 + SquareRoot(5)) / 2");
/// <summary>Epsilon (1.192092896...e-012f)</summary>
//public static readonly T Epsilon = Compute.ComputeEpsilon<T>();
#endif
#endregion
#region Epsilon
#if false
// Note sure if this method will be necessary.
//internal static T ComputeEpsilon<T>()
//{
// if (typeof(T) == typeof(float))
// {
// return (T)(object)float.Epsilon;
// }
//
//}
#endif
#endregion
}
}
| 32.059603 | 134 | 0.64181 | [
"MIT"
] | WhiteBlackGoose/Towel | Sources/Towel/Constant.cs | 4,861 | C# |
using Mina.Core.Session;
using Mina.Filter.Codec;
namespace UCanSoft.PortForwarding.Common.Codec.Direct
{
public class DirectCodecFactory : IProtocolCodecFactory
{
private readonly DirectEncoder _encoder;
private readonly DirectDecoder _decoder;
public DirectCodecFactory()
{
_encoder = new DirectEncoder();
_decoder = new DirectDecoder();
}
IProtocolEncoder IProtocolCodecFactory.GetEncoder(IoSession session)
{
return _encoder;
}
IProtocolDecoder IProtocolCodecFactory.GetDecoder(IoSession session)
{
return _decoder;
}
}
}
| 24.25 | 76 | 0.642121 | [
"MIT"
] | UCan927/PortForwarding | Source Code/UCanSoft.PortForwarding.Common/Codec/Direct/DirectCodecFactory.cs | 681 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Live-Video
* 直播管理API
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace JDCloudSDK.Live.Model
{
/// <summary>
/// playDataStatisticResult
/// </summary>
public class PlayDataStatisticResult
{
///<summary>
/// 时间点
///
///</summary>
public string StartTime{ get; set; }
///<summary>
/// 时间点
///
///</summary>
public string EndTime{ get; set; }
///<summary>
/// Data
///</summary>
public PlayDataStatisticResultData Data{ get; set; }
}
}
| 23.75 | 76 | 0.633835 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Live/Model/PlayDataStatisticResult.cs | 1,350 | C# |
using RelhaxModpack.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RelhaxModpack.Database
{
/// <summary>
/// A structure that is used to track the relative path of a user file (like session stats),
/// and the root path between the installer and WoT directory.
/// </summary>
public struct UserDataFile
{
/// <summary>
/// Create an instance of the UserDataFile struct.
/// </summary>
/// <param name="dataFileToCopy">The UserDataFile struct to copy.</param>
public UserDataFile(UserDataFile dataFileToCopy)
{
this.WoTRoot = dataFileToCopy.WoTRoot;
this.TempSaveRoot = dataFileToCopy.TempSaveRoot;
this.FilePath = dataFileToCopy.FilePath;
}
/// <summary>
/// The WoT root directory where the UserDataFile is from.
/// </summary>
public string WoTRoot;
/// <summary>
/// The directory path to the installer's temporary folder for holding user files during an installation.
/// </summary>
public string TempSaveRoot;
/// <summary>
/// The relative path of the user file.
/// </summary>
public string FilePath;
}
/// <summary>
/// An object that represents cache files generated by mods that should be backed up and restored as to not loose cache data (like session stats or auto equip data).
/// </summary>
public class UserFile : XmlComponent, IXmlSerializable
{
/// <summary>
/// Create an instance of the UserFile class.
/// </summary>
public UserFile() : base()
{
}
/// <summary>
/// Create an instance of the UserFile class, copying values from a given UserFile object.
/// </summary>
/// <param name="userfileToCopy">The UserFile instance to copy from.</param>
public UserFile(UserFile userfileToCopy) : base(userfileToCopy)
{
this.Pattern = userfileToCopy.Pattern;
}
/// <summary>
/// Create an instance of the UserFile class, copying values and list contents from a given UserFile object.
/// </summary>
/// <param name="userfileToCopy">The UserFile instance to copy from.</param>
/// <param name="deep">If true, copy the list of files saved.</param>
public UserFile(UserFile userfileToCopy, bool deep) : this(userfileToCopy)
{
if (deep)
foreach (UserDataFile dataFile in userfileToCopy.FilesSaved)
this.FilesSaved.Add(new UserDataFile(dataFile));
}
#region Xml serialization V1
/// <summary>
/// Defines a list of properties in the class to be serialized into xml attributes.
/// </summary>
/// <returns>A list of string property names.</returns>
/// <remarks>Xml attributes will always be written, xml elements are optional.</remarks>
public string[] PropertiesForSerializationAttributes()
{
return new string[] { nameof(Pattern) };
}
/// <summary>
/// Defines a list of properties in the class to be serialized into xml elements.
/// </summary>
/// <returns>A list of string property names.</returns>
/// <remarks>Xml attributes will always be written, xml elements are optional.</remarks>
public string[] PropertiesForSerializationElements()
{
return new string[] { };
}
#endregion
#region Xml serialization V2
/// <summary>
/// Creates the list of xml components (attributes and elements) to use for xml serialization according to the 1.0 xml schema.
/// </summary>
/// <returns>The list of xml components, describing the class property name, xml node name, and xml node type</returns>
/// <remarks>The order of the properties in the list is used to consider where in the xml document they should be located (it tracks order).</remarks>
/// <seealso cref="XmlDatabaseProperty"/>
protected override List<XmlDatabaseProperty> GetXmlDatabasePropertiesV1Dot0()
{
List<XmlDatabaseProperty> xmlDatabaseProperties = new List<XmlDatabaseProperty>()
{
//list attributes
new XmlDatabaseProperty() { XmlName = nameof(Pattern), XmlEntryType = Utilities.Enums.XmlEntryType.XmlAttribute, PropertyName = nameof(Pattern) }
};
return xmlDatabaseProperties;
}
/// <summary>
/// Creates the list of xml components (attributes and elements) to use for xml serialization according to the 1.1 xml schema.
/// </summary>
/// <returns>The list of xml components, describing the class property name, xml node name, and xml node type</returns>
/// <remarks>The order of the properties in the list is used to consider where in the xml document they should be located (it tracks order).</remarks>
/// <seealso cref="XmlDatabaseProperty"/>
protected override List<XmlDatabaseProperty> GetXmlDatabasePropertiesV1Dot1()
{
return this.GetXmlDatabasePropertiesV1Dot0();
}
/// <summary>
/// Creates the list of xml components (attributes and elements) to use for xml serialization according to the 1.2 xml schema.
/// </summary>
/// <returns>The list of xml components, describing the class property name, xml node name, and xml node type</returns>
/// <remarks>The order of the properties in the list is used to consider where in the xml document they should be located (it tracks order).</remarks>
/// <seealso cref="XmlDatabaseProperty"/>
protected override List<XmlDatabaseProperty> GetXmlDatabasePropertiesV1Dot2()
{
return this.GetXmlDatabasePropertiesV1Dot1();
}
#endregion
/// <summary>
/// The path or pattern to a file or files to backup to a temporary directory.
/// </summary>
public string Pattern { get; set; } = string.Empty;
/// <summary>
/// The list of actual files saved to the temporary backup directory. Contains the full path and file name
/// </summary>
public List<UserDataFile> FilesSaved { get; } = new List<UserDataFile>();
/// <summary>
/// The string representation of the UserFile object.
/// </summary>
/// <returns>The string pattern.</returns>
public override string ToString()
{
return Pattern;
}
/// <summary>
/// Create a copy of the UserFile object.
/// </summary>
/// <param name="userFileToCopy">The object to copy.</param>
/// <returns>A new UserFile object with the same values.</returns>
public static UserFile Copy(UserFile userFileToCopy)
{
return new UserFile(userFileToCopy);
}
/// <summary>
/// Create a deep copy of the UserFile object.
/// </summary>
/// <param name="userFileToCopy">The object to copy.</param>
/// <returns>A new UserFile object with the same values and new list elements with the same values.</returns>
public static UserFile DeepCopy(UserFile userFileToCopy)
{
return new UserFile(userFileToCopy, true);
}
}
}
| 42.123596 | 169 | 0.620832 | [
"Apache-2.0"
] | Willster419/RelicModManager | RelhaxModpack/RelhaxModpack/Database/UserFile.cs | 7,500 | C# |
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Web.Mvc;
//namespace ND.MCJ.AOP.Transaction
//{
// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
// public class TransactionAttribute : ActionFilterAttribute
// {
// private IDbContext _dbContext;
// private bool _delegateTransactionSupport;
// public IDbContext DbContext
// {
// get
// {
// if (_dbContext == null) _dbContext = SmartServiceLocator<IDbContext>.GetService();
// return _dbContext;
// }
// }
// public override void OnActionExecuting(ActionExecutingContext filterContext)
// {
// _delegateTransactionSupport = ShouldDelegateTransactionSupport(filterContext);
// if (_delegateTransactionSupport) return;
// DbContext.BeginTransaction();
// }
// public override void OnActionExecuted(ActionExecutedContext filterContext)
// {
// if (_delegateTransactionSupport) return;
// if (DbContext.IsActive)
// {
// if (filterContext.Exception == null)
// {
// DbContext.CommitTransaction();
// }
// else
// {
// DbContext.RollbackTransaction();
// }
// }
// }
// private static bool ShouldDelegateTransactionSupport(ActionExecutingContext context)
// {
// var attrs = context.ActionDescriptor.GetCustomAttributes(typeof(TransactionalActionBaseAttribute), false);
// return attrs.Length > 0;
// }
// }
//}
| 30.59322 | 121 | 0.550139 | [
"Apache-2.0"
] | PengXX0/ND.MCJ | Infrastructure/ND.MCJ.AOP/Transaction/TransactionAttribute.cs | 1,807 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace UnitTestingAspNetMvcKata.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
| 20.818182 | 97 | 0.583697 | [
"MIT"
] | danilojrr/UnitTestingAspNetMvcKata | UnitTestingAspNetMvcKata.Web/Controllers/HomeController.cs | 689 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using ESFA.DC.PeriodEnd.ReportService.Reports.Interface.AppsCoInvestment.Model;
namespace ESFA.DC.PeriodEnd.ReportService.Reports.Tests.AppsCoInvestment.Builders
{
public class LearnerEmploymentStatusBuilder: AbstractBuilder<LearnerEmploymentStatus>
{
public static DateTime DateEmpStat { get; } = new DateTime(2019, 8, 1);
public static int? EmpId { get; } = 1234;
public LearnerEmploymentStatusBuilder()
{
modelObject = new LearnerEmploymentStatus()
{
DateEmpStatApp = DateEmpStat,
EmpId = EmpId
};
}
}
}
| 29.083333 | 89 | 0.663324 | [
"MIT"
] | SkillsFundingAgency/DC-2021-PeriodEnd-ReportService | src/ESFA.DC.PeriodEnd.ReportService.Reports.Tests/AppsCoInvestment/Builders/LearnerEmploymentStatusBuilder.cs | 700 | C# |
using SpiceSharp.General;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace SpiceSharp.ParameterSets
{
/// <summary>
/// The default implementation of an <see cref="IParameterSetCollection"/>. This implementation
/// also makes the collection itself an <see cref="IParameterSet"/>.
/// </summary>
/// <seealso cref="IParameterSetCollection" />
/// <seealso cref="IParameterSet" />
public class ParameterSetCollection : ParameterSet,
IParameterSetCollection
{
/// <inheritdoc/>
public virtual P GetParameterSet<P>() where P : IParameterSet, ICloneable<P>
{
if (this is IParameterized<P> parameterized)
return parameterized.Parameters;
else
{
foreach (var ps in ParameterSets)
{
if (ps is P result)
return result;
}
}
throw new TypeNotFoundException(typeof(P), Properties.Resources.ParameterSets_NotDefined.FormatString(typeof(P).FullName));
}
/// <inheritdoc/>
public virtual bool TryGetParameterSet<P>(out P value) where P : IParameterSet, ICloneable<P>
{
if (this is IParameterized<P> parameterized)
{
value = parameterized.Parameters;
return true;
}
else
{
foreach (var ps in ParameterSets)
{
if (ps is P result)
{
value = result;
return true;
}
}
}
value = default;
return false;
}
/// <inheritdoc/>
public virtual IEnumerable<IParameterSet> ParameterSets
{
get
{
foreach (var type in InterfaceCache.Get(GetType()).Where(t =>
{
var info = t.GetTypeInfo();
return info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IParameterized<>);
}))
{
// Get the value associated with this interface (returned by IParameterized<>.Parameters)
yield return (IParameterSet)type.GetTypeInfo().GetProperty("Parameters").GetValue(this);
}
}
}
/// <inheritdoc/>
public override void SetParameter<P>(string name, P value)
{
// First try our parameter sets
foreach (var ps in ParameterSets)
{
if (ps.TrySetParameter(name, value))
return;
}
base.SetParameter(name, value);
}
/// <inheritdoc/>
public override bool TrySetParameter<P>(string name, P value)
{
// First try our parameter sets
foreach (var ps in ParameterSets)
{
if (ps.TrySetParameter(name, value))
return true;
}
return base.TrySetParameter(name, value);
}
/// <inheritdoc/>
public override P GetProperty<P>(string name)
{
// First try our parameter sets
foreach (var ps in ParameterSets)
{
if (ps.TryGetProperty(name, out P value))
return value;
}
return base.GetProperty<P>(name);
}
/// <inheritdoc/>
public override bool TryGetProperty<P>(string name, out P value)
{
// First try our parameter sets
foreach (var ps in ParameterSets)
{
if (ps.TryGetProperty(name, out value))
return true;
}
return base.TryGetProperty(name, out value);
}
/// <inheritdoc/>
public override Action<P> CreateParameterSetter<P>(string name)
{
// First try our parameter sets
foreach (var ps in ParameterSets)
{
var setter = ps.CreateParameterSetter<P>(name);
if (setter != null)
return setter;
}
return base.CreateParameterSetter<P>(name);
}
/// <inheritdoc/>
public override Func<P> CreatePropertyGetter<P>(string name)
{
// First try our parameter sets
foreach (var ps in ParameterSets)
{
var getter = ps.CreatePropertyGetter<P>(name);
if (getter != null)
return getter;
}
return base.CreatePropertyGetter<P>(name);
}
}
}
| 32.295302 | 135 | 0.499792 | [
"MIT"
] | Neos-Metaverse/SpiceSharp | SpiceSharp/Parameters/ParameterSetCollection.cs | 4,814 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace dpz3 {
/// <summary>
/// 文件夹操作
/// </summary>
public static class Folder {
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="path"></param>
public static void Create(string path) {
if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path);
}
/// <summary>
/// 获取所属子文件夹
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string[] GetDirectories(string path) {
return System.IO.Directory.GetDirectories(path);
}
/// <summary>
/// 获取所属文件
/// </summary>
/// <param name="path"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string[] GetFiles(string path, string pattern = null) {
if (pattern == null) {
return System.IO.Directory.GetFiles(path);
} else {
return System.IO.Directory.GetFiles(path, pattern);
}
}
}
}
| 26.066667 | 93 | 0.512361 | [
"MIT"
] | dpzsoft/dotnet-dpz3 | dpz3/Folder.cs | 1,223 | C# |
using System;
using LuaInterface;
using System.Collections.Generic;
using System.Collections;
public class System_Collections_Generic_Dictionary_ValueCollectionWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(Dictionary<,>.ValueCollection), typeof(System.Object), "ValueCollection");
L.RegFunction("CopyTo", CopyTo);
L.RegFunction("GetEnumerator", GetEnumerator);
L.RegFunction("New", _CreateSystem_Collections_Generic_Dictionary_ValueCollection);
L.RegFunction("__tostring", ToLua.op_ToString);
L.RegVar("Count", get_Count, null);
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _CreateSystem_Collections_Generic_Dictionary_ValueCollection(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1)
{
object arg0 = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>));
Type kv = arg0.GetType().GetNestedType("ValueCollection");
object obj = Activator.CreateInstance(kv, arg0);
ToLua.PushObject(L, obj);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to ctor method: System.Collections.Generic.Dictionary.ValueCollection.New");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CopyTo(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 3);
Type kt, kv;
object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>.ValueCollection), out kt, out kv);
object arg0 = ToLua.CheckObject(L, 2, kv.MakeArrayType());
int arg1 = (int)LuaDLL.luaL_checknumber(L, 3);
LuaMethodCache.CallSingleMethod("CopyTo", obj, arg0, arg1);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetEnumerator(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>.ValueCollection));
IEnumerator o = (IEnumerator)LuaMethodCache.CallSingleMethod("GetEnumerator", obj);
ToLua.Push(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_Count(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
int ret = (int)LuaMethodCache.CallSingleMethod("get_Count", o);
LuaDLL.lua_pushinteger(L, ret);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index Count on a nil value");
}
}
}
| 31.53 | 139 | 0.584523 | [
"Apache-2.0"
] | 871041532/LuaProfiler-For-Unity | ToLuaClient/Assets/ToLua/BaseType/System_Collections_Generic_Dictionary_ValueCollectionWrap.cs | 3,155 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EF.DbContextFactory.StructureMap")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Geovanny Alzate Sandoval")]
[assembly: AssemblyProduct("EF.DbContextFactory.StructureMap")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4a1e97db-c412-4b26-a96e-ee978a131173")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
| 39.351351 | 84 | 0.754808 | [
"MIT"
] | Meberem/EF.DbContextFactory | src/Extensions/EF.DbContextFactory.StructureMap/Properties/AssemblyInfo.cs | 1,459 | C# |
#pragma checksum "..\..\..\MainWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1323492F21F1F696196680E7BE9C4025FFE995B2"
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
using MaterialDesignThemes.Wpf;
using MaterialDesignThemes.Wpf.Converters;
using MaterialDesignThemes.Wpf.Transitions;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Controls.Ribbon;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using Wpf_Hart;
namespace Wpf_Hart {
/// <summary>
/// MainWindow
/// </summary>
public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {
#line 61 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Minimaize;
#line default
#line hidden
#line 62 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Chande;
#line default
#line hidden
#line 63 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Exit;
#line default
#line hidden
#line 66 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Grid GridMenu;
#line default
#line hidden
#line 69 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonCloseMenu;
#line default
#line hidden
#line 72 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonOpenMenu;
#line default
#line hidden
#line 76 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ListView List_menu;
#line default
#line hidden
#line 117 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TabControl Tab_control_main;
#line default
#line hidden
#line 119 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Grid grid;
#line default
#line hidden
#line 123 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox ComboBox_UsbDevaise;
#line default
#line hidden
#line 124 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal MaterialDesignThemes.Wpf.Badged usb_stats;
#line default
#line hidden
#line 126 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button B_findDevaise;
#line default
#line hidden
#line 127 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button B_findDevaiseStop;
#line default
#line hidden
#line 133 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.DataGrid listBox_dev;
#line default
#line hidden
#line 149 "..\..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ProgressBar Skan_progres;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/Wpf_Hart;component/mainwindow.xaml", System.UriKind.Relative);
#line 1 "..\..\..\MainWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
#line 43 "..\..\..\MainWindow.xaml"
((System.Windows.Controls.Grid)(target)).MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(this.Grid_MouseLeftButtonDown);
#line default
#line hidden
return;
case 2:
this.Minimaize = ((System.Windows.Controls.Button)(target));
#line 61 "..\..\..\MainWindow.xaml"
this.Minimaize.Click += new System.Windows.RoutedEventHandler(this.Minimaize_Click);
#line default
#line hidden
return;
case 3:
this.Chande = ((System.Windows.Controls.Button)(target));
#line 62 "..\..\..\MainWindow.xaml"
this.Chande.Click += new System.Windows.RoutedEventHandler(this.stateChanged);
#line default
#line hidden
return;
case 4:
this.Exit = ((System.Windows.Controls.Button)(target));
#line 63 "..\..\..\MainWindow.xaml"
this.Exit.Click += new System.Windows.RoutedEventHandler(this.Exit_Click);
#line default
#line hidden
return;
case 5:
this.GridMenu = ((System.Windows.Controls.Grid)(target));
return;
case 6:
this.ButtonCloseMenu = ((System.Windows.Controls.Button)(target));
#line 69 "..\..\..\MainWindow.xaml"
this.ButtonCloseMenu.Click += new System.Windows.RoutedEventHandler(this.ButtonCloseMenu_Click);
#line default
#line hidden
return;
case 7:
this.ButtonOpenMenu = ((System.Windows.Controls.Button)(target));
#line 72 "..\..\..\MainWindow.xaml"
this.ButtonOpenMenu.Click += new System.Windows.RoutedEventHandler(this.ButtonOpenMenu_Click);
#line default
#line hidden
return;
case 8:
this.List_menu = ((System.Windows.Controls.ListView)(target));
#line 76 "..\..\..\MainWindow.xaml"
this.List_menu.PreviewMouseUp += new System.Windows.Input.MouseButtonEventHandler(this.List_menu_MouseDown);
#line default
#line hidden
return;
case 9:
this.Tab_control_main = ((System.Windows.Controls.TabControl)(target));
return;
case 10:
this.grid = ((System.Windows.Controls.Grid)(target));
return;
case 11:
this.ComboBox_UsbDevaise = ((System.Windows.Controls.ComboBox)(target));
#line 123 "..\..\..\MainWindow.xaml"
this.ComboBox_UsbDevaise.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.ComboBox_UsbDevaise_SelectionChanged);
#line default
#line hidden
return;
case 12:
this.usb_stats = ((MaterialDesignThemes.Wpf.Badged)(target));
return;
case 13:
this.B_findDevaise = ((System.Windows.Controls.Button)(target));
#line 126 "..\..\..\MainWindow.xaml"
this.B_findDevaise.Click += new System.Windows.RoutedEventHandler(this.B_findDevaise_Click);
#line default
#line hidden
return;
case 14:
this.B_findDevaiseStop = ((System.Windows.Controls.Button)(target));
#line 127 "..\..\..\MainWindow.xaml"
this.B_findDevaiseStop.Click += new System.Windows.RoutedEventHandler(this.B_findDevaiseStop_Click);
#line default
#line hidden
return;
case 15:
this.listBox_dev = ((System.Windows.Controls.DataGrid)(target));
return;
case 16:
this.Skan_progres = ((System.Windows.Controls.ProgressBar)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 38.429032 | 157 | 0.605137 | [
"MIT"
] | TviZet/HART_DLL | Wpf_Hart/Wpf_Hart/obj/Debug/netcoreapp3.1/MainWindow.g.cs | 12,049 | C# |
using System;
using TypeRegex;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TypeRegexTest
{
[TestClass]
public class UnicodeGroupTest
{
#region Helper
private class Implementation : UnicodeGroup
{
public Implementation(string set) : base(set)
{
}
protected override string CompositeFormat => "{0}";
}
#endregion
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Contructor_ArgumentNullException_Test()
{
new Implementation(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Contructor_EmptyArgument_Test()
{
new Implementation("");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Contructor_WhiteSpaceArgument_Test()
{
new Implementation(" \t\n\r");
}
[TestMethod]
public void Contructor_Test()
{
new Implementation("Block");
}
[TestMethod]
public void ToString_Test()
{
Assert.AreEqual("Block", new Implementation("Block").ToString());
}
}
}
| 21.716667 | 77 | 0.57099 | [
"MIT"
] | parloti/FluentRegex | TypeRegexTest/CharacterGroup/UnicodeGroupTest.cs | 1,305 | C# |
using System.IO;
using System.Text;
using System.Windows.Controls;
using System.Windows.Documents;
namespace TextPoint
{
/// <summary>
/// Interaction logic for WPFSpellCheck.xaml
/// </summary>
public partial class WpfSpellCheck : UserControl
{
public WpfSpellCheck()
{
//this.rtf = rtf;
InitializeComponent();
var lang = RichTextBox.Language;
RichTextBox.Language = System.Windows.Markup.XmlLanguage.GetLanguage("en-US");
//LoadRTF();
var lang2 = RichTextBox.Language;
}
public void LoadRtf(string rtf)
{
TextRange range = new TextRange(RichTextBox.Document.ContentStart, RichTextBox.Document.ContentEnd);
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(rtf);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);
range.Load(stream, System.Windows.DataFormats.Rtf);
stream.Close();
}
public TextPointer GetStart()
{
return RichTextBox.Document.ContentStart;
}
public TextPointer GetEnd()
{
return RichTextBox.Document.ContentEnd;
}
}
}
| 29.931818 | 112 | 0.599089 | [
"MIT"
] | naxxxe/Transcriber | TextPoint/WPFSpellCheck.xaml.cs | 1,319 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace AsyncInn.Migrations
{
public partial class AddHotelRoomsTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "HotelRoom",
columns: table => new
{
HotelId = table.Column<long>(nullable: false),
RoomId = table.Column<int>(nullable: false),
RoomNumber = table.Column<int>(nullable: false),
Rate = table.Column<decimal>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HotelRoom", x => new { x.HotelId, x.RoomId });
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "HotelRoom");
}
}
}
| 32.064516 | 87 | 0.525151 | [
"MIT"
] | dahlbyk-demo/AsyncInn | AsyncInn/Migrations/20200520193726_AddHotelRoomsTable.cs | 996 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 06:06:54 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static go.builtin;
using fmt = go.fmt_package;
using strings = go.strings_package;
using utf8 = go.unicode.utf8_package;
using bidirule = go.golang.org.x.text.secure.bidirule_package;
using bidi = go.golang.org.x.text.unicode.bidi_package;
using norm = go.golang.org.x.text.unicode.norm_package;
using go;
#nullable enable
namespace go {
namespace vendor {
namespace golang.org {
namespace x {
namespace net
{
public static partial class idna_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
[PromotedStruct(typeof(options))]
public partial struct Profile
{
// options structure promotion - sourced from value copy
private readonly ptr<options> m_optionsRef;
private ref options options_val => ref m_optionsRef.Value;
public ref bool transitional => ref m_optionsRef.Value.transitional;
public ref bool useSTD3Rules => ref m_optionsRef.Value.useSTD3Rules;
public ref bool validateLabels => ref m_optionsRef.Value.validateLabels;
public ref bool verifyDNSLength => ref m_optionsRef.Value.verifyDNSLength;
public ref bool removeLeadingDots => ref m_optionsRef.Value.removeLeadingDots;
public ref ptr<idnaTrie> trie => ref m_optionsRef.Value.trie;
public ref Func<ptr<Profile>, @string, error> fromPuny => ref m_optionsRef.Value.fromPuny;
public ref Func<ptr<Profile>, @string, (@string, bool, error)> mapping => ref m_optionsRef.Value.mapping;
public ref Func<@string, bool> bidirule => ref m_optionsRef.Value.bidirule;
// Constructors
public Profile(NilType _)
{
this.m_optionsRef = new ptr<options>(new options(nil));
}
public Profile(options options = default)
{
this.m_optionsRef = new ptr<options>(options);
}
// Enable comparisons between nil and Profile struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Profile value, NilType nil) => value.Equals(default(Profile));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Profile value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, Profile value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, Profile value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Profile(NilType nil) => default(Profile);
}
[GeneratedCode("go2cs", "0.1.0.0")]
public static Profile Profile_cast(dynamic value)
{
return new Profile(value.options);
}
}
}}}}} | 36.463158 | 117 | 0.635681 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/vendor/golang.org/x/net/idna/idna10.0.0_ProfileStruct.cs | 3,464 | C# |
#if !NET5_0
//-----------------------------------------------------------------------
// <copyright file="BinaryFormatterWrapper.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Wraps the <see cref="BinaryFormatter"/></summary>
//-----------------------------------------------------------------------
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Csla.Serialization
{
/// <summary>
/// Wraps the <see cref="BinaryFormatter"/>
/// in the
/// <see cref="ISerializationFormatter"/>
/// interface so it can be used in a standardized
/// manner.
/// </summary>
public class BinaryFormatterWrapper : ISerializationFormatter
{
private readonly BinaryFormatter _formatter =
new BinaryFormatter();
/// <summary>
/// Converts a serialization stream into an
/// object graph.
/// </summary>
/// <param name="serializationStream">
/// Byte stream containing the serialized data.</param>
/// <returns>A deserialized object graph.</returns>
public object Deserialize(System.IO.Stream serializationStream)
{
return _formatter.Deserialize(serializationStream);
}
/// <summary>
/// Converts a serialization stream into an
/// object graph.
/// </summary>
/// <param name="buffer">
/// Byte stream containing the serialized data.</param>
/// <returns>A deserialized object graph.</returns>
public object Deserialize(byte[] buffer)
{
using var serializationStream = new MemoryStream(buffer);
return _formatter.Deserialize(serializationStream);
}
/// <summary>
/// Converts an object graph into a byte stream.
/// </summary>
/// <param name="serializationStream">
/// Stream that will contain the the serialized data.</param>
/// <param name="graph">Object graph to be serialized.</param>
public void Serialize(System.IO.Stream serializationStream, object graph)
{
_formatter.Serialize(serializationStream, graph);
}
/// <summary>
/// Converts an object graph into a byte stream.
/// </summary>
/// <param name="graph">Object graph to be serialized.</param>
public byte[] Serialize(object graph)
{
using var buffer = new MemoryStream();
_formatter.Serialize(buffer, graph);
buffer.Position = 0;
return buffer.ToArray();
}
/// <summary>
/// Gets a reference to the underlying
/// <see cref="BinaryFormatter"/>
/// object.
/// </summary>
public BinaryFormatter Formatter
{
get
{
return _formatter;
}
}
}
}
#endif | 30.795455 | 77 | 0.613284 | [
"MIT"
] | Brannos1970/csla | Source/Csla/Serialization/BinaryFormatterWrapper.cs | 2,710 | C# |
using System;
namespace ChainUtils.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecP192R1Point
: AbstractFpPoint
{
/**
* Create a point which encodes with point compression.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
*
* @deprecated Use ECCurve.createPoint to construct points
*/
public SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
: this(curve, x, y, false)
{
}
/**
* Create a point that encodes with or without point compresion.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
* @param withCompression
* if true encode with point compression
*
* @deprecated per-point compression property will be removed, refer
* {@link #getEncoded(bool)}
*/
public SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
: base(curve, x, y, withCompression)
{
if ((x == null) != (y == null))
throw new ArgumentException("Exactly one of the field elements is null");
}
internal SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
: base(curve, x, y, zs, withCompression)
{
}
protected override ECPoint Detach()
{
return new SecP192R1Point(null, AffineXCoord, AffineYCoord);
}
public override ECPoint Add(ECPoint b)
{
if (IsInfinity)
return b;
if (b.IsInfinity)
return this;
if (this == b)
return Twice();
var curve = Curve;
SecP192R1FieldElement X1 = (SecP192R1FieldElement)RawXCoord, Y1 = (SecP192R1FieldElement)RawYCoord;
SecP192R1FieldElement X2 = (SecP192R1FieldElement)b.RawXCoord, Y2 = (SecP192R1FieldElement)b.RawYCoord;
var Z1 = (SecP192R1FieldElement)RawZCoords[0];
var Z2 = (SecP192R1FieldElement)b.RawZCoords[0];
uint c;
var tt1 = Nat192.CreateExt();
var t2 = Nat192.Create();
var t3 = Nat192.Create();
var t4 = Nat192.Create();
var Z1IsOne = Z1.IsOne;
uint[] U2, S2;
if (Z1IsOne)
{
U2 = X2.x;
S2 = Y2.x;
}
else
{
S2 = t3;
SecP192R1Field.Square(Z1.x, S2);
U2 = t2;
SecP192R1Field.Multiply(S2, X2.x, U2);
SecP192R1Field.Multiply(S2, Z1.x, S2);
SecP192R1Field.Multiply(S2, Y2.x, S2);
}
var Z2IsOne = Z2.IsOne;
uint[] U1, S1;
if (Z2IsOne)
{
U1 = X1.x;
S1 = Y1.x;
}
else
{
S1 = t4;
SecP192R1Field.Square(Z2.x, S1);
U1 = tt1;
SecP192R1Field.Multiply(S1, X1.x, U1);
SecP192R1Field.Multiply(S1, Z2.x, S1);
SecP192R1Field.Multiply(S1, Y1.x, S1);
}
var H = Nat192.Create();
SecP192R1Field.Subtract(U1, U2, H);
var R = t2;
SecP192R1Field.Subtract(S1, S2, R);
// Check if b == this or b == -this
if (Nat192.IsZero(H))
{
if (Nat192.IsZero(R))
{
// this == b, i.e. this must be doubled
return Twice();
}
// this == -b, i.e. the result is the point at infinity
return curve.Infinity;
}
var HSquared = t3;
SecP192R1Field.Square(H, HSquared);
var G = Nat192.Create();
SecP192R1Field.Multiply(HSquared, H, G);
var V = t3;
SecP192R1Field.Multiply(HSquared, U1, V);
SecP192R1Field.Negate(G, G);
Nat192.Mul(S1, G, tt1);
c = Nat192.AddBothTo(V, V, G);
SecP192R1Field.Reduce32(c, G);
var X3 = new SecP192R1FieldElement(t4);
SecP192R1Field.Square(R, X3.x);
SecP192R1Field.Subtract(X3.x, G, X3.x);
var Y3 = new SecP192R1FieldElement(G);
SecP192R1Field.Subtract(V, X3.x, Y3.x);
SecP192R1Field.MultiplyAddToExt(Y3.x, R, tt1);
SecP192R1Field.Reduce(tt1, Y3.x);
var Z3 = new SecP192R1FieldElement(H);
if (!Z1IsOne)
{
SecP192R1Field.Multiply(Z3.x, Z1.x, Z3.x);
}
if (!Z2IsOne)
{
SecP192R1Field.Multiply(Z3.x, Z2.x, Z3.x);
}
var zs = new ECFieldElement[] { Z3 };
return new SecP192R1Point(curve, X3, Y3, zs, IsCompressed);
}
public override ECPoint Twice()
{
if (IsInfinity)
return this;
var curve = Curve;
var Y1 = (SecP192R1FieldElement)RawYCoord;
if (Y1.IsZero)
return curve.Infinity;
SecP192R1FieldElement X1 = (SecP192R1FieldElement)RawXCoord, Z1 = (SecP192R1FieldElement)RawZCoords[0];
uint c;
var t1 = Nat192.Create();
var t2 = Nat192.Create();
var Y1Squared = Nat192.Create();
SecP192R1Field.Square(Y1.x, Y1Squared);
var T = Nat192.Create();
SecP192R1Field.Square(Y1Squared, T);
var Z1IsOne = Z1.IsOne;
var Z1Squared = Z1.x;
if (!Z1IsOne)
{
Z1Squared = t2;
SecP192R1Field.Square(Z1.x, Z1Squared);
}
SecP192R1Field.Subtract(X1.x, Z1Squared, t1);
var M = t2;
SecP192R1Field.Add(X1.x, Z1Squared, M);
SecP192R1Field.Multiply(M, t1, M);
c = Nat192.AddBothTo(M, M, M);
SecP192R1Field.Reduce32(c, M);
var S = Y1Squared;
SecP192R1Field.Multiply(Y1Squared, X1.x, S);
c = Nat.ShiftUpBits(6, S, 2, 0);
SecP192R1Field.Reduce32(c, S);
c = Nat.ShiftUpBits(6, T, 3, 0, t1);
SecP192R1Field.Reduce32(c, t1);
var X3 = new SecP192R1FieldElement(T);
SecP192R1Field.Square(M, X3.x);
SecP192R1Field.Subtract(X3.x, S, X3.x);
SecP192R1Field.Subtract(X3.x, S, X3.x);
var Y3 = new SecP192R1FieldElement(S);
SecP192R1Field.Subtract(S, X3.x, Y3.x);
SecP192R1Field.Multiply(Y3.x, M, Y3.x);
SecP192R1Field.Subtract(Y3.x, t1, Y3.x);
var Z3 = new SecP192R1FieldElement(M);
SecP192R1Field.Twice(Y1.x, Z3.x);
if (!Z1IsOne)
{
SecP192R1Field.Multiply(Z3.x, Z1.x, Z3.x);
}
return new SecP192R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
}
public override ECPoint TwicePlus(ECPoint b)
{
if (this == b)
return ThreeTimes();
if (IsInfinity)
return b;
if (b.IsInfinity)
return Twice();
var Y1 = RawYCoord;
if (Y1.IsZero)
return b;
return Twice().Add(b);
}
public override ECPoint ThreeTimes()
{
if (IsInfinity || RawYCoord.IsZero)
return this;
// NOTE: Be careful about recursions between TwicePlus and ThreeTimes
return Twice().Add(this);
}
public override ECPoint Negate()
{
if (IsInfinity)
return this;
return new SecP192R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed);
}
}
}
| 30.942446 | 126 | 0.472448 | [
"MIT"
] | assinnata/ChainUtils | ChainUtils.BouncyCastle/math/ec/custom/sec/SecP192R1Point.cs | 8,604 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace <%= projectName %>.Domain
{
public class Country : Abp.Domain.Entities.Entity<string>, Abp.Domain.Entities.IPassivable
{
public string Name { get; set; }
public string Abreviation { get; set; }
public bool IsActive { get; set; }
}
}
| 26 | 94 | 0.70362 | [
"MIT"
] | ronymaychan/generator-pln | app/templates/aspnet/aspnet-core/src/Plenumsoft.Core/Domain/Country.cs | 444 | C# |
using AltNetworkUtility.Repositories.NetworkInterfaceRepository;
using AltNetworkUtility.Services;
using AltNetworkUtility.ViewModels;
using Microsoft.Toolkit.Mvvm.Input;
using Rotorsoft.Forms;
using System;
using System.Collections.ObjectModel;
using System.Net.NetworkInformation;
using System.Windows.Input;
using Xamarin.Forms;
namespace AltNetworkUtility.Tabs.Info
{
public class InfoPageViewModel : ViewModelBase
{
public ObservableCollection<NetworkInterfaceViewModel> AvailableNetworkInterfaces { get; }
private Predicate<object> _NetworkInterfaceFilter;
public Predicate<object> NetworkInterfaceFilter => _NetworkInterfaceFilter;
public ICollectionView? NetworkInterfacesView { get; private set; }
public PreferencesService Preferences { get; }
private NetworkInterfaceViewModel? _SelectedNetworkInterface;
public NetworkInterfaceViewModel? SelectedNetworkInterface
{
get => _SelectedNetworkInterface;
set => SetProperty(ref _SelectedNetworkInterface, value);
}
private bool _ShowAllNetworkInterfaces;
public bool ShowAllNetworkInterfaces
{
get => _ShowAllNetworkInterfaces;
set
{
SetProperty(ref _ShowAllNetworkInterfaces, value);
Preferences.Set(nameof(ShowAllNetworkInterfaces), value);
NetworkInterfacesView?.Refresh();
}
}
public ICommand ToggleShowAllNetworkInterfacesCommand { get; }
public InfoPageViewModel()
{
Preferences = PreferencesService.GetInstance<InfoPageViewModel>();
ShowAllNetworkInterfaces = Preferences.Get(nameof(ShowAllNetworkInterfaces), false);
_NetworkInterfaceFilter = o =>
{
if (o is not NetworkInterfaceViewModel networkInterface)
return false;
if (ShowAllNetworkInterfaces)
return true;
bool shouldShowType = networkInterface.NetworkInterfaceType switch
{
NetworkInterfaceType.AsymmetricDsl => true,
NetworkInterfaceType.Atm => true,
NetworkInterfaceType.BasicIsdn => true,
NetworkInterfaceType.Ethernet => true,
NetworkInterfaceType.Ethernet3Megabit => true,
NetworkInterfaceType.FastEthernetFx => true,
NetworkInterfaceType.FastEthernetT => true,
NetworkInterfaceType.Fddi => true,
NetworkInterfaceType.GenericModem => true,
NetworkInterfaceType.GigabitEthernet => true,
NetworkInterfaceType.HighPerformanceSerialBus => true,
NetworkInterfaceType.IPOverAtm => true,
NetworkInterfaceType.Isdn => true,
NetworkInterfaceType.MultiRateSymmetricDsl => true,
NetworkInterfaceType.Ppp => true,
NetworkInterfaceType.PrimaryIsdn => true,
NetworkInterfaceType.RateAdaptDsl => true,
NetworkInterfaceType.Slip => true,
NetworkInterfaceType.SymmetricDsl => true,
NetworkInterfaceType.TokenRing => true,
NetworkInterfaceType.VeryHighSpeedDsl => true,
NetworkInterfaceType.Wireless80211 => true,
NetworkInterfaceType.Wman => true,
NetworkInterfaceType.Wwanpp => true,
NetworkInterfaceType.Wwanpp2 => true,
NetworkInterfaceType.Loopback => false,
NetworkInterfaceType.Tunnel => false,
_ => false
};
// Mono considers these "Ethernet"
bool filterName = networkInterface.BsdName!.StartsWith("p2p") ||
networkInterface.BsdName.StartsWith("awdl") ||
networkInterface.BsdName.StartsWith("llw");
return shouldShowType && !filterName;
};
ToggleShowAllNetworkInterfacesCommand = new RelayCommand(() =>
ShowAllNetworkInterfaces = !ShowAllNetworkInterfaces);
var repo = DependencyService.Get<Repository>();
AvailableNetworkInterfaces = repo.AsObservable;
}
public void Init(ICollectionView? networkInterfacesView)
{
NetworkInterfacesView = networkInterfacesView;
foreach (var item in AvailableNetworkInterfaces)
item.ParentVM = this;
}
}
}
| 38.104839 | 98 | 0.609947 | [
"MIT"
] | chucker/AltNetworkUtility | AltNetworkUtility/Tabs/Info/InfoPageViewModel.cs | 4,727 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the GNU Affero General Public License, Version 3.
namespace SixLabors.ImageSharp.Processing.Processors.Quantization
{
/// <summary>
/// A palette quantizer consisting of colors as defined in the original second edition of Werner’s Nomenclature of Colours 1821.
/// The hex codes were collected and defined by Nicholas Rougeux <see href="https://www.c82.net/werner"/>
/// </summary>
public class WernerPaletteQuantizer : PaletteQuantizer
{
private static readonly QuantizerOptions DefaultOptions = new QuantizerOptions();
/// <summary>
/// Initializes a new instance of the <see cref="WernerPaletteQuantizer" /> class.
/// </summary>
public WernerPaletteQuantizer()
: this(DefaultOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WernerPaletteQuantizer" /> class.
/// </summary>
/// <param name="options">The quantizer options defining quantization rules.</param>
public WernerPaletteQuantizer(QuantizerOptions options)
: base(Color.WernerPalette, options)
{
}
}
}
| 38.15625 | 132 | 0.659296 | [
"Apache-2.0"
] | fahadabdulaziz/ImageSharp | src/ImageSharp/Processing/Processors/Quantization/WernerPaletteQuantizer.cs | 1,223 | C# |
using EPlast.DataAccess.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace EPlast.BLL.DTO.Club
{
public class ClubAnnualReportDTO
{
public int ID { get; set; }
public AnnualReportStatus Status { get; set; }
[Required(ErrorMessage = "Заповніть поле")]
[Range(0, int.MaxValue, ErrorMessage = "Кількість не може бути від'ємною")]
public int CurrentClubMembers { get; set; }
[Required(ErrorMessage = "Заповніть поле")]
[Range(0, int.MaxValue, ErrorMessage = "Кількість не може бути від'ємною")]
public int CurrentClubFollowers { get; set; }
[Required(ErrorMessage = "Заповніть поле")]
[Range(0, int.MaxValue, ErrorMessage = "Кількість не може бути від'ємною")]
public int ClubEnteredMembersCount { get; set; }
[Required(ErrorMessage = "Заповніть поле")]
[Range(0, int.MaxValue, ErrorMessage = "Кількість не може бути від'ємною")]
public int ClubLeftMembersCount { get; set; }
[StringLength(18, ErrorMessage = "Контактний номер куреня повинен містити 12 цифр")]
public string PhoneNumber { get; set; }
[MaxLength(50, ErrorMessage = "Email куреня не має перевищувати 50 символів")]
public string Email { get; set; }
[MaxLength(256, ErrorMessage = "Посилання на web-сторінку куреня не має перевищувати 256 символів")]
public string ClubURL { get; set; }
[MaxLength(60, ErrorMessage = "Назва вулиці розташування куреня не має перевищувати 60 символів")]
public string Street { get; set; }
[MaxLength(200, ErrorMessage = "Максимально допустима кількість символів 200")]
public string ClubCenters { get; set; }
[MaxLength(500, ErrorMessage = "Максимально допустима кількість символів 500")]
public string KbUSPWishes { get; set; }
public int ClubId { get; set; }
public string ClubName { get; set; }
public DateTime Date { get; set; }
public ClubReportAdministrationDTO Head { get; set; }
public List<ClubReportAdministrationDTO> Admins { get; set; }
public List<ClubMemberHistoryDTO> Members { get; set; }
public List<ClubMemberHistoryDTO> Followers { get; set; }
}
}
| 44.346154 | 108 | 0.667389 | [
"MIT"
] | ita-social-projects/EPlas | EPlast/EPlast.BLL/DTO/Club/ClubAnnualReportDTO.cs | 2,716 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Roslynator.CSharp.CodeFixes;
using Roslynator.Testing.CSharp;
using Xunit;
namespace Roslynator.CSharp.Analysis.Tests
{
public class RCS1159UseGenericEventHandlerTests : AbstractCSharpDiagnosticVerifier<UseGenericEventHandlerAnalyzer, TypeCodeFixProvider>
{
public override DiagnosticDescriptor Descriptor { get; } = DiagnosticDescriptors.UseGenericEventHandler;
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseGenericEventHandler)]
public async Task Test_EventField()
{
await VerifyDiagnosticAndFixAsync(@"
using System;
class C
{
public event [|FooEventHandler|] E;
}
class FooEventArgs : EventArgs
{
}
delegate void FooEventHandler(object sender, FooEventArgs args);
", @"
using System;
class C
{
public event EventHandler<FooEventArgs> E;
}
class FooEventArgs : EventArgs
{
}
delegate void FooEventHandler(object sender, FooEventArgs args);
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseGenericEventHandler)]
public async Task Test_Event()
{
await VerifyDiagnosticAndFixAsync(@"
using System;
class C
{
public event [|FooEventHandler|] E
{
add { }
remove { }
}
}
class FooEventArgs : EventArgs
{
}
delegate void FooEventHandler(object sender, FooEventArgs args);
", @"
using System;
class C
{
public event EventHandler<FooEventArgs> E
{
add { }
remove { }
}
}
class FooEventArgs : EventArgs
{
}
delegate void FooEventHandler(object sender, FooEventArgs args);
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseGenericEventHandler)]
public async Task Test_Interface()
{
await VerifyDiagnosticAndFixAsync(@"
using System;
public interface IC
{
event [|FooEventHandler|] E;
}
public class FooEventArgs : EventArgs
{
}
public delegate void FooEventHandler(object sender, FooEventArgs args);
", @"
using System;
public interface IC
{
event EventHandler<FooEventArgs> E;
}
public class FooEventArgs : EventArgs
{
}
public delegate void FooEventHandler(object sender, FooEventArgs args);
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseGenericEventHandler)]
public async Task Test_InterfaceImplementation()
{
await VerifyDiagnosticAndFixAsync(@"
using System;
interface IC
{
event [|FooEventHandler|] E;
}
class FooEventArgs : EventArgs
{
}
delegate void FooEventHandler(object sender, FooEventArgs args);
", @"
using System;
interface IC
{
event EventHandler<FooEventArgs> E;
}
class FooEventArgs : EventArgs
{
}
delegate void FooEventHandler(object sender, FooEventArgs args);
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseGenericEventHandler)]
public async Task TestNoDiagnostic()
{
await VerifyNoDiagnosticAsync(@"
using System;
using System.Collections.Generic;
using System.ComponentModel;
class Foo2
{
public event EventHandler E;
}
class FooEventArgs : EventArgs
{
}
delegate void FooEventHandler(object sender, FooEventArgs args);
public interface INotifyPropertyChangedEx : INotifyPropertyChanged
{
}
class BaseClass : INotifyPropertyChangedEx
{
public event PropertyChangedEventHandler PropertyChanged;
}
class BaseClass2 : INotifyPropertyChangedEx
{
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseGenericEventHandler)]
public async Task TestNoDiagnostic_NonVoidDelegate()
{
await VerifyNoDiagnosticAsync(@"
class C
{
public delegate object FooEventHandler(object sender, FooEventArgs e);
public event FooEventHandler OnFoo;
void M()
{
object x = OnFoo?.Invoke(this, new FooEventArgs());
}
}
class FooEventArgs
{
}
");
}
}
}
| 20.075117 | 160 | 0.709775 | [
"Apache-2.0"
] | joebone/Roslynator | src/Tests/Analyzers.Tests/RCS1159UseGenericEventHandlerTests.cs | 4,278 | C# |
using System;
using FinanceControl.Services.Users.Domain.ValueObjects;
using FinanceControl.Services.Users.Infrastructure.Messages;
using Newtonsoft.Json;
namespace FinanceControl.Services.Users.Application.Messages.Commands
{
public class EditUserCommand : IAuthenticatedCommand
{
public Request Request { get; }
public Guid UserId { get; }
public string Email { get; }
public string Name { get; }
public string FirstName { get; }
public string LastName { get; }
public string PhoneNumber { get; }
public UserAddress Address { get; }
[JsonConstructor]
public EditUserCommand(Guid userId, string email, string name,
string firstName, string lastName, string phoneNumber, UserAddress address)
{
Request = Request.New<EditUserCommand>();
UserId = userId;
Email = email;
Name = name;
FirstName = firstName;
LastName = lastName;
PhoneNumber = phoneNumber;
Address = address;
}
}
} | 33.181818 | 87 | 0.628311 | [
"MIT"
] | FreshBlast/FinanceControl.Services.Users | src/FinanceControl.Services.Users.Application/Messages/Commands/EditUserCommand.cs | 1,097 | C# |
using AddressService.Core.Dto;
using AddressService.Core.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using HelpMyStreet.Utils.Utils;
namespace AddressService.Mappers
{
public class QasMapper : IQasMapper
{
public PostcodeDto MapToPostcodeDto(string postcode, IEnumerable<QasFormatRootResponse> qasFormatRootResponses)
{
DateTime timeNow = DateTime.UtcNow;
postcode = PostcodeFormatter.FormatPostcode(postcode);
PostcodeDto postcodeDto = new PostcodeDto();
postcodeDto.Postcode = postcode;
postcodeDto.LastUpdated = timeNow;
foreach (var qasFormatRootResponse in qasFormatRootResponses)
{
AddressDetailsDto addressDetailsDto = new AddressDetailsDto();
foreach (QasFormatAddressReponse address in qasFormatRootResponse.Address) // to deal with strange way results are returned ...
{
if (!String.IsNullOrWhiteSpace(address.AddressLine1))
{
addressDetailsDto.AddressLine1 = address.AddressLine1;
}
else if(!String.IsNullOrWhiteSpace(address.AddressLine2))
{
addressDetailsDto.AddressLine2 = address.AddressLine2;
}
else if (!String.IsNullOrWhiteSpace(address.AddressLine3))
{
addressDetailsDto.AddressLine3 = address.AddressLine3;
}
else if (!String.IsNullOrWhiteSpace(address.Locality))
{
addressDetailsDto.Locality = address.Locality;
}
else if (!String.IsNullOrWhiteSpace(address.PostalCode))
{
addressDetailsDto.Postcode = PostcodeFormatter.FormatPostcode(address.PostalCode);
}
}
// filter out postcodes that weren't returned or don't have the expected postcode
if (!String.IsNullOrWhiteSpace(addressDetailsDto.Postcode) && addressDetailsDto.Postcode == postcode)
{
addressDetailsDto.LastUpdated = timeNow;
postcodeDto.AddressDetails.Add(addressDetailsDto);
}
}
return postcodeDto;
}
/// <summary>
/// Returns Format IDs grouped by postcode
/// </summary>
/// <param name="qasSearchRootResponses"></param>
/// <returns></returns>
public ILookup<string, string> GetFormatIds(IEnumerable<QasSearchRootResponse> qasSearchRootResponses)
{
List<Tuple<string, string>> formatIds = new List<Tuple<string, string>>();
foreach (var qasSearchRootResponse in qasSearchRootResponses)
{
foreach (var result in qasSearchRootResponse.Results)
{
// filter out any addresses missing a Format ID
if (!String.IsNullOrWhiteSpace(result.Format))
{
Tuple<string, string> postCodeWithFormatId = new Tuple<string, string>(qasSearchRootResponse.Postcode, GetFormatIdFromUri(result.Format));
formatIds.Add(postCodeWithFormatId);
}
}
}
ILookup<string, string> formatIdsLookup = formatIds.ToLookup(x => x.Item1, x => x.Item2);
return formatIdsLookup;
}
private string GetFormatIdFromUri(string uri)
{
NameValueCollection queryParameters = HttpUtility.ParseQueryString(uri);
string id = queryParameters.Get("id");
return id;
}
}
}
| 41.221053 | 162 | 0.576098 | [
"MIT"
] | HelpMyStreet/address-service | AddressService/AddressService.Mappers/QasMapper.cs | 3,918 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SPAHost
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
//if (env.IsDevelopment())
//{
// spa.UseAngularCliServer(npmScript: "start");
//}
});
}
}
}
| 30.941176 | 106 | 0.566065 | [
"MIT"
] | staneee/ServiceFabricDemo | SPAHost/Startup.cs | 2,104 | C# |
using System;
using Equinox.Domain.Core.Events;
namespace Equinox.Domain.Events
{
public class CurrencyRemovedEvent : Event
{
public CurrencyRemovedEvent(Guid id)
{
Id = id;
AggregateId = id;
}
public Guid Id { get; set; }
}
} | 18.5625 | 45 | 0.572391 | [
"MIT"
] | duyxaoke/DEV | src/Equinox.Domain/Events/Currency/CurrencyRemovedEvent.cs | 299 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Server {
class Program {
static void Main(string[] args) {
new BackEndLogic.IO();
TcpListener server = new TcpListener(8080);
server.Start();
while (true) {
TcpClient client = server.AcceptTcpClient();
new Thread(() => {
var tempClient = client;
try {
StreamReader sr = new StreamReader(tempClient.GetStream());
List<string> myGetRequests = new List<string>();
string lel = "test";
while (lel != "") {
lel = sr.ReadLine();
if (lel.Contains("GET"))
myGetRequests.Add(lel.Split(' ')[1]);
}
string answer = "";
try {
foreach (var a in myGetRequests) {
Dictionary<string, string> data = new Dictionary<string, string>();
foreach (var b in a.Substring(a.IndexOf('?') + 1).Split('&')) {
data.Add(b.Split('=')[0], b.Split('=')[1]);
}
switch (a.Substring(0, a.IndexOf('?'))) {
case "/account/reg":
answer = BackEndLogic.IO.Database.Registrieren(data["user"], data["password"], data["mail"], data["phone"]);
break;
case "/account/login":
answer = BackEndLogic.IO.Database.Login(data["user"], data["password"]);
break;
case "/player/friends":
answer = BackEndLogic.IO.Database.Friends(data["sessionkey"]);
break;
case "/player/search":
answer = BackEndLogic.IO.Database.SearchFriend(data["sessionkey"], data["name"]);
break;
case "/player/addfriend":
answer = BackEndLogic.IO.Database.AddFriend(data["sessionkey"], data["userid"]);
break;
case "/player/removefriend":
answer = BackEndLogic.IO.Database.RemoveFriend(data["sessionkey"], data["userid"]);
break;
case "/player/homescreen":
answer = BackEndLogic.IO.Database.LoadHomeScreen(data["sessionkey"]);
break;
case "/player/ranking":
answer = BackEndLogic.IO.Database.Ranks(data["type"], data["sessionkey"]);
break;
case "/player/keepalive":
answer = BackEndLogic.IO.Database.KeepAlive(data["sessionkey"]);
break;
case "/player/getallowonlyfriends":
answer = BackEndLogic.IO.Database.GetAllowOnlyFriend(data["sessionkey"]);
break;
case "/player/setallowonlyfriendss":
answer = BackEndLogic.IO.Database.SetAllowOnlyFriends(data["sessionkey"], data["allowonlyfriends"]);
break;
case "/game/create":
answer = BackEndLogic.IO.Database.RequestGame(data["sessionkey"], data["userid"], data["time"], data["size"]);
break;
case "/game/accept":
answer = BackEndLogic.IO.Database.AcceptGame(data["sessionkey"], data["id"]);
break;
case "/game/decline":
answer = BackEndLogic.IO.Database.DeclineGame(data["sessionkey"], data["id"]);
break;
case "/game/field":
answer = BackEndLogic.IO.Database.GetGamefield(data["sessionkey"], data["id"]);
break;
case "/game/turn":
answer = BackEndLogic.IO.Database.SetTurn(data["id"], data["sessionkey"], data["x"], data["y"]);
break;
case "/game/concede":
answer = BackEndLogic.IO.Database.GiveUp(data["sessionkey"], data["id"]);
break;
default:
Console.WriteLine(a.Substring(0, a.IndexOf('?')));
break;
}
}
} catch {
answer = new BackEndLogic.Response() { success = false, message = "Nicht alle benötigten Daten übergeben." }.ToString() + " ";
}
StreamWriter writer = new StreamWriter(tempClient.GetStream());
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write("Content-Type: text/plain; charset=UTF-8");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + answer.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(answer);
writer.Flush();
} catch {
} finally {
tempClient.Close();
}
}).Start();
}
}
}
}
| 55.319672 | 155 | 0.383316 | [
"Apache-2.0"
] | joham97/letsGOServer | Server/Program.cs | 6,753 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Disruptor.Tests;
public abstract class AsyncWaitStrategyTests : WaitStrategyFixture<AsyncWaitStrategy>
{
[Test]
public void ShouldWaitFromMultipleThreadsAsync()
{
// Arrange
var waitStrategy = CreateWaitStrategy();
var waitResult1 = new TaskCompletionSource<SequenceWaitResult>();
var waitResult2 = new TaskCompletionSource<SequenceWaitResult>();
var dependentSequence1 = Cursor;
var dependentSequence2 = new Sequence();
var waitTask1 = Task.Run(async () =>
{
waitResult1.SetResult(await waitStrategy.WaitForAsync(10, Cursor, dependentSequence1, CancellationToken));
Thread.Sleep(1);
dependentSequence2.SetValue(10);
});
var waitTask2 = Task.Run(async () => waitResult2.SetResult(await waitStrategy.WaitForAsync(10, Cursor, dependentSequence2, CancellationToken)));
// Ensure waiting tasks are blocked
AssertIsNotCompleted(waitResult1.Task);
AssertIsNotCompleted(waitResult2.Task);
// Act
Cursor.SetValue(10);
waitStrategy.SignalAllWhenBlocking();
// Assert
AssertHasResult(waitResult1.Task, new SequenceWaitResult(10));
AssertHasResult(waitResult2.Task, new SequenceWaitResult(10));
AssertIsCompleted(waitTask1);
AssertIsCompleted(waitTask2);
}
[Test]
public void ShouldWaitFromMultipleThreadsSyncAndAsync()
{
// Arrange
var waitStrategy = CreateWaitStrategy();
var waitResult1 = new TaskCompletionSource<SequenceWaitResult>();
var waitResult2 = new TaskCompletionSource<SequenceWaitResult>();
var waitResult3 = new TaskCompletionSource<SequenceWaitResult>();
var dependentSequence1 = Cursor;
var dependentSequence2 = new Sequence();
var dependentSequence3 = new Sequence();
var waitTask1 = Task.Run(() =>
{
waitResult1.SetResult(waitStrategy.WaitFor(10, Cursor, dependentSequence1, CancellationToken));
Thread.Sleep(1);
dependentSequence2.SetValue(10);
});
var waitTask2 = Task.Run(async () =>
{
waitResult2.SetResult(await waitStrategy.WaitForAsync(10, Cursor, dependentSequence2, CancellationToken));
Thread.Sleep(1);
dependentSequence3.SetValue(10);
});
var waitTask3 = Task.Run(async () => waitResult3.SetResult(await waitStrategy.WaitForAsync(10, Cursor, dependentSequence3, CancellationToken)));
// Ensure waiting tasks are blocked
AssertIsNotCompleted(waitResult1.Task);
AssertIsNotCompleted(waitResult2.Task);
AssertIsNotCompleted(waitResult3.Task);
// Act
Cursor.SetValue(10);
waitStrategy.SignalAllWhenBlocking();
// Assert WaitFor is unblocked
AssertHasResult(waitResult1.Task, new SequenceWaitResult(10));
AssertHasResult(waitResult2.Task, new SequenceWaitResult(10));
AssertHasResult(waitResult3.Task, new SequenceWaitResult(10));
AssertIsCompleted(waitTask1);
AssertIsCompleted(waitTask2);
AssertIsCompleted(waitTask3);
}
[Test]
public void ShouldUnblockAfterCancellationAsync()
{
// Arrange
var waitStrategy = CreateWaitStrategy();
var dependentSequence = new Sequence();
var waitResult = new TaskCompletionSource<Exception>();
var waitTask = Task.Run(async () =>
{
try
{
await waitStrategy.WaitForAsync(10, Cursor, dependentSequence, CancellationToken);
}
catch (Exception e)
{
waitResult.SetResult(e);
}
});
// Ensure waiting tasks are blocked
AssertIsNotCompleted(waitTask);
// Act
CancellationTokenSource.Cancel();
waitStrategy.SignalAllWhenBlocking();
// Assert
AssertIsCompleted(waitResult.Task);
Assert.That(waitResult.Task.Result, Is.InstanceOf<OperationCanceledException>());
AssertIsCompleted(waitTask);
}
}
| 33.96 | 152 | 0.653946 | [
"Apache-2.0"
] | ltrzesniewski/Disruptor-net | src/Disruptor.Tests/AsyncWaitStrategyTests.cs | 4,245 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.