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 |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Diagnostics;
namespace System.Globalization
{
/// <remarks>
/// Rules for the Hebrew calendar:
/// - The Hebrew calendar is both a Lunar (months) and Solar (years)
/// calendar, but allows for a week of seven days.
/// - Days begin at sunset.
/// - Leap Years occur in the 3, 6, 8, 11, 14, 17, & 19th years of a
/// 19-year cycle. Year = leap iff ((7y+1) mod 19 < 7).
/// - There are 12 months in a common year and 13 months in a leap year.
/// - In a common year, the 6th month, Adar, has 29 days. In a leap
/// year, the 6th month, Adar I, has 30 days and the leap month,
/// Adar II, has 29 days.
/// - Common years have 353-355 days. Leap years have 383-385 days.
/// - The Hebrew new year (Rosh HaShanah) begins on the 1st of Tishri,
/// the 7th month in the list below.
/// - The new year may not begin on Sunday, Wednesday, or Friday.
/// - If the new year would fall on a Tuesday and the conjunction of
/// the following year were at midday or later, the new year is
/// delayed until Thursday.
/// - If the new year would fall on a Monday after a leap year, the
/// new year is delayed until Tuesday.
/// - The length of the 8th and 9th months vary from year to year,
/// depending on the overall length of the year.
/// - The length of a year is determined by the dates of the new
/// years (Tishri 1) preceding and following the year in question.
/// - The 2th month is long (30 days) if the year has 355 or 385 days.
/// - The 3th month is short (29 days) if the year has 353 or 383 days.
/// - The Hebrew months are:
/// 1. Tishri (30 days)
/// 2. Heshvan (29 or 30 days)
/// 3. Kislev (29 or 30 days)
/// 4. Teveth (29 days)
/// 5. Shevat (30 days)
/// 6. Adar I (30 days)
/// 7. Adar {II} (29 days, this only exists if that year is a leap year)
/// 8. Nisan (30 days)
/// 9. Iyyar (29 days)
/// 10. Sivan (30 days)
/// 11. Tammuz (29 days)
/// 12. Av (30 days)
/// 13. Elul (29 days)
/// Calendar support range:
/// Calendar Minimum Maximum
/// ========== ========== ==========
/// Gregorian 1583/01/01 2239/09/29
/// Hebrew 5343/04/07 5999/13/29
///
/// Includes CHebrew implemetation;i.e All the code necessary for converting
/// Gregorian to Hebrew Lunar from 1583 to 2239.
/// </remarks>
public class HebrewCalendar : Calendar
{
public static readonly int HebrewEra = 1;
private const int DatePartYear = 0;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Hebrew Translation Table.
//
// This table is used to get the following Hebrew calendar information for a
// given Gregorian year:
// 1. The day of the Hebrew month corresponding to Gregorian January 1st
// for a given Gregorian year.
// 2. The month of the Hebrew month corresponding to Gregorian January 1st
// for a given Gregorian year.
// The information is not directly in the table. Instead, the info is decoded
// by special values (numbers above 29 and below 1).
// 3. The type of the Hebrew year for a given Gregorian year.
//
// More notes:
// This table includes 2 numbers for each year.
// The offset into the table determines the year. (offset 0 is Gregorian year 1500)
// 1st number determines the day of the Hebrew month coresponeds to January 1st.
// 2nd number determines the type of the Hebrew year. (the type determines how
// many days are there in the year.)
//
// normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
// Leap years : 4 = 383 5 384 6 = 385 days.
//
// A 99 means the year is not supported for translation.
// for convenience the table was defined for 750 year,
// but only 640 years are supported. (from 1583 to 2239)
// the years before 1582 (starting of Georgian calendar)
// and after 2239, are filled with 99.
//
// Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days.
// That's why, there no nead to specify the lunar month in the table.
// There are exceptions, these are coded by giving numbers above 29 and below 1.
// Actual decoding is takenig place whenever fetching information from the table.
// The function for decoding is in GetLunarMonthDay().
//
// Example:
// The data for 2000 - 2005 A.D. is:
// 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004
//
// For year 2000, we know it has a Hebrew year type 6, which means it has 385 days.
// And 1/1/2000 A.D. is Hebrew year 5760, 23rd day of 4th month.
//
// Jewish Era in use today is dated from the supposed year of the
// Creation with its beginning in 3761 B.C.
//
// The Hebrew year of Gregorian 1st year AD.
// 0001/01/01 AD is Hebrew 3760/01/01
private const int HebrewYearOf1AD = 3760;
private const int FirstGregorianTableYear = 1583; // == Hebrew Year 5343
private const int LastGregorianTableYear = 2239; // == Hebrew Year 5999
private const int TableSize = (LastGregorianTableYear - FirstGregorianTableYear);
private const int MinHebrewYear = HebrewYearOf1AD + FirstGregorianTableYear; // == 5343
private const int MaxHebrewYear = HebrewYearOf1AD + LastGregorianTableYear; // == 5999
private static readonly byte[] s_hebrewTable =
{
7,3,17,3, // 1583-1584 (Hebrew year: 5343 - 5344)
0,4,11,2,21,6,1,3,13,2, // 1585-1589
25,4,5,3,16,2,27,6,9,1, // 1590-1594
20,2,0,6,11,3,23,4,4,2, // 1595-1599
14,3,27,4,8,2,18,3,28,6, // 1600
11,1,22,5,2,3,12,3,25,4, // 1605
6,2,16,3,26,6,8,2,20,1, // 1610
0,6,11,2,24,4,4,3,15,2, // 1615
25,6,8,1,19,2,29,6,9,3, // 1620
22,4,3,2,13,3,25,4,6,3, // 1625
17,2,27,6,7,3,19,2,31,4, // 1630
11,3,23,4,5,2,15,3,25,6, // 1635
6,2,19,1,29,6,10,2,22,4, // 1640
3,3,14,2,24,6,6,1,17,3, // 1645
28,5,8,3,20,1,32,5,12,3, // 1650
22,6,4,1,16,2,26,6,6,3, // 1655
17,2,0,4,10,3,22,4,3,2, // 1660
14,3,24,6,5,2,17,1,28,6, // 1665
9,2,19,3,31,4,13,2,23,6, // 1670
3,3,15,1,27,5,7,3,17,3, // 1675
29,4,11,2,21,6,3,1,14,2, // 1680
25,6,5,3,16,2,28,4,9,3, // 1685
20,2,0,6,12,1,23,6,4,2, // 1690
14,3,26,4,8,2,18,3,0,4, // 1695
10,3,21,5,1,3,13,1,24,5, // 1700
5,3,15,3,27,4,8,2,19,3, // 1705
29,6,10,2,22,4,3,3,14,2, // 1710
26,4,6,3,18,2,28,6,10,1, // 1715
20,6,2,2,12,3,24,4,5,2, // 1720
16,3,28,4,8,3,19,2,0,6, // 1725
12,1,23,5,3,3,14,3,26,4, // 1730
7,2,17,3,28,6,9,2,21,4, // 1735
1,3,13,2,25,4,5,3,16,2, // 1740
27,6,9,1,19,3,0,5,11,3, // 1745
23,4,4,2,14,3,25,6,7,1, // 1750
18,2,28,6,9,3,21,4,2,2, // 1755
12,3,25,4,6,2,16,3,26,6, // 1760
8,2,20,1,0,6,11,2,22,6, // 1765
4,1,15,2,25,6,6,3,18,1, // 1770
29,5,9,3,22,4,2,3,13,2, // 1775
23,6,4,3,15,2,27,4,7,3, // 1780
19,2,31,4,11,3,21,6,3,2, // 1785
15,1,25,6,6,2,17,3,29,4, // 1790
10,2,20,6,3,1,13,3,24,5, // 1795
4,3,16,1,27,5,7,3,17,3, // 1800
0,4,11,2,21,6,1,3,13,2, // 1805
25,4,5,3,16,2,29,4,9,3, // 1810
19,6,30,2,13,1,23,6,4,2, // 1815
14,3,27,4,8,2,18,3,0,4, // 1820
11,3,22,5,2,3,14,1,26,5, // 1825
6,3,16,3,28,4,10,2,20,6, // 1830
30,3,11,2,24,4,4,3,15,2, // 1835
25,6,8,1,19,2,29,6,9,3, // 1840
22,4,3,2,13,3,25,4,7,2, // 1845
17,3,27,6,9,1,21,5,1,3, // 1850
11,3,23,4,5,2,15,3,25,6, // 1855
6,2,19,1,29,6,10,2,22,4, // 1860
3,3,14,2,24,6,6,1,18,2, // 1865
28,6,8,3,20,4,2,2,12,3, // 1870
24,4,4,3,16,2,26,6,6,3, // 1875
17,2,0,4,10,3,22,4,3,2, // 1880
14,3,24,6,5,2,17,1,28,6, // 1885
9,2,21,4,1,3,13,2,23,6, // 1890
5,1,15,3,27,5,7,3,19,1, // 1895
0,5,10,3,22,4,2,3,13,2, // 1900
24,6,4,3,15,2,27,4,8,3, // 1905
20,4,1,2,11,3,22,6,3,2, // 1910
15,1,25,6,7,2,17,3,29,4, // 1915
10,2,21,6,1,3,13,1,24,5, // 1920
5,3,15,3,27,4,8,2,19,6, // 1925
1,1,12,2,22,6,3,3,14,2, // 1930
26,4,6,3,18,2,28,6,10,1, // 1935
20,6,2,2,12,3,24,4,5,2, // 1940
16,3,28,4,9,2,19,6,30,3, // 1945
12,1,23,5,3,3,14,3,26,4, // 1950
7,2,17,3,28,6,9,2,21,4, // 1955
1,3,13,2,25,4,5,3,16,2, // 1960
27,6,9,1,19,6,30,2,11,3, // 1965
23,4,4,2,14,3,27,4,7,3, // 1970
18,2,28,6,11,1,22,5,2,3, // 1975
12,3,25,4,6,2,16,3,26,6, // 1980
8,2,20,4,30,3,11,2,24,4, // 1985
4,3,15,2,25,6,8,1,18,3, // 1990
29,5,9,3,22,4,3,2,13,3, // 1995
23,6,6,1,17,2,27,6,7,3, // 2000 - 2004
20,4,1,2,11,3,23,4,5,2, // 2005 - 2009
15,3,25,6,6,2,19,1,29,6, // 2010
10,2,20,6,3,1,14,2,24,6, // 2015
4,3,17,1,28,5,8,3,20,4, // 2020
1,3,12,2,22,6,2,3,14,2, // 2025
26,4,6,3,17,2,0,4,10,3, // 2030
20,6,1,2,14,1,24,6,5,2, // 2035
15,3,28,4,9,2,19,6,1,1, // 2040
12,3,23,5,3,3,15,1,27,5, // 2045
7,3,17,3,29,4,11,2,21,6, // 2050
1,3,12,2,25,4,5,3,16,2, // 2055
28,4,9,3,19,6,30,2,12,1, // 2060
23,6,4,2,14,3,26,4,8,2, // 2065
18,3,0,4,10,3,22,5,2,3, // 2070
14,1,25,5,6,3,16,3,28,4, // 2075
9,2,20,6,30,3,11,2,23,4, // 2080
4,3,15,2,27,4,7,3,19,2, // 2085
29,6,11,1,21,6,3,2,13,3, // 2090
25,4,6,2,17,3,27,6,9,1, // 2095
20,5,30,3,10,3,22,4,3,2, // 2100
14,3,24,6,5,2,17,1,28,6, // 2105
9,2,21,4,1,3,13,2,23,6, // 2110
5,1,16,2,27,6,7,3,19,4, // 2115
30,2,11,3,23,4,3,3,14,2, // 2120
25,6,5,3,16,2,28,4,9,3, // 2125
21,4,2,2,12,3,23,6,4,2, // 2130
16,1,26,6,8,2,20,4,30,3, // 2135
11,2,22,6,4,1,14,3,25,5, // 2140
6,3,18,1,29,5,9,3,22,4, // 2145
2,3,13,2,23,6,4,3,15,2, // 2150
27,4,7,3,20,4,1,2,11,3, // 2155
21,6,3,2,15,1,25,6,6,2, // 2160
17,3,29,4,10,2,20,6,3,1, // 2165
13,3,24,5,4,3,17,1,28,5, // 2170
8,3,18,6,1,1,12,2,22,6, // 2175
2,3,14,2,26,4,6,3,17,2, // 2180
28,6,10,1,20,6,1,2,12,3, // 2185
24,4,5,2,15,3,28,4,9,2, // 2190
19,6,33,3,12,1,23,5,3,3, // 2195
13,3,25,4,6,2,16,3,26,6, // 2200
8,2,20,4,30,3,11,2,24,4, // 2205
4,3,15,2,25,6,8,1,18,6, // 2210
33,2,9,3,22,4,3,2,13,3, // 2215
25,4,6,3,17,2,27,6,9,1, // 2220
21,5,1,3,11,3,23,4,5,2, // 2225
15,3,25,6,6,2,19,4,33,3, // 2230
10,2,22,4,3,3,14,2,24,6, // 2235
6,1 // 2240 (Hebrew year: 6000)
};
private const int MaxMonthPlusOne = 14;
// The lunar calendar has 6 different variations of month lengths
// within a year.
private static readonly byte[] s_lunarMonthLen =
{
0,00,00,00,00,00,00,00,00,00,00,00,00,0,
0,30,29,29,29,30,29,30,29,30,29,30,29,0, // 3 common year variations
0,30,29,30,29,30,29,30,29,30,29,30,29,0,
0,30,30,30,29,30,29,30,29,30,29,30,29,0,
0,30,29,29,29,30,30,29,30,29,30,29,30,29, // 3 leap year variations
0,30,29,30,29,30,30,29,30,29,30,29,30,29,
0,30,30,30,29,30,30,29,30,29,30,29,30,29
};
private static readonly DateTime s_calendarMinValue = new DateTime(1583, 1, 1);
// Gregorian 2239/9/29 = Hebrew 5999/13/29 (last day in Hebrew year 5999).
// We can only format/parse Hebrew numbers up to 999, so we limit the max range to Hebrew year 5999.
private static readonly DateTime s_calendarMaxValue = new DateTime((new DateTime(2239, 9, 29, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime => s_calendarMinValue;
public override DateTime MaxSupportedDateTime => s_calendarMaxValue;
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunisolarCalendar;
public HebrewCalendar()
{
}
internal override CalendarId ID => CalendarId.HEBREW;
private static void CheckHebrewYearValue(int y, int era, string varName)
{
CheckEraRange(era);
if (y > MaxHebrewYear || y < MinHebrewYear)
{
throw new ArgumentOutOfRangeException(
varName,
y,
SR.Format(SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear));
}
}
/// <summary>
/// Check if the Hebrew month value is valid.
/// </summary>
/// <remarks>
/// Call CheckHebrewYearValue() before calling this to verify the year value is supported.
/// </remarks>
private void CheckHebrewMonthValue(int year, int month, int era)
{
int monthsInYear = GetMonthsInYear(year, era);
if (month < 1 || month > monthsInYear)
{
throw new ArgumentOutOfRangeException(
nameof(month),
month,
SR.Format(SR.ArgumentOutOfRange_Range, 1, monthsInYear));
}
}
/// <summary>
/// Check if the Hebrew day value is valid.
/// </summary>
/// <remarks>
/// Call CheckHebrewYearValue()/CheckHebrewMonthValue() before calling this to verify the year/month values are valid.
/// </remarks>
private void CheckHebrewDayValue(int year, int month, int day, int era)
{
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Range, 1, daysInMonth));
}
}
private static void CheckEraRange(int era)
{
if (era != CurrentEra && era != HebrewEra)
{
throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue);
}
}
private static void CheckTicksRange(long ticks)
{
if (ticks < s_calendarMinValue.Ticks || ticks > s_calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
ticks,
// Print out the date in Gregorian using InvariantCulture since the DateTime is based on GreograinCalendar.
SR.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
s_calendarMinValue,
s_calendarMaxValue));
}
}
private static int GetResult(DateBuffer result, int part)
{
switch (part)
{
case DatePartYear:
return result.year;
case DatePartMonth:
return result.month;
case DatePartDay:
return result.day;
}
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
/// <summary>
/// Using the Hebrew table (HebrewTable) to get the Hebrew month/day value for Gregorian January 1st
/// in a given Gregorian year.
/// Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days.
/// That's why, there no nead to specify the lunar month in the table. There are exceptions, and these
/// are coded by giving numbers above 29 and below 1.
/// Actual decoding is takenig place in the switch statement below.
/// </summary>
/// <returns>
/// The Hebrew year type. The value is from 1 to 6.
/// normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
/// Leap years : 4 = 383 5 384 6 = 385 days.
/// </returns>
internal static int GetLunarMonthDay(int gregorianYear, DateBuffer lunarDate)
{
// Get the offset into the LunarMonthLen array and the lunar day
// for January 1st.
int index = gregorianYear - FirstGregorianTableYear;
if (index < 0 || index > TableSize)
{
throw new ArgumentOutOfRangeException(nameof(gregorianYear));
}
index *= 2;
lunarDate.day = s_hebrewTable[index];
// Get the type of the year. The value is from 1 to 6
int lunarYearType = s_hebrewTable[index + 1];
// Get the Lunar Month.
switch (lunarDate.day)
{
case 0: // 1/1 is on Shvat 1
lunarDate.month = 5;
lunarDate.day = 1;
break;
case 30: // 1/1 is on Kislev 30
lunarDate.month = 3;
break;
case 31: // 1/1 is on Shvat 2
lunarDate.month = 5;
lunarDate.day = 2;
break;
case 32: // 1/1 is on Shvat 3
lunarDate.month = 5;
lunarDate.day = 3;
break;
case 33: // 1/1 is on Kislev 29
lunarDate.month = 3;
lunarDate.day = 29;
break;
default: // 1/1 is on Tevet (This is the general case)
lunarDate.month = 4;
break;
}
return lunarYearType;
}
/// <summary>
/// Returns a given date part of this DateTime. This method is used
/// to compute the year, day-of-year, month, or day part.
/// </summary>
internal virtual int GetDatePart(long ticks, int part)
{
// The Gregorian year, month, day value for ticks.
int gregorianYear, gregorianMonth, gregorianDay;
int hebrewYearType; // lunar year type
long AbsoluteDate; // absolute date - absolute date 1/1/1600
// Make sure we have a valid Gregorian date that will fit into our
// Hebrew conversion limits.
CheckTicksRange(ticks);
DateTime time = new DateTime(ticks);
// Save the Gregorian date values.
time.GetDatePart(out gregorianYear, out gregorianMonth, out gregorianDay);
DateBuffer lunarDate = new DateBuffer(); // lunar month and day for Jan 1
// From the table looking-up value of HebrewTable[index] (stored in lunarDate.day), we get the
// lunar month and lunar day where the Gregorian date 1/1 falls.
lunarDate.year = gregorianYear + HebrewYearOf1AD;
hebrewYearType = GetLunarMonthDay(gregorianYear, lunarDate);
// This is the buffer used to store the result Hebrew date.
DateBuffer result = new DateBuffer();
// Store the values for the start of the new year - 1/1.
result.year = lunarDate.year;
result.month = lunarDate.month;
result.day = lunarDate.day;
// Get the absolute date from 1/1/1600.
AbsoluteDate = GregorianCalendar.GetAbsoluteDate(gregorianYear, gregorianMonth, gregorianDay);
// If the requested date was 1/1, then we're done.
if ((gregorianMonth == 1) && (gregorianDay == 1))
{
return GetResult(result, part);
}
// Calculate the number of days between 1/1 and the requested date.
long numDays = AbsoluteDate - GregorianCalendar.GetAbsoluteDate(gregorianYear, 1, 1);
// If the requested date is within the current lunar month, then
// we're done.
if ((numDays + (long)lunarDate.day) <= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month]))
{
result.day += (int)numDays;
return GetResult(result, part);
}
// Adjust for the current partial month.
result.month++;
result.day = 1;
// Adjust the Lunar Month and Year (if necessary) based on the number
// of days between 1/1 and the requested date.
// Assumes Jan 1 can never translate to the last Lunar month, which
// is true.
numDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day);
Debug.Assert(numDays >= 1, "NumDays >= 1");
// If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
// and day.
if (numDays > 1)
{
// See if we're on the correct Lunar month.
while (numDays > (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month]))
{
// Adjust the number of days and move to the next month.
numDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month++]);
// See if we need to adjust the Year.
// Must handle both 12 and 13 month years.
if ((result.month > 13) || (s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month] == 0))
{
// Adjust the Year.
result.year++;
hebrewYearType = s_hebrewTable[(gregorianYear + 1 - FirstGregorianTableYear) * 2 + 1];
// Adjust the Month.
result.month = 1;
}
}
// Found the right Lunar month.
result.day += (int)(numDays - 1);
}
return GetResult(result, part);
}
public override DateTime AddMonths(DateTime time, int months)
{
try
{
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int monthsInYear;
int i;
if (months >= 0)
{
i = m + months;
while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra)))
{
y++;
i -= monthsInYear;
}
}
else
{
if ((i = m + months) <= 0)
{
months = -months;
months -= m;
y--;
while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra)))
{
y--;
months -= monthsInYear;
}
monthsInYear = GetMonthsInYear(y, CurrentEra);
i = monthsInYear - months;
}
}
int days = GetDaysInMonth(y, i);
if (d > days)
{
d = days;
}
return new DateTime(ToDateTime(y, i, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay));
}
// We expect ArgumentException and ArgumentOutOfRangeException (which is subclass of ArgumentException)
// If exception is thrown in the calls above, we are out of the supported range of this calendar.
catch (ArgumentException)
{
throw new ArgumentOutOfRangeException(nameof(months), months, SR.ArgumentOutOfRange_AddValue);
}
}
public override DateTime AddYears(DateTime time, int years)
{
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
y += years;
CheckHebrewYearValue(y, Calendar.CurrentEra, nameof(years));
int months = GetMonthsInYear(y, CurrentEra);
if (m > months)
{
m = months;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = ToDateTime(y, m, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return new DateTime(ticks);
}
public override int GetDayOfMonth(DateTime time)
{
return GetDatePart(time.Ticks, DatePartDay);
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
// If we calculate back, the Hebrew day of week for Gregorian 0001/1/1 is Monday (1).
// Therfore, the fomula is:
return (DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7);
}
internal static int GetHebrewYearType(int year, int era)
{
CheckHebrewYearValue(year, era, nameof(year));
// The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear.
// So we need to convert year (Hebrew year value) to Gregorian Year below.
return s_hebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1];
}
public override int GetDayOfYear(DateTime time)
{
// Get Hebrew year value of the specified time.
int year = GetYear(time);
DateTime beginOfYearDate;
if (year == 5343)
{
// Gregorian 1583/01/01 corresponds to Hebrew 5343/04/07 (MinSupportedDateTime)
// To figure out the Gregorian date associated with Hebrew 5343/01/01, we need to
// count the days from 5343/01/01 to 5343/04/07 and subtract that from Gregorian
// 1583/01/01.
// 1. Tishri (30 days)
// 2. Heshvan (30 days since 5343 has 355 days)
// 3. Kislev (30 days since 5343 has 355 days)
// 96 days to get from 5343/01/01 to 5343/04/07
// Gregorian 1583/01/01 - 96 days = 1582/9/27
// the beginning of Hebrew year 5343 corresponds to Gregorian September 27, 1582.
beginOfYearDate = new DateTime(1582, 9, 27);
}
else
{
// following line will fail when year is 5343 (first supported year)
beginOfYearDate = ToDateTime(year, 1, 1, 0, 0, 0, 0, CurrentEra);
}
return (int)((time.Ticks - beginOfYearDate.Ticks) / TicksPerDay) + 1;
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckEraRange(era);
int hebrewYearType = GetHebrewYearType(year, era);
CheckHebrewMonthValue(year, month, era);
Debug.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
"hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
int monthDays = s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + month];
if (monthDays == 0)
{
throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month);
}
return monthDays;
}
public override int GetDaysInYear(int year, int era)
{
CheckEraRange(era);
// normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
// Leap years : 4 = 383 5 384 6 = 385 days.
// LunarYearType is from 1 to 6
int LunarYearType = GetHebrewYearType(year, era);
if (LunarYearType < 4)
{
// common year: LunarYearType = 1, 2, 3
return 352 + LunarYearType;
}
return 382 + (LunarYearType - 3);
}
public override int GetEra(DateTime time) => HebrewEra;
public override int[]? Eras => new int[] { HebrewEra };
public override int GetMonth(DateTime time)
{
return GetDatePart(time.Ticks, DatePartMonth);
}
public override int GetMonthsInYear(int year, int era)
{
return IsLeapYear(year, era) ? 13 : 12;
}
public override int GetYear(DateTime time)
{
return GetDatePart(time.Ticks, DatePartYear);
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
if (IsLeapMonth(year, month, era))
{
// Every day in a leap month is a leap day.
CheckHebrewDayValue(year, month, day, era);
return true;
}
else if (IsLeapYear(year, Calendar.CurrentEra))
{
// There is an additional day in the 6th month in the leap year (the extra day is the 30th day in the 6th month),
// so we should return true for 6/30 if that's in a leap year.
if (month == 6 && day == 30)
{
return true;
}
}
CheckHebrewDayValue(year, month, day, era);
return false;
}
public override int GetLeapMonth(int year, int era)
{
// Year/era values are checked in IsLeapYear().
if (IsLeapYear(year, era))
{
// The 7th month in a leap year is a leap month.
return 7;
}
return 0;
}
public override bool IsLeapMonth(int year, int month, int era)
{
// Year/era values are checked in IsLeapYear().
bool isLeapYear = IsLeapYear(year, era);
CheckHebrewMonthValue(year, month, era);
// The 7th month in a leap year is a leap month.
return isLeapYear && month == 7;
}
public override bool IsLeapYear(int year, int era)
{
CheckHebrewYearValue(year, era, nameof(year));
return ((7 * (long)year + 1) % 19) < 7;
}
/// <summary>
/// (month1, day1) - (month2, day2)
/// </summary>
private static int GetDayDifference(int lunarYearType, int month1, int day1, int month2, int day2)
{
if (month1 == month2)
{
return (day1 - day2);
}
// Make sure that (month1, day1) < (month2, day2)
bool swap = (month1 > month2);
if (swap)
{
// (month1, day1) < (month2, day2). Swap the values.
// The result will be a negative number.
int tempMonth, tempDay;
tempMonth = month1; tempDay = day1;
month1 = month2; day1 = day2;
month2 = tempMonth; day2 = tempDay;
}
// Get the number of days from (month1,day1) to (month1, end of month1)
int days = s_lunarMonthLen[lunarYearType * MaxMonthPlusOne + month1] - day1;
// Move to next month.
month1++;
// Add up the days.
while (month1 < month2)
{
days += s_lunarMonthLen[lunarYearType * MaxMonthPlusOne + month1++];
}
days += day2;
return swap ? days : -days;
}
/// <summary>
/// Convert Hebrew date to Gregorian date.
/// The algorithm is like this:
/// The hebrew year has an offset to the Gregorian year, so we can guess the Gregorian year for
/// the specified Hebrew year. That is, GreogrianYear = HebrewYear - FirstHebrewYearOf1AD.
///
/// From the Gregorian year and HebrewTable, we can get the Hebrew month/day value
/// of the Gregorian date January 1st. Let's call this month/day value [hebrewDateForJan1]
///
/// If the requested Hebrew month/day is less than [hebrewDateForJan1], we know the result
/// Gregorian date falls in previous year. So we decrease the Gregorian year value, and
/// retrieve the Hebrew month/day value of the Gregorian date january 1st again.
///
/// Now, we get the answer of the Gregorian year.
///
/// The next step is to get the number of days between the requested Hebrew month/day
/// and [hebrewDateForJan1]. When we get that, we can create the DateTime by adding/subtracting
/// the ticks value of the number of days.
/// </summary>
private static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond)
{
// Get the rough Gregorian year for the specified hebrewYear.
int gregorianYear = hebrewYear - HebrewYearOf1AD;
DateBuffer hebrewDateOfJan1 = new DateBuffer(); // year value is unused.
int lunarYearType = GetLunarMonthDay(gregorianYear, hebrewDateOfJan1);
if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day))
{
return new DateTime(gregorianYear, 1, 1, hour, minute, second, millisecond);
}
int days = GetDayDifference(lunarYearType, hebrewMonth, hebrewDay, hebrewDateOfJan1.month, hebrewDateOfJan1.day);
DateTime gregorianNewYear = new DateTime(gregorianYear, 1, 1);
return new DateTime(gregorianNewYear.Ticks + days * TicksPerDay + TimeToTicks(hour, minute, second, millisecond));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckHebrewYearValue(year, era, nameof(year));
CheckHebrewMonthValue(year, month, era);
CheckHebrewDayValue(year, month, day, era);
DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond);
CheckTicksRange(dt.Ticks);
return dt;
}
private const int DefaultTwoDigitYearMax = 5790;
public override int TwoDigitYearMax
{
get
{
if (_twoDigitYearMax == -1)
{
_twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax);
}
return _twoDigitYearMax;
}
set
{
VerifyWritable();
if (value == 99)
{
// Do nothing here. Year 99 is allowed so that TwoDitYearMax is disabled.
}
else
{
CheckHebrewYearValue(value, HebrewEra, nameof(value));
}
_twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year < 100)
{
return base.ToFourDigitYear(year);
}
if (year > MaxHebrewYear || year < MinHebrewYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear));
}
return year;
}
internal class DateBuffer
{
internal int year;
internal int month;
internal int day;
}
}
}
| 42.481888 | 148 | 0.503036 | [
"MIT"
] | MattKotsenas/corefx | src/Common/src/CoreLib/System/Globalization/HebrewCalendar.cs | 38,701 | C# |
// This file is part of Companion Cube project
//
// Copyright 2018 Emzi0767
//
// 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.Immutable;
using Newtonsoft.Json;
namespace Emzi0767.CompanionCube.Data
{
/// <summary>
/// Represents the entire configuration file.
/// </summary>
public sealed class CompanionCubeConfig
{
/// <summary>
/// Gets this configuration file's version data.
/// </summary>
[JsonProperty("version")]
public CompanionCubeConfigVersion Version { get; private set; } = new CompanionCubeConfigVersion();
/// <summary>
/// Gets the Discord configuration.
/// </summary>
[JsonProperty("discord")]
public CompanionCubeConfigDiscord Discord { get; private set; } = new CompanionCubeConfigDiscord();
/// <summary>
/// Gets the PostgreSQL configuration.
/// </summary>
[JsonProperty("postgres")]
public CompanionCubeConfigPostgres PostgreSQL { get; private set; } = new CompanionCubeConfigPostgres();
/// <summary>
/// Gets the Lavalink configuration.
/// </summary>
[JsonProperty("lavalink")]
public CompanionCubeConfigLavalink Lavalink { get; private set; } = new CompanionCubeConfigLavalink();
/// <summary>
/// Gets the YouTube API configuration.
/// </summary>
[JsonProperty("youtube")]
public CompanionCubeConfigYouTube YouTube { get; private set; } = new CompanionCubeConfigYouTube();
/// <summary>
/// Gets the GitHub API configuration.
/// </summary>
[JsonProperty("github")]
public CompanionCubeConfigGitHub GitHub { get; private set; } = new CompanionCubeConfigGitHub();
}
/// <summary>
/// Represents version section of the configuration file.
/// </summary>
public sealed class CompanionCubeConfigVersion
{
/// <summary>
/// Gets the numeric version of the config data.
/// </summary>
[JsonProperty("config")]
public int Configuration { get; private set; }
}
/// <summary>
/// Represents Discord section of the configuration file.
/// </summary>
public sealed class CompanionCubeConfigDiscord
{
/// <summary>
/// Gets the token for Discord API.
/// </summary>
[JsonProperty("token")]
public string Token { get; private set; } = "insert_token_here";
/// <summary>
/// Gets the default command prefixes of the bot.
/// </summary>
[JsonProperty("prefixes")]
public ImmutableArray<string> DefaultPrefixes { get; private set; } = new[] { "cc!", "//", "??" }.ToImmutableArray();
/// <summary>
/// Gets whether to enable the user mention prefix for the bot.
/// </summary>
[JsonProperty("mention_prefix")]
public bool EnableMentionPrefix { get; private set; } = true;
/// <summary>
/// Gets the size of the message cache. 0 means disable.
/// </summary>
[JsonProperty("message_cache_size")]
public int MessageCacheSize { get; private set; } = 512;
/// <summary>
/// Gets the total number of shards on which the bot will operate.
/// </summary>
[JsonProperty("shards")]
public int ShardCount { get; private set; } = 1;
/// <summary>
/// Gets the game the bot will be playing. Null means disable.
/// </summary>
[JsonProperty("game")]
public string Game { get; private set; } = "with Portals";
}
/// <summary>
/// Represents PostgreSQL section of the configuration file.
/// </summary>
public sealed class CompanionCubeConfigPostgres
{
/// <summary>
/// Gets the hostname of the PostgreSQL server.
/// </summary>
[JsonProperty("hostname")]
public string Hostname { get; private set; } = "localhost";
/// <summary>
/// Gets the port of the PostgreSQL server.
/// </summary>
[JsonProperty("port")]
public int Port { get; private set; } = 5432;
/// <summary>
/// Gets the name of the PostgreSQL database.
/// </summary>
[JsonProperty("database")]
public string Database { get; private set; } = "companion_cube";
/// <summary>
/// Gets the username for PostgreSQL authentication.
/// </summary>
[JsonProperty("username")]
public string Username { get; private set; } = "companion_cube";
/// <summary>
/// Gets the password for PostgreSQL authentication.
/// </summary>
[JsonProperty("password")]
public string Password { get; private set; } = "hunter2";
/// <summary>
/// Gets whether to use SSL/TLS for communication with PostgreSQL server.
/// </summary>
[JsonProperty("ssl")]
public bool UseEncryption { get; private set; } = true;
/// <summary>
/// Gets whether to trust the PostgreSQL server certificate unconditionally.
/// </summary>
[JsonProperty("trust_certificate")]
public bool TrustServerCertificate { get; private set; } = true;
/// <summary>
/// Gets the required database schema version.
/// </summary>
[JsonProperty("schema_version")]
public int SchemaVersion { get; private set; } = 4;
}
/// <summary>
/// Represents Lavalink section of the configuration file.
/// </summary>
public sealed class CompanionCubeConfigLavalink
{
/// <summary>
/// Gets the hostname of the Lavalink node server.
/// </summary>
[JsonProperty("hostname")]
public string Hostname { get; private set; } = "localhost";
/// <summary>
/// Gets the port of the Lavalink node server.
/// </summary>
[JsonProperty("port")]
public int Port { get; private set; } = 2333;
/// <summary>
/// Gets the password to Lavalink node server.
/// </summary>
[JsonProperty("password")]
public string Password { get; private set; } = "youshallnotpass";
}
/// <summary>
/// Represents YouTube section of the configuration file.
/// </summary>
public sealed class CompanionCubeConfigYouTube
{
/// <summary>
/// Gets the API key for YouTube's data API.
/// </summary>
[JsonProperty("api_key")]
public string ApiKey { get; private set; } = "insert_api_key_here";
}
/// <summary>
/// Represents GitHub section of the configuration file.
/// </summary>
public sealed class CompanionCubeConfigGitHub
{
/// <summary>
/// Gets whether processing is enabled.
/// </summary>
[JsonProperty("enabled")]
public bool IsEnabled { get; private set; }
/// <summary>
/// Gets the channels allowed to process Issues and PRs.
/// </summary>
[JsonProperty("channels")]
public ulong[] Channels { get; private set; }
/// <summary>
/// Gets the guilds allowed to process Issues and PRs.
/// </summary>
[JsonProperty("guilds")]
public ulong[] Guilds { get; private set; }
}
} | 34.125541 | 125 | 0.593302 | [
"Apache-2.0"
] | ProfDoof/Discord-Companion-Cube-Bot | Emzi0767.CompanionCube/Data/CompanionCubeConfig.cs | 7,883 | C# |
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace UWPTestLibrary
{
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SetProperty<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (object.Equals(value, storage))
{
return;
}
storage = value;
NotifyPropertyChanged(propertyName);
}
protected void NotifyPropertyChanged(string propertyName)
{
if (propertyName != null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 26.4 | 107 | 0.604798 | [
"MIT"
] | hhy37/AdaptiveCards | source/uwp/UWPTestLibrary/BindableBase.cs | 794 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("_2629")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_2629")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("30277f40-8ad9-413b-8b10-4a26e84d4f95")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 28.837838 | 57 | 0.741331 | [
"MIT"
] | yu3mars/procon | aoj/2600s/2629/Properties/AssemblyInfo.cs | 1,636 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Microsoft.DotNet.Interactive.ExtensionLab;
using Microsoft.DotNet.Interactive.Formatting;
namespace System.Collections.Generic
{
public static class EnumerableExtensions
{
public static SandDanceDataExplorer ExploreWithSandDance<T>(this IEnumerable<T> source)
{
return source.ToTabularDataResource().ExploreWithSandDance();
}
public static NteractDataExplorer ExploreWithNteract<T>(this IEnumerable<T> source)
{
return source.ToTabularDataResource().ExploreWithNteract();
}
public static void Explore<T>(this IEnumerable<T> source)
{
source.ExploreWithNteract();
}
public static IReadOnlyList<IDictionary<string, object>> ToTable(this IEnumerable<IEnumerable<(string name, object value)>> source)
{
var listOfRows = new List<Dictionary<string, object>>();
foreach (var row in source)
{
var dict = new Dictionary<string, object>();
listOfRows.Add(dict);
foreach (var (fieldName, fieldValue) in row)
{
dict.Add(fieldName, fieldValue);
}
}
return listOfRows;
}
public static IEnumerable<IReadOnlyList<IDictionary<string, object>>> ToTables(this IEnumerable<IEnumerable<IEnumerable<(string, object)>>> source) =>
source.Select(x => x.ToTable());
}
} | 34.489796 | 159 | 0.630769 | [
"MIT"
] | WhiteBlackGoose/interactive | src/Microsoft.DotNet.Interactive.ExtensionLab/System.Collections.Generic/EnumerableExtensions.cs | 1,692 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.Xml;
namespace Lab4Server
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
Thread T;
bool mustStop;
protected override void OnStart(string[] args)
{
T = new Thread(WorkerThread);
T.Start();
}
protected override void OnStop()
{
if ((T != null) && (T.IsAlive))
{
mustStop = true;
}
}
void WorkerThread()
{
Debugger.Launch();
string ip = "192.168.0.101";
WriteLog($"started\nmustStop={mustStop}");
IPAddress IP = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 54000);
WriteLog($"IP={ip}\n");
Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
S.Bind(ipEndPoint);
while (!mustStop)
{
try
{
//S.Listen(10);
//WriteLog($"listening on {ip}\n");
while (true)
{
//using (Socket H = S.Accept())
//{
IPEndPoint L = new IPEndPoint(IPAddress.Any, 0);
EndPoint R = (EndPoint)(L);
byte[] D = new byte[10000];
int Receive = S.ReceiveFrom(D, ref R);
string Request = Encoding.UTF8.GetString(D, 0, Receive);
WriteLog($"Request recived from {R.ToString()}:\n{Request}");
CheckRequest(Request);
string W = File.ReadAllText(@"C:\Windows\Demon\response.xml", Encoding.UTF8);
byte[] M = Encoding.UTF8.GetBytes(W);
S.SendTo(M, R);
// H.Send(M);
// H.Shutdown(SocketShutdown.Both);
//}
}
}
catch (Exception e)
{
WriteLog(e.Message);
}
S.Close();
}
}
private static void CheckRequest(string request)
{
try
{
string reqFile = @"C:\Windows\Demon\request.xml";
using (StreamWriter F = new StreamWriter(reqFile, false, Encoding.UTF8))
{
F.WriteLine(request);
}
XmlDocument doc = new XmlDocument();
doc.Load(reqFile);
XmlElement xRoot = doc.DocumentElement;
string curKey;
string newKey;
curKey = xRoot.ChildNodes[0].InnerText;
newKey = xRoot.ChildNodes[1].InnerText;
WriteLog($"type {xRoot.Name}");
WriteLog($"Get current key{curKey}");
WriteLog($"Get new key{newKey}");
if (xRoot.Name == "request")
using (RegistryKey v = Registry.LocalMachine.OpenSubKey(curKey, true))
{
if (v == null)
{
writeResponse(404, $"Key '{curKey}' DOESN'T EXIST :(");
WriteLog($"\n404\t{curKey} DOESN'T EXIST \n");
}
else
if (v.GetSubKeyNames().Contains(newKey))
{
writeResponse(300, $"Key '{newKey}' EXIST");
WriteLog($"\n\n300\t{newKey} EXIST\n\n");
}
else
{
writeResponse(400, $"Key '{newKey}' DOESN'T EXIST :(");
WriteLog($"\n400\t{newKey} DOESN'T EXIST \n");
}
}
if (xRoot.Name=="create")
using (RegistryKey v = Registry.LocalMachine.OpenSubKey(curKey, true))
{
if (v == null)
{
writeResponse(204, $"Key '{curKey}' DOESN'T EXIST :(");
WriteLog($"\n204\t{curKey} DOESN'T EXIST \n");
}
else
if (v.GetSubKeyNames().Contains(newKey))
{
writeResponse(203, $"Key '{newKey}' EXIST");
WriteLog($"\n\n203\t{newKey} EXIST\n\n");
}
else
{
v.CreateSubKey(newKey);
writeResponse(200, $"Key '{newKey}' WAS CREATED");
WriteLog($"\n200\t{newKey} WAS CREATED \n");
}
}
}
catch (Exception e)
{
WriteLog(e.Message);
}
}
private static void WriteLog(string z)
{
using (StreamWriter F = new StreamWriter(@"C:\Windows\Logs\Demon.txt", true, Encoding.UTF8))
{
F.WriteLine(z);
}
}
static void writeResponse(int code,string description)
{
Debugger.Launch();
string filePath = @"C:\Windows\Demon\response.xml";
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
doc.DocumentElement.ParentNode.RemoveAll();
XmlElement xRoot = doc.DocumentElement;
XmlElement response = doc.CreateElement("response");
XmlElement xcode = doc.CreateElement("code");
XmlElement xdesc = doc.CreateElement("description");
XmlText responseText = doc.CreateTextNode(description);
XmlText respCode = doc.CreateTextNode($"{code}");
xdesc.AppendChild(responseText);
xcode.AppendChild(respCode);
response.AppendChild(xdesc);
response.AppendChild(xcode);
doc.AppendChild(response);
doc.Save(filePath);
}
}
}
| 31.892523 | 105 | 0.429304 | [
"MIT"
] | triod315/SysProgLabworks | Lab4/Lab4Server/Lab4Server/Service1.cs | 6,827 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the cognito-identity-2014-06-30.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CognitoIdentity.Model
{
/// <summary>
/// An object representing an Amazon Cognito identity pool.
/// </summary>
public partial class UpdateIdentityPoolResponse : AmazonWebServiceResponse
{
private bool? _allowClassicFlow;
private bool? _allowUnauthenticatedIdentities;
private List<CognitoIdentityProviderInfo> _cognitoIdentityProviders = new List<CognitoIdentityProviderInfo>();
private string _developerProviderName;
private string _identityPoolId;
private string _identityPoolName;
private Dictionary<string, string> _identityPoolTags = new Dictionary<string, string>();
private List<string> _openIdConnectProviderARNs = new List<string>();
private List<string> _samlProviderARNs = new List<string>();
private Dictionary<string, string> _supportedLoginProviders = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property AllowClassicFlow.
/// <para>
/// Enables or disables the Basic (Classic) authentication flow. For more information,
/// see <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html">Identity
/// Pools (Federated Identities) Authentication Flow</a> in the <i>Amazon Cognito Developer
/// Guide</i>.
/// </para>
/// </summary>
public bool AllowClassicFlow
{
get { return this._allowClassicFlow.GetValueOrDefault(); }
set { this._allowClassicFlow = value; }
}
// Check to see if AllowClassicFlow property is set
internal bool IsSetAllowClassicFlow()
{
return this._allowClassicFlow.HasValue;
}
/// <summary>
/// Gets and sets the property AllowUnauthenticatedIdentities.
/// <para>
/// TRUE if the identity pool supports unauthenticated logins.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public bool AllowUnauthenticatedIdentities
{
get { return this._allowUnauthenticatedIdentities.GetValueOrDefault(); }
set { this._allowUnauthenticatedIdentities = value; }
}
// Check to see if AllowUnauthenticatedIdentities property is set
internal bool IsSetAllowUnauthenticatedIdentities()
{
return this._allowUnauthenticatedIdentities.HasValue;
}
/// <summary>
/// Gets and sets the property CognitoIdentityProviders.
/// <para>
/// A list representing an Amazon Cognito user pool and its client ID.
/// </para>
/// </summary>
public List<CognitoIdentityProviderInfo> CognitoIdentityProviders
{
get { return this._cognitoIdentityProviders; }
set { this._cognitoIdentityProviders = value; }
}
// Check to see if CognitoIdentityProviders property is set
internal bool IsSetCognitoIdentityProviders()
{
return this._cognitoIdentityProviders != null && this._cognitoIdentityProviders.Count > 0;
}
/// <summary>
/// Gets and sets the property DeveloperProviderName.
/// <para>
/// The "domain" by which Cognito will refer to your users.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=128)]
public string DeveloperProviderName
{
get { return this._developerProviderName; }
set { this._developerProviderName = value; }
}
// Check to see if DeveloperProviderName property is set
internal bool IsSetDeveloperProviderName()
{
return this._developerProviderName != null;
}
/// <summary>
/// Gets and sets the property IdentityPoolId.
/// <para>
/// An identity pool ID in the format REGION:GUID.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=55)]
public string IdentityPoolId
{
get { return this._identityPoolId; }
set { this._identityPoolId = value; }
}
// Check to see if IdentityPoolId property is set
internal bool IsSetIdentityPoolId()
{
return this._identityPoolId != null;
}
/// <summary>
/// Gets and sets the property IdentityPoolName.
/// <para>
/// A string that you provide.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=128)]
public string IdentityPoolName
{
get { return this._identityPoolName; }
set { this._identityPoolName = value; }
}
// Check to see if IdentityPoolName property is set
internal bool IsSetIdentityPoolName()
{
return this._identityPoolName != null;
}
/// <summary>
/// Gets and sets the property IdentityPoolTags.
/// <para>
/// The tags that are assigned to the identity pool. A tag is a label that you can apply
/// to identity pools to categorize and manage them in different ways, such as by purpose,
/// owner, environment, or other criteria.
/// </para>
/// </summary>
public Dictionary<string, string> IdentityPoolTags
{
get { return this._identityPoolTags; }
set { this._identityPoolTags = value; }
}
// Check to see if IdentityPoolTags property is set
internal bool IsSetIdentityPoolTags()
{
return this._identityPoolTags != null && this._identityPoolTags.Count > 0;
}
/// <summary>
/// Gets and sets the property OpenIdConnectProviderARNs.
/// <para>
/// The ARNs of the OpenID Connect providers.
/// </para>
/// </summary>
public List<string> OpenIdConnectProviderARNs
{
get { return this._openIdConnectProviderARNs; }
set { this._openIdConnectProviderARNs = value; }
}
// Check to see if OpenIdConnectProviderARNs property is set
internal bool IsSetOpenIdConnectProviderARNs()
{
return this._openIdConnectProviderARNs != null && this._openIdConnectProviderARNs.Count > 0;
}
/// <summary>
/// Gets and sets the property SamlProviderARNs.
/// <para>
/// An array of Amazon Resource Names (ARNs) of the SAML provider for your identity pool.
/// </para>
/// </summary>
public List<string> SamlProviderARNs
{
get { return this._samlProviderARNs; }
set { this._samlProviderARNs = value; }
}
// Check to see if SamlProviderARNs property is set
internal bool IsSetSamlProviderARNs()
{
return this._samlProviderARNs != null && this._samlProviderARNs.Count > 0;
}
/// <summary>
/// Gets and sets the property SupportedLoginProviders.
/// <para>
/// Optional key:value pairs mapping provider names to provider app IDs.
/// </para>
/// </summary>
[AWSProperty(Max=10)]
public Dictionary<string, string> SupportedLoginProviders
{
get { return this._supportedLoginProviders; }
set { this._supportedLoginProviders = value; }
}
// Check to see if SupportedLoginProviders property is set
internal bool IsSetSupportedLoginProviders()
{
return this._supportedLoginProviders != null && this._supportedLoginProviders.Count > 0;
}
}
} | 36.151261 | 118 | 0.615528 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CognitoIdentity/Generated/Model/UpdateIdentityPoolResponse.cs | 8,604 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
namespace Microsoft.Azure.Internal.Subscriptions
{
public static partial class SubscriptionClientExtensions
{
}
}
| 32.517241 | 77 | 0.71474 | [
"MIT"
] | DalavanCloud/azure-powershell | src/ResourceManager/Common/Commands.ResourceManager.Common/Generated/SubscriptionClientExtensions.cs | 915 | C# |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Apache License, Version 2.0
// Please see http://www.apache.org/licenses/LICENSE-2.0 for details.
// All other rights reserved.
using AgFx;
using System;
using System.Linq;
using System.Xml.Linq;
namespace NWSWeather.Sample.ViewModels
{
/// <summary>
/// Our wrapper around fetching location information for a zipcode - city, state, etc.
/// </summary>
[CachePolicy(CachePolicy.Forever)]
public class ZipCodeVm : ModelItemBase<ZipCodeLoadContext>
{
public ZipCodeVm()
{
}
public ZipCodeVm(string zipcode)
: base(new ZipCodeLoadContext(zipcode))
{
}
#region Property City
private string _City;
public string City
{
get
{
return _City;
}
set
{
if (_City != value)
{
_City = value;
RaisePropertyChanged("City");
}
}
}
#endregion
#region Property State
private string _State;
public string State
{
get
{
return _State;
}
set
{
if (_State != value)
{
_State = value;
RaisePropertyChanged("State");
}
}
}
#endregion
#region Property AreaCode
private string _AreaCode;
public string AreaCode
{
get
{
return _AreaCode;
}
set
{
if (_AreaCode != value)
{
_AreaCode = value;
RaisePropertyChanged("AreaCode");
}
}
}
#endregion
#region Property TimeZone
private string _TimeZone;
public string TimeZone
{
get
{
return _TimeZone;
}
set
{
if (_TimeZone != value)
{
_TimeZone = value;
RaisePropertyChanged("TimeZone");
}
}
}
#endregion
/// <summary>
/// Loaders know how to do two things:
///
/// 1. Request new data
/// 2. Process the response of that request into an object of the containing type (ZipCodeVm in this case)
/// </summary>
public class ZipCodeVmDataLoader : IDataLoader<ZipCodeLoadContext>
{
private const string ZipCodeUriFormat = "http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip={0}";
public LoadRequest GetLoadRequest(ZipCodeLoadContext loadContext, Type objectType)
{
// build the URI, return a WebLoadRequest.
string uri = String.Format(ZipCodeUriFormat, loadContext.ZipCode);
return new WebLoadRequest(loadContext, new Uri(uri));
}
public object Deserialize(ZipCodeLoadContext loadContext, Type objectType, System.IO.Stream stream)
{
// the XML will look like hte following, so we parse it.
//<?xml version="1.0" encoding="utf-8"?>
//<NewDataSet>
// <Table>
// <CITY>Kirkland</CITY>
// <STATE>WA</STATE>
// <ZIP>98033</ZIP>
// <AREA_CODE>425</AREA_CODE>
// <TIME_ZONE>P</TIME_ZONE>
// </Table>
//</NewDataSet>
var xml = XElement.Load(stream);
var table = (
from t in xml.Elements("Table")
select t).FirstOrDefault();
if (table == null) {
throw new ArgumentException("Unknown zipcode " + loadContext.ZipCode);
}
ZipCodeVm vm = new ZipCodeVm(loadContext.ZipCode);
vm.City = table.Element("CITY").Value;
vm.State = table.Element("STATE").Value;
vm.AreaCode = table.Element("AREA_CODE").Value;
vm.TimeZone = table.Element("TIME_ZONE").Value;
return vm;
}
}
}
}
| 28.35625 | 115 | 0.461979 | [
"Apache-2.0"
] | l3v5y/AgFx | Samples/NWSWeather.Sample/ViewModels/ZipCodeVm.cs | 4,539 | 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.Linq;
using Stride.Core.Annotations;
using Stride.Core.Reflection;
using Stride.Core.Presentation.Quantum;
using Stride.Core.Presentation.Quantum.Presenters;
using Stride.Core.Quantum;
namespace Stride.Core.Assets.Editor.Quantum.NodePresenters.Commands
{
public class AddPrimitiveKeyCommand : SyncNodePresenterCommandBase
{
/// <summary>
/// The name of this command.
/// </summary>
public const string CommandName = "AddPrimitiveKey";
/// <inheritdoc/>
public override string Name => CommandName;
/// <inheritdoc/>
public override CombineMode CombineMode => CombineMode.CombineOnlyForAll;
/// <inheritdoc/>
public override bool CanAttach(INodePresenter nodePresenter)
{
// We are in a dictionary...
var dictionaryDescriptor = nodePresenter.Descriptor as DictionaryDescriptor;
if (dictionaryDescriptor == null)
return false;
// ... that is not read-only...
var memberCollection = (nodePresenter as MemberNodePresenter)?.MemberAttributes.OfType<MemberCollectionAttribute>().FirstOrDefault()
?? nodePresenter.Descriptor.Attributes.OfType<MemberCollectionAttribute>().FirstOrDefault();
if (memberCollection?.ReadOnly == true)
return false;
// ... can construct key type...
if (!AddNewItemCommand.CanConstruct(dictionaryDescriptor.KeyType))
return false;
// ... and can construct value type
var elementType = dictionaryDescriptor.ValueType;
return AddNewItemCommand.CanAdd(elementType);
}
/// <inheritdoc/>
protected override void ExecuteSync(INodePresenter nodePresenter, object parameter, object preExecuteResult)
{
var assetNodePresenter = nodePresenter as IAssetNodePresenter;
var dictionaryDescriptor = (DictionaryDescriptor)nodePresenter.Descriptor;
var value = nodePresenter.Value;
var newKey = dictionaryDescriptor.KeyType != typeof(string) ? new NodeIndex(Activator.CreateInstance(dictionaryDescriptor.KeyType)) : GenerateStringKey(value, dictionaryDescriptor, parameter as string);
var newItem = dictionaryDescriptor.ValueType.Default();
var instance = CreateInstance(dictionaryDescriptor.ValueType);
if (!AddNewItemCommand.IsReferenceType(dictionaryDescriptor.ValueType) && (assetNodePresenter == null || !assetNodePresenter.IsObjectReference(instance)))
newItem = instance;
nodePresenter.AddItem(newItem, newKey);
}
/// <summary>
/// Creates an instance of the specified type using that type's default constructor.
/// </summary>
/// <param name="type">The type of object to create.</param>
/// <returns>A reference to the newly created object.</returns>
/// <seealso cref="Activator.CreateInstance(Type)"/>
/// <exception cref="ArgumentNullException">type is null.</exception>
private static object CreateInstance(Type type)
{
if (type == null) throw new ArgumentNullException(nameof(type));
// abstract type cannot be instantiated
if (type.IsAbstract)
return null;
// string is a special case
if (type == typeof(string))
return string.Empty;
// note:
// Type not having a public parameterless constructor will throw a MissingMethodException at this point.
// This is intended as YAML serialization requires this constructor.
return ObjectFactoryRegistry.NewInstance(type);
}
internal static NodeIndex GenerateStringKey(object dictionary, ITypeDescriptor descriptor, string baseValue)
{
// TODO: use a dialog service and popup a message when the given key is invalid
const string defaultKey = "Key";
if (string.IsNullOrWhiteSpace(baseValue))
baseValue = defaultKey;
var i = 1;
string baseName = baseValue;
var dictionaryDescriptor = (DictionaryDescriptor)descriptor;
while (dictionaryDescriptor.ContainsKey(dictionary, baseValue))
{
baseValue = baseName + " " + ++i;
}
return new NodeIndex(baseValue);
}
}
}
| 43.254545 | 214 | 0.643758 | [
"MIT"
] | Aggror/Stride | sources/editor/Stride.Core.Assets.Editor/Quantum/NodePresenters/Commands/AddPrimitiveKeyCommand.cs | 4,758 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Design;
using Microsoft.Win32;
namespace System.Windows.Forms.ComponentModel.Com2Interop
{
public interface IComPropertyBrowser
{
void DropDownDone();
bool InPropertySet { get; }
event ComponentRenameEventHandler ComComponentNameChanged;
bool EnsurePendingChangesCommitted();
void HandleF4();
void LoadState(RegistryKey key);
void SaveState(RegistryKey key);
}
}
| 29.73913 | 71 | 0.726608 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/IComPropertyBrowser.cs | 686 | C# |
/*
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HTLib2
{
/// <summary>
/// AVL tree whose nodes are linked as a linked-list in increasing order
/// </summary>
///////////////////////////////////////////////////////////////////////
/// Binar Search Tree
///////////////////////////////////////////////////////////////////////
public class LinkedBST<T>
{
public struct RetT
{
public T value;
public static RetT New(T val) { return new RetT { value = val }; }
}
public class Node : BTree.Node
{
public T value ;
public Node parent;
public Node left ;
public Node right ;
public Node prev ;
public Node next ;
public static Node New(T value,Node parent,Node left, Node right, Node prev, Node next)
{
return new Node
{
value = value ,
parent = parent,
left = left ,
right = right ,
prev = prev ,
next = next ,
};
}
}
Node root;
int cont;
Comparison<T> comp;
public Comparison<T> Comp { get { return comp; } }
public void ChangeComp(Comparison<T> comp)
{
this.comp = comp;
HDebug.Assert(Validate());
}
public LinkedBST(Comparison<T> comp)
{
this.root = null;
this.cont = 0;
this.comp = comp;
}
public bool IsEmpty () { return (root == null); }
public bool Contains(T query) { return (Search(query) != null); }
public T? Search (T query) { Node<T> node = BstSearchWithParent( root, null, query, _comp).ret; if(node == null) return null; return RetT.New(node.value); }
public void Insert (T value) { Node<T> node = BstInsert (ref root , value, _comp) ; if(node == null) return null; return RetT.New(node.value); }
public void Delete (T query) { var del = BstDelete (ref root , query, _comp) ; if(del == null) return null ; return RetT.New(del.Value.value); }
public bool Validate()
{
if(BstValidateConnection(root) == false) return false;
if(BstValidateOrder(root, _comp) == false) return false;
return true;
}
public Node SearchNode(T query)
{
Node node = root;
while(node != null)
{
int cmp = comp(query, node.value);
if(cmp == 0)
{
return node;
}
else if(cmp < 0)
{
// query < node
node = node.left;
}
else
{
// node < query
node = node.right;
}
}
return null;
}
///////////////////////////////////////////////////////////////////////
/// BST Insert
///
/// 1. Insert value into BST
/// 2. Return the inserted node
///////////////////////////////////////////////////////////////////////
static bool InsertNode_selftest = true;
public Node InsertNode(T value)
{
if(InsertNode_selftest)
{
InsertNode_selftest = false;
Comparison<int> _compare = delegate(int a, int b) { return a - b; };
//Node<int> _root = null;
//BstInsert(ref _root, 10, _compare); HDebug.Assert(_root.ToStringSimple() == "(10)" );
//BstInsert(ref _root, 5, _compare); HDebug.Assert(_root.ToStringSimple() == "(5,10,_)" );
//BstInsert(ref _root, 20, _compare); HDebug.Assert(_root.ToStringSimple() == "(5,10,20)" );
//BstInsert(ref _root, 2, _compare); HDebug.Assert(_root.ToStringSimple() == "((2,5,_),10,20)" );
//BstInsert(ref _root, 7, _compare); HDebug.Assert(_root.ToStringSimple() == "((2,5,7),10,20)" );
//BstInsert(ref _root, 4, _compare); HDebug.Assert(_root.ToStringSimple() == "(((_,2,4),5,7),10,20)" );
//BstInsert(ref _root, 6, _compare); HDebug.Assert(_root.ToStringSimple() == "(((_,2,4),5,(6,7,_)),10,20)" );
//BstInsert(ref _root, 30, _compare); HDebug.Assert(_root.ToStringSimple() == "(((_,2,4),5,(6,7,_)),10,(_,20,30))" );
//BstInsert(ref _root, 3, _compare); HDebug.Assert(_root.ToStringSimple() == "(((_,2,(3,4,_)),5,(6,7,_)),10,(_,20,30))" );
//BstInsert(ref _root, 25, _compare); HDebug.Assert(_root.ToStringSimple() == "(((_,2,(3,4,_)),5,(6,7,_)),10,(_,20,(25,30,_)))");
}
if(root == null)
{
root = new Node
{
value = value,
parent = null,
left = null,
right = null,
prev = null,
next = null,
};
return root;
}
else
{
Node p = root;
while(true)
{
int cmp = comp(value, p.value);
if(cmp < 0)
{
if(p.left == null)
{
Node node = Node.New(value, p, null, null, p.prev, p);
p.prev.next = node;
p.prev = node;
p.left = node;
return node;
}
else
{
p = p.left;
}
}
else
{
if(p.right == null)
{
Node node = Node.New(value, p, null, null, p, p.next);
p.next.prev = node;
p.next = node;
p.right = node;
return node;
}
else
{
p = p.right;
}
}
}
}
}
///////////////////////////////////////////////////////////////////////
/// BST Delete
///
/// 1. Delete node whose value is same to query
/// 2. Return the value in the deleted node
///////////////////////////////////////////////////////////////////////
T DeleteNode(ref Node root, T query)
{
return DeleteNodeImpl(ref root, query);
}
T DeleteNodeImpl(ref Node node, T query)
{
// find node to delete
HDebug.Assert(node != null);
int query_node = comp(query, node.value);
if (query_node < 0) return DeleteNodeImpl(ref node.left , query);
else if(query_node > 0) return DeleteNodeImpl(ref node.right, query);
else if(query_node == 0) return DeleteNodeImpl(ref node);
else throw new Exception();
}
T DeleteNodeImpl(ref Node node)
{
if(node.left == null && node.right == null)
{
// delete a leaf
T value = node.value;
Node parent = node.parent;
node = null;
return (value, parent);
}
else if(node.left != null && node.right == null)
{
// has left child
T value = node.value;
Node parent = node.parent;
node = node.left;
node.parent = parent;
return (value, parent);
}
else if(node.left == null && node.right != null)
{
// has right child
T value = node.value;
Node parent = node.parent;
node = node.right;
node.parent = parent;
return (value, parent);
}
else
{
// has both left and right children
// 1. find predecessor reference
ref Node Pred(ref Node lnode)
{
if(lnode.right == null)
return ref lnode;
return ref Pred(ref lnode.right);
};
ref Node pred = ref Pred(ref node.left);
// 2. backup value to return
T value = node.value;
// 3. copy pred.value to node
node.value = pred.value;
// 4. node updated
Node pred_parent = pred.parent;
// 4. delete pred; since (*pred).right == null, make pred = (*pred).left
pred = pred.left;
if(pred != null)
pred.parent = pred_parent;
return (value, pred_parent);
}
}
}
///////////////////////////////////////////////////////////////////////
/// Validate connections
///////////////////////////////////////////////////////////////////////
static bool BstValidateConnection<T>(Node<T> root)
{
if(root.parent != null)
return false;
if(root.ValidateConnection() == false)
return false;
return true;
}
///////////////////////////////////////////////////////////////////////
/// Validate order
///////////////////////////////////////////////////////////////////////
static bool BstValidateOrder<T>(Node<T> root, Comparison<T> compare)
{
if(root == null)
return true;
int count = root.Count();
Node<T> node = root.MinNode();
Node<T> next = node.Successor();
if(next == null)
return true;
int num_compare = 0;
while(next != null)
{
if(compare(node.value, next.value) > 0)
return false;
num_compare ++;
node = next;
next = next.Successor();
}
if(num_compare != count-1)
return false;
return true;
}
///////////////////////////////////////////////////////////////////////
/// BST Search
///////////////////////////////////////////////////////////////////////
static bool BstSearch_selftest = true;
//public T BstSearch(T query)
//{
// Node node = BstSearch(root, query);
// if(node == null)
// return default(T);
// return node.value;
//}
static Node<T> BstSearch<T>(Node<T> node, T query, Comparison<T> compare)
{
(Node<T> ret, Node<T> ret_parent) = BstSearchWithParent(node, null, query, compare);
return ret;
}
static (Node<T> ret, Node<T> ret_parent) BstSearchWithParent<T>(Node<T> node, Node<T> node_parent, T query, Comparison<T> compare)
{
if(BstSearch_selftest)
{
BstSearch_selftest = false;
Comparison<int> _compare = delegate(int a, int b) { return a - b; };
Node<int> _root = null;
BstInsertRange(ref _root, new int[] { 10, 5, 20, 2, 7, 4, 6, 30, 3, 25 }, _compare);
HDebug.Assert(_root.ToString() == "(((_,2,(3,4,_)),5,(6,7,_)),10,(_,20,(25,30,_)))");
HDebug.Assert((BstSearchWithParent(_root, null, 10, _compare).ret != null) == true);
HDebug.Assert((BstSearchWithParent(_root, null, 25, _compare).ret != null) == true);
HDebug.Assert((BstSearchWithParent(_root, null, 4, _compare).ret != null) == true);
HDebug.Assert((BstSearchWithParent(_root, null, 7, _compare).ret != null) == true);
HDebug.Assert((BstSearchWithParent(_root, null, 0, _compare).ret != null) == false);
HDebug.Assert((BstSearchWithParent(_root, null, 9, _compare).ret != null) == false);
HDebug.Assert((BstSearchWithParent(_root, null, 15, _compare).ret != null) == false);
HDebug.Assert((BstSearchWithParent(_root, null, 50, _compare).ret != null) == false);
}
if(node == null)
return (null, node_parent);
int query_node = compare(query, node.value);
if (query_node < 0) return BstSearchWithParent(node.left , node, query, compare);
else if(query_node > 0) return BstSearchWithParent(node.right, node, query, compare);
else return (node, node_parent);
}
}
*/ | 40.975904 | 178 | 0.399515 | [
"MIT"
] | htna/HCsbLib | HCsbLib/HCsbLib/HTLib2/HDataStruc.Tree/LinkedBST.cs | 13,606 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace JekyllLibrary.Library
{
public partial class ModernWarfare
{
public class Localize : IXAssetPool
{
public override string Name => "Localize Entry";
public override int Index => (int)XAssetType.ASSET_TYPE_LOCALIZE_ENTRY;
/// <summary>
/// Structure of a Modern Warfare LocalizeEntry.
/// </summary>
private struct LocalizeEntry
{
public long Name { get; set; }
public long Value { get; set; }
}
/// <summary>
/// Load the valid XAssets for the Localize XAsset Pool.
/// </summary>
/// <param name="instance"></param>
/// <returns>List of Localize XAsset objects.</returns>
public override List<GameXAsset> Load(JekyllInstance instance)
{
List<GameXAsset> results = new List<GameXAsset>();
DBAssetPool pool = instance.Reader.ReadStruct<DBAssetPool>(instance.Game.BaseAddress + instance.Game.DBAssetPools + (Index * Marshal.SizeOf<DBAssetPool>()));
Entries = pool.Entries;
ElementSize = pool.ElementSize;
PoolSize = pool.PoolSize;
if (IsValidPool(Name, ElementSize, Marshal.SizeOf<LocalizeEntry>()) == false)
{
return results;
}
Dictionary<string, string> entries = new Dictionary<string, string>();
for (int i = 0; i < PoolSize; i++)
{
LocalizeEntry header = instance.Reader.ReadStruct<LocalizeEntry>(Entries + (i * ElementSize));
if (IsNullXAsset(header.Name))
{
continue;
}
string key = instance.Reader.ReadNullTerminatedString(header.Name).ToUpper();
if (entries.TryGetValue(key, out string _))
{
continue;
}
string value = instance.Reader.ReadNullTerminatedString(header.Value, nullCheck: true);
entries.Add(key, value);
Console.WriteLine($"Exported {Name} {key}");
}
string path = Path.Combine(instance.ExportPath, "localize.json");
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (StreamWriter file = File.CreateText(path))
{
file.Write(JsonConvert.SerializeObject(entries, Formatting.Indented));
}
return results;
}
/// <summary>
/// Exports the specified Localize XAsset.
/// </summary>
/// <param name="xasset"></param>
/// <param name="instance"></param>
/// <returns>Status of the export operation.</returns>
public override JekyllStatus Export(GameXAsset xasset, JekyllInstance instance)
{
return JekyllStatus.Success;
}
}
}
} | 35.322581 | 173 | 0.525419 | [
"MIT"
] | iAmThatMichael/Jekyll | Jekyll.Library/Game/ModernWarfare/XAssets/Localize.cs | 3,287 | C# |
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Terraria;
using Terraria.ID;
namespace Starvers.PlayerBoosts.Skills
{
public class UniverseBlast : UltimateSlash
{
private string msg;
private readonly int[] Projs =
{
ProjectileID.NebulaBlaze1,
ProjectileID.NebulaBlaze1,
ProjectileID.NebulaBlaze1,
ProjectileID.NebulaBlaze1,
ProjectileID.NebulaBlaze1,
ProjectileID.NebulaBlaze2,
ProjectileID.NebulaBlaze2,
ProjectileID.CrystalBullet,
ProjectileID.CrystalBullet,
ProjectileID.CrystalBullet,
ProjectileID.CrystalBullet,
ProjectileID.CrystalBullet,
ProjectileID.CrystalLeafShot,
ProjectileID.CrystalLeafShot,
ProjectileID.CrystalLeafShot,
ProjectileID.CrystalLeafShot,
ProjectileID.CrystalStorm,
ProjectileID.CrystalStorm,
ProjectileID.CrystalStorm,
ProjectileID.CrystalStorm,
ProjectileID.CrystalStorm,
};
public UniverseBlast()
{
msg = @"我就是懒, 怎么着?
有本事你顺着网线来打我啊";
Summary = "[20000][最终技能]召唤大量星云之门释放弹幕";
}
protected override void AsyncRelease(StarverPlayer player)
{
Task.Run(() =>
{
try
{
unsafe
{
int count = Rand.Next(6, 15);
int damage = 1500;
damage += (int)(5 * Math.Sqrt(player.Level));
int* Indexes = stackalloc int[count];
Vector* Positions = stackalloc Vector[count];
Vector2* AlsoPositions = (Vector2*)Positions;
for (int i = 0; i < count; i++)
{
AlsoPositions[i] = player.Center;
AlsoPositions[i] += Rand.NextVector2(16 * 50, 16 * 45);
Indexes[i] =
player.NewProj(AlsoPositions[i], Rand.NextVector2(0.35f), ProjectileID.NebulaArcanum, damage + Rand.Next(50));
}
var timer = 0;
while (timer < 4000)
{
for (int i = 0; i < count; i++)
{
#region Fix
var proj = Main.projectile[Indexes[i]];
if (!proj.active || proj.type != ProjectileID.NebulaArcanum)
{
Indexes[i] = player.NewProj(AlsoPositions[i], Rand.NextVector2(0.35f), ProjectileID.NebulaArcanum, damage + Rand.Next(50));
proj = Main.projectile[Indexes[i]];
}
proj.position = AlsoPositions[i];
proj.SendData();
#endregion
player.NewProj(Main.projectile[Indexes[i]].Center, Rand.NextVector2(13 + Rand.Next(6)), Projs.Next(), damage / Rand.Next(2, 4) + Rand.Next(70));
Thread.Sleep(2);
player.NewProj(Main.projectile[Indexes[i]].Center, Rand.NextVector2(13 + Rand.Next(6)), Projs.Next(), damage / Rand.Next(2, 4) + Rand.Next(70));
}
Thread.Sleep(100);
timer += 100;
}
for (int i = 0; i < count; i++)
{
AlsoPositions[i] = player.Center;
Positions[i] += Vector.FromPolar(Math.PI * 2 * i / count + Math.PI / 2, 16 * 60);
player.ProjSector(AlsoPositions[i], 19, 16 * 3, Positions[i].Angle + Math.PI, Math.PI / 3, damage, ProjectileID.DD2SquireSonicBoom, 5);
}
}
}
catch
{
}
});
}
}
}
| 28.190909 | 152 | 0.643018 | [
"MIT"
] | ArkeyDarz/Starver | PlayerBoosts/Skills/UniverseBlast.cs | 3,173 | C# |
namespace DotNetInterceptTester.My_System.Security.Cryptography.Rijndael
{
public class CreateEncryptor_System_Security_Cryptography_Rijndael
{
public static bool _CreateEncryptor_System_Security_Cryptography_Rijndael( )
{
//Parameters
//ReturnType/Value
System.Security.Cryptography.ICryptoTransform returnVal_Real = null;
System.Security.Cryptography.ICryptoTransform returnVal_Intercepted = null;
//Exception
Exception exception_Real = null;
Exception exception_Intercepted = null;
InterceptionMaintenance.disableInterception( );
try
{
returnValue_Real = System.Security.Cryptography.Rijndael.CreateEncryptor();
}
catch( Exception e )
{
exception_Real = e;
}
InterceptionMaintenance.enableInterception( );
try
{
returnValue_Intercepted = System.Security.Cryptography.Rijndael.CreateEncryptor();
}
catch( Exception e )
{
exception_Intercepted = e;
}
Return ( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
}
}
}
| 24.021277 | 127 | 0.718335 | [
"MIT"
] | SecurityInnovation/Holodeck | Test/Automation/DotNetInterceptTester/DotNetInterceptTester/System.Security.Cryptography.Rijndael.CreateEncryptor().cs | 1,129 | C# |
using System;
namespace MagiCommon.Models
{
public class ElasticFileInfo
{
public string Id { get; set; }
public string Name { get; set; }
public string MimeType { get; set; }
public string Extension { get; set; }
public long Size { get; set; }
public DateTimeOffset LastModified { get; set; }
public DateTimeOffset LastUpdated { get; set; }
public string Hash { get; set; }
public string FileText { get; set; }
public string UserId { get; set; }
public bool IsPublic { get; set; }
public bool IsDeleted { get; set; }
}
}
| 30.142857 | 56 | 0.589258 | [
"MIT"
] | magico13/MagiCloud | MagiCommon/Models/ElasticFileInfo.cs | 635 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Dds.Model.V20151201
{
public class DescribeBackupDBsResponse : AcsResponse
{
private string requestId;
private int? pageNumber;
private int? pageSize;
private int? totalCount;
private List<DescribeBackupDBs_Database> databases;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public int? PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
}
}
public int? TotalCount
{
get
{
return totalCount;
}
set
{
totalCount = value;
}
}
public List<DescribeBackupDBs_Database> Databases
{
get
{
return databases;
}
set
{
databases = value;
}
}
public class DescribeBackupDBs_Database
{
private string dBName;
public string DBName
{
get
{
return dBName;
}
set
{
dBName = value;
}
}
}
}
}
| 17.290598 | 63 | 0.62432 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-dds/Dds/Model/V20151201/DescribeBackupDBsResponse.cs | 2,023 | C# |
using System;
namespace WindsorDependencyResolver_Specification
{
class DependencyOnTypeWithGernericParams
{
public String Dependency { get; private set; }
public DependencyOnTypeWithGernericParams(String dependency)
{
Dependency = dependency;
}
}
} | 22.571429 | 68 | 0.661392 | [
"MIT"
] | openrasta/openrasta-core | src/OpenRasta.DI.Windsor.Tests.Unit/MockTypes.cs | 318 | C# |
using Commands.Security;
using Microsoft.Azure.Commands.Security.Common;
using Microsoft.Azure.Commands.SecurityCenter.Models.SqlVulnerabilityAssessment;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Text;
namespace Microsoft.Azure.Commands.SecurityCenter.Cmdlets.SqlVulnerabilityAssessment
{
[Cmdlet(VerbsCommon.Add, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "SecuritySqlVulnerabilityAssessmentBaseline", DefaultParameterSetName = ParameterSetNames.ResourceIdWithBaselineObject, SupportsShouldProcess = true), OutputType(typeof(PSSqlVulnerabilityAssessmentBaselineResults))]
public class AddSecuritySqlVulnerabilityAssessmentBaseline : SqlVulnerabilityAssessmentBaseWithBaseline
{
[Parameter(ParameterSetName = ParameterSetNames.ResourceIdWithBaselineObject, Mandatory = true, HelpMessage = ParameterHelpMessages.RuleId)]
[Parameter(ParameterSetName = ParameterSetNames.OnPremMachinesWithBaselineObject, Mandatory = true, HelpMessage = ParameterHelpMessages.RuleId)]
public string RuleId { get; set; }
[Parameter(ParameterSetName = ParameterSetNames.ResourceIdWithBaselineObject, Mandatory = false, HelpMessage = ParameterHelpMessages.Baseline)]
[Parameter(ParameterSetName = ParameterSetNames.OnPremMachinesWithBaselineObject, Mandatory = false, HelpMessage = ParameterHelpMessages.Baseline)]
public string[][] Baseline { get; set; }
[Parameter(ParameterSetName = ParameterSetNames.InputObjectBaselineWithResourceId, Mandatory = true, ValueFromPipeline = true, HelpMessage = ParameterHelpMessages.InputObject)]
[Parameter(ParameterSetName = ParameterSetNames.InputObjectBaselineWithOnPrem, Mandatory = true, ValueFromPipeline = true, HelpMessage = ParameterHelpMessages.InputObject)]
public PSSqlVulnerabilityAssessmentBaselineResults InputObject { get; set; }
public override void ExecuteCmdlet()
{
var databaseResourceId = BuildDatabaseResourceId();
if (this.ParameterSetName == ParameterSetNames.InputObjectBaselineWithResourceId
|| this.ParameterSetName == ParameterSetNames.InputObjectBaselineWithOnPrem)
{
foreach (var rule in InputObject.Results)
{
if (ShouldProcess(rule.Name, $"Adding baseline for {databaseResourceId}."))
{
var results = SecurityCenterClient.SqlVulnerabilityAssessmentBaselineRules.CreateOrUpdateWithHttpMessagesAsync(rule.Name, WorkspaceId, VulnerabilityAssessmentConstants.ApiVersion, databaseResourceId, results: rule.Results).GetAwaiter().GetResult().Body;
WriteObject(results?.ConvertToPSType());
}
}
}
else
{
if (ShouldProcess(RuleId, $"Adding baseline for {databaseResourceId}."))
{
if (Baseline == null)
{
var results = SecurityCenterClient.SqlVulnerabilityAssessmentBaselineRules.CreateOrUpdateWithHttpMessagesAsync(RuleId, WorkspaceId, VulnerabilityAssessmentConstants.ApiVersion, databaseResourceId, latestScan: true).GetAwaiter().GetResult().Body;
WriteObject(results?.ConvertToPSType());
}
else
{
var results = SecurityCenterClient.SqlVulnerabilityAssessmentBaselineRules.CreateOrUpdateWithHttpMessagesAsync(RuleId, WorkspaceId, VulnerabilityAssessmentConstants.ApiVersion, databaseResourceId, results: Baseline).GetAwaiter().GetResult().Body;
WriteObject(results?.ConvertToPSType());
}
}
}
}
}
}
| 65 | 301 | 0.696923 | [
"MIT"
] | Agazoth/azure-powershell | src/Security/Security/Cmdlets/SqlVulnerabilityAssessment/AddSecuritySqlVulnerabilityAssessmentBaseline.cs | 3,843 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.Tools.Internal;
namespace Microsoft.AspNetCore.Authentication.JwtBearer.Tools;
internal sealed class ProjectCommandLineApplication : CommandLineApplication
{
public CommandOption ProjectOption { get; private set; }
public IReporter Reporter { get; private set; }
public ProjectCommandLineApplication(IReporter reporter, bool throwOnUnexpectedArg = true, bool continueAfterUnexpectedArg = false, bool treatUnmatchedOptionsAsArguments = false)
: base(throwOnUnexpectedArg, continueAfterUnexpectedArg, treatUnmatchedOptionsAsArguments)
{
ProjectOption = Option(
"-p|--project",
Resources.ProjectOption_Description,
CommandOptionType.SingleValue);
Reporter = reporter;
}
public ProjectCommandLineApplication Command(string name, Action<ProjectCommandLineApplication> configuration)
{
var command = new ProjectCommandLineApplication(Reporter) { Name = name, Parent = this };
Commands.Add(command);
configuration(command);
return command;
}
}
| 38.666667 | 182 | 0.745298 | [
"Apache-2.0"
] | aspnet/AspNetCore | src/Tools/dotnet-user-jwts/src/Commands/ProjectCommandLineApplication.cs | 1,276 | C# |
namespace DarkstarCrm.Repository.Interfaces
{
public interface IBaseEntity
{
int Id { get; set; }
}
} | 17.428571 | 44 | 0.631148 | [
"Apache-2.0"
] | glubox/darkstar-crm | DarkstarCrm/DarkstarCrm.Repository.Interfaces/IBaseEntity.cs | 124 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReadSharp.Encodings
{
public class Encoder
{
/// <summary>
/// All available custom encodings
/// </summary>
private static Dictionary<string, string> customEncodings = new Dictionary<string, string>()
{
{ "windows-1250", "Windows1250" },
{ "windows-1251", "Windows1251" },
{ "windows-1252", "Windows1252" },
{ "windows-1253", "Windows1253" },
{ "windows-1254", "Windows1254" },
{ "windows-1255", "Windows1255" },
{ "windows-1256", "Windows1256" },
{ "windows-1257", "Windows1257" },
{ "windows-1258", "Windows1258" },
{ "iso-8859-1", "Iso88591" },
{ "iso-8859-2", "Iso88592" },
{ "iso-8859-3", "Iso88593" },
{ "iso-8859-4", "Iso88594" },
{ "iso-8859-5", "Iso88595" },
{ "iso-8859-6", "Iso88596" },
{ "iso-8859-7", "Iso88597" },
{ "iso-8859-8", "Iso88598" },
{ "iso-8859-9", "Iso88599" },
{ "iso-8859-13", "Iso885913" },
{ "iso-8859-15", "Iso885915" }
};
/// <summary>
/// try custom encoder
/// </summary>
private bool tryCustomEncoder;
/// <summary>
/// Initializes a new instance of the <see cref="Encoder"/> class.
/// </summary>
public Encoder(bool tryCustomEncoder = false)
{
this.tryCustomEncoder = tryCustomEncoder;
}
/// <summary>
/// Gets the encoding from string.
/// </summary>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
public Encoding GetEncodingFromString(string encoding)
{
Encoding correctEncoding = null;
if (!String.IsNullOrEmpty(encoding))
{
// try get encoding from string
try
{
correctEncoding = Encoding.GetEncoding(encoding);
}
catch (ArgumentException)
{
// encoding not found in environment
// handled in finally block as it could also generate null without throwing exceptions
}
finally
{
// use a custom encoder
if (tryCustomEncoder && correctEncoding == null)
{
try
{
KeyValuePair<string, string> customEncoder = customEncodings.FirstOrDefault(item => item.Key == encoding.ToLower());
if (!String.IsNullOrEmpty(customEncoder.Value))
{
Type encoderType = Type.GetType("ReadSharp.Encodings." + customEncoder.Value);
if (encoderType != null)
{
correctEncoding = (Encoding)System.Activator.CreateInstance(Type.GetType("ReadSharp.Encodings." + customEncoder.Value));
}
}
}
catch (Exception)
{
// couldn't create instance for whatever reason.
// nothing to do here, as the default encoder will be used in the program.
}
}
}
}
return correctEncoding;
}
}
}
| 28.635514 | 138 | 0.549935 | [
"MIT"
] | JTOne123/ReadSharp.Core | ReadSharp.Core/Encodings/Encoder.cs | 3,066 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Build.Framework
{
/// <summary>
/// The argument for a property initial value set event.
/// </summary>
[Serializable]
public class PropertyInitialValueSetEventArgs : BuildMessageEventArgs
{
/// <summary>
/// Creates an instance of the <see cref="PropertyInitialValueSetEventArgs"/> class.
/// </summary>
public PropertyInitialValueSetEventArgs() { }
/// <summary>
/// Creates an instance of the <see cref="PropertyInitialValueSetEventArgs"/> class.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="propertyValue">The value of the property.</param>
/// <param name="propertySource">The source of the property.</param>
public PropertyInitialValueSetEventArgs(
string propertyName,
string propertyValue,
string propertySource,
string message,
string helpKeyword = null,
string senderName = null,
MessageImportance importance = MessageImportance.Low) : base(message, helpKeyword, senderName, importance)
{
this.PropertyName = propertyName;
this.PropertyValue = propertyValue;
this.PropertySource = propertySource;
}
/// <summary>
/// The name of the property.
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// The value of the property.
/// </summary>
public string PropertyValue { get; set; }
/// <summary>
/// The source of the property.
/// </summary>
public string PropertySource { get; set; }
}
}
| 34.745455 | 118 | 0.607535 | [
"MIT"
] | 3F/msbuild | src/Framework/PropertyInitialValueSetEventArgs.cs | 1,913 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using PowerLib.System.Collections;
using PowerLib.System.IO.Streamed.Typed;
namespace PowerLib.System.Data.SqlTypes.Collections
{
[SqlUserDefinedType(Format.UserDefined, Name = "BitCollection", IsByteOrdered = true, IsFixedLength = false, MaxByteSize = -1)]
public sealed class SqlBooleanCollection : INullable, IBinarySerialize
{
private List<Boolean?> _list;
#region Contructors
public SqlBooleanCollection()
{
_list = null;
}
public SqlBooleanCollection(IEnumerable<Boolean?> coll)
{
_list = coll != null ? new List<Boolean?>(coll) : null;
}
private SqlBooleanCollection(List<Boolean?> list)
{
_list = list;
}
#endregion
#region Properties
public List<Boolean?> List
{
get { return _list; }
set { _list = value; }
}
public static SqlBooleanCollection Null
{
get { return new SqlBooleanCollection(); }
}
public bool IsNull
{
get { return _list == null; }
}
public SqlInt32 Count
{
get { return _list != null ? _list.Count : SqlInt32.Null; }
}
#endregion
#region Methods
public static SqlBooleanCollection Parse(SqlString s)
{
if (s.IsNull)
return Null;
return new SqlBooleanCollection(SqlFormatting.ParseCollection<Boolean?>(s.Value,
t => !t.Equals(SqlFormatting.NullText, StringComparison.InvariantCultureIgnoreCase) ? SqlBoolean.Parse(t).Value : default(Boolean?)));
}
public override String ToString()
{
return SqlFormatting.Format(_list, t => (t.HasValue ? new SqlBoolean(t.Value) : SqlBoolean.Null).ToString());
}
[SqlMethod(IsMutator = true)]
public void Clear()
{
_list.Clear();
}
[SqlMethod(IsMutator = true)]
public void AddItem(SqlBoolean value)
{
_list.Add(value.IsNull ? default(Boolean?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void InsertItem(SqlInt32 index, SqlBoolean value)
{
_list.Insert(index.IsNull ? _list.Count : index.Value, value.IsNull ? default(Boolean?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void RemoveItem(SqlBoolean value)
{
_list.Remove(value.IsNull ? default(Boolean?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void RemoveAt(SqlInt32 index)
{
if (index.IsNull)
return;
_list.RemoveAt(index.Value);
}
[SqlMethod(IsMutator = true)]
public void SetItem(SqlInt32 index, SqlBoolean value)
{
if (index.IsNull)
return;
_list[index.Value] = value.IsNull ? default(Boolean?) : value.Value;
}
[SqlMethod(IsMutator = true)]
public void AddRange(SqlBooleanCollection coll)
{
if (coll.IsNull)
return;
_list.AddRange(coll._list);
}
[SqlMethod(IsMutator = true)]
public void AddRepeat(SqlBoolean value, SqlInt32 count)
{
if (count.IsNull)
return;
_list.AddRepeat(value.IsNull ? default(Boolean?) : value.Value, count.Value);
}
[SqlMethod(IsMutator = true)]
public void InsertRange(SqlInt32 index, SqlBooleanCollection coll)
{
if (coll.IsNull)
return;
int indexValue = !index.IsNull ? index.Value : _list.Count;
_list.InsertRange(indexValue, coll._list);
}
[SqlMethod(IsMutator = true)]
public void InsertRepeat(SqlInt32 index, SqlBoolean value, SqlInt32 count)
{
if (count.IsNull)
return;
int indexValue = !index.IsNull ? index.Value : _list.Count;
_list.InsertRepeat(indexValue, value.IsNull ? default(Boolean?) : value.Value, count.Value);
}
[SqlMethod(IsMutator = true)]
public void SetRange(SqlInt32 index, SqlBooleanCollection range)
{
if (range.IsNull)
return;
int indexValue = index.IsNull ? _list.Count - Comparable.Min(_list.Count, range._list.Count) : index.Value;
_list.SetRange(indexValue, range.List);
}
[SqlMethod(IsMutator = true)]
public void SetRepeat(SqlInt32 index, SqlBoolean value, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
_list.SetRepeat(indexValue, value.IsNull ? default(Boolean?) : value.Value, countValue);
}
[SqlMethod(IsMutator = true)]
public void RemoveRange(SqlInt32 index, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
_list.RemoveRange(indexValue, countValue);
}
[SqlMethod]
public SqlBoolean GetItem(SqlInt32 index)
{
return !index.IsNull && _list[index.Value].HasValue ? _list[index.Value].Value : SqlBoolean.Null;
}
[SqlMethod]
public SqlBooleanCollection GetRange(SqlInt32 index, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
return new SqlBooleanCollection(_list.GetRange(indexValue, countValue));
}
[SqlMethod]
public SqlBooleanArray ToArray()
{
return new SqlBooleanArray(_list);
}
#endregion
#region Operators
public static implicit operator byte[] (SqlBooleanCollection coll)
{
using (var ms = new MemoryStream())
using (var sc = new NulBooleanStreamedCollection(ms, SizeEncoding.B4, coll._list, true, false))
return ms.ToArray();
}
public static explicit operator SqlBooleanCollection(byte[] buffer)
{
using (var ms = new MemoryStream(buffer))
using (var sc = new NulBooleanStreamedCollection(ms, true, false))
return new SqlBooleanCollection(sc.ToList());
}
#endregion
#region IBinarySerialize implementation
public void Read(BinaryReader rd)
{
using (var sc = new NulBooleanStreamedCollection(rd.BaseStream, true, false))
_list = sc.ToList();
}
public void Write(BinaryWriter wr)
{
using (var ms = new MemoryStream())
using (var sc = new NulBooleanStreamedCollection(ms, SizeEncoding.B4, _list, true, false))
wr.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
#endregion
}
}
| 27.924051 | 142 | 0.656392 | [
"MIT"
] | vaseug/PowerLib | PowerLib.System.Data.SqlTypes/Collections/SqlBooleanCollection.cs | 6,620 | 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 Snowflake.Data.Core {
using System;
/// <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", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class ErrorMessages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ErrorMessages() {
}
/// <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("Snowflake.Data.Core.ErrorMessages", typeof(ErrorMessages).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 Column index {0} is out of bound of valid index..
/// </summary>
internal static string COLUMN_INDEX_OUT_OF_BOUND {
get {
return ResourceManager.GetString("COLUMN_INDEX_OUT_OF_BOUND", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data reader has already been closed..
/// </summary>
internal static string DATA_READER_ALREADY_CLOSED {
get {
return ResourceManager.GetString("DATA_READER_ALREADY_CLOSED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Snowflake Internal Error: {0}.
/// </summary>
internal static string INTERNAL_ERROR {
get {
return ResourceManager.GetString("INTERNAL_ERROR", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Connection string is invalid: {0}.
/// </summary>
internal static string INVALID_CONNECTION_STRING {
get {
return ResourceManager.GetString("INVALID_CONNECTION_STRING", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to convert data {0} from type {0} to type {1}..
/// </summary>
internal static string INVALID_DATA_CONVERSION {
get {
return ResourceManager.GetString("INVALID_DATA_CONVERSION", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Required property {0} is not provided..
/// </summary>
internal static string MISSING_CONNECTION_PROPERTY {
get {
return ResourceManager.GetString("MISSING_CONNECTION_PROPERTY", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Query has been cancelled..
/// </summary>
internal static string QUERY_CANCELLED {
get {
return ResourceManager.GetString("QUERY_CANCELLED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Request reach its timeout..
/// </summary>
internal static string REQUEST_TIMEOUT {
get {
return ResourceManager.GetString("REQUEST_TIMEOUT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Another query is already running against this statement..
/// </summary>
internal static string STATEMENT_ALREADY_RUNNING_QUERY {
get {
return ResourceManager.GetString("STATEMENT_ALREADY_RUNNING_QUERY", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Feature is not supported. .
/// </summary>
internal static string UNSUPPORTED_FEATURE {
get {
return ResourceManager.GetString("UNSUPPORTED_FEATURE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to "Could not read RSA private key {0} : {1}.".
/// </summary>
internal static string JWT_ERROR_READING_PK
{
get
{
return ResourceManager.GetString("JWT_ERROR_READING_PK", resourceCulture);
}
}
}
}
| 40.484848 | 183 | 0.564371 | [
"Apache-2.0"
] | BatNiy/snowflake-connector-net | Snowflake.Data/Core/ErrorMessages.Designer.cs | 6,682 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Wims.Common.Entity;
namespace ChinaTtlWifi.NewEntity
{
[Serializable]
public class TestCase : BaseEntity
{
[Description("测试例名称")]
public string Name { get; set; }
[Description("测试例编号")]
public string Code { get; set; }
[Description("测试例描述")]
public string Desc { get; set; }
private string status = TestStatus.测试未开始;
[Description("测试状态")]
public string Status
{
get { return status; }
set { status = value; }
}
private string assign = EquipmentStatus.未指定;
[Description("是否指定设备")]
public string Assign
{
get { return assign; }
set { assign = value; }
}
public List<double> LimitList { get; set; }
public LinkedList<Step> StepList { get; set; }
public List<TestLog> LogList { get; set; }
}
}
| 24.714286 | 55 | 0.542389 | [
"Apache-2.0"
] | wardensky/wardensky-demo | csharp/ChinaTtlWifi/ChinaTtlWifi.NewEntity/TestCase.cs | 1,106 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Network
{
/// <summary> A Class representing a HubVirtualNetworkConnection along with the instance operations that can be performed on it. </summary>
public partial class HubVirtualNetworkConnection : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="HubVirtualNetworkConnection"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string virtualHubName, string connectionName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _hubVirtualNetworkConnectionClientDiagnostics;
private readonly HubVirtualNetworkConnectionsRestOperations _hubVirtualNetworkConnectionRestClient;
private readonly HubVirtualNetworkConnectionData _data;
/// <summary> Initializes a new instance of the <see cref="HubVirtualNetworkConnection"/> class for mocking. </summary>
protected HubVirtualNetworkConnection()
{
}
/// <summary> Initializes a new instance of the <see cref = "HubVirtualNetworkConnection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal HubVirtualNetworkConnection(ArmClient client, HubVirtualNetworkConnectionData data) : this(client, new ResourceIdentifier(data.Id))
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="HubVirtualNetworkConnection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal HubVirtualNetworkConnection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_hubVirtualNetworkConnectionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(ResourceType, out string hubVirtualNetworkConnectionApiVersion);
_hubVirtualNetworkConnectionRestClient = new HubVirtualNetworkConnectionsRestOperations(_hubVirtualNetworkConnectionClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, hubVirtualNetworkConnectionApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Network/virtualHubs/hubVirtualNetworkConnections";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual HubVirtualNetworkConnectionData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Retrieves the details of a HubVirtualNetworkConnection. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<HubVirtualNetworkConnection>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _hubVirtualNetworkConnectionClientDiagnostics.CreateScope("HubVirtualNetworkConnection.Get");
scope.Start();
try
{
var response = await _hubVirtualNetworkConnectionRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _hubVirtualNetworkConnectionClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new HubVirtualNetworkConnection(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Retrieves the details of a HubVirtualNetworkConnection. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<HubVirtualNetworkConnection> Get(CancellationToken cancellationToken = default)
{
using var scope = _hubVirtualNetworkConnectionClientDiagnostics.CreateScope("HubVirtualNetworkConnection.Get");
scope.Start();
try
{
var response = _hubVirtualNetworkConnectionRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _hubVirtualNetworkConnectionClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new HubVirtualNetworkConnection(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a HubVirtualNetworkConnection. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<ArmOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _hubVirtualNetworkConnectionClientDiagnostics.CreateScope("HubVirtualNetworkConnection.Delete");
scope.Start();
try
{
var response = await _hubVirtualNetworkConnectionRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new NetworkArmOperation(_hubVirtualNetworkConnectionClientDiagnostics, Pipeline, _hubVirtualNetworkConnectionRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a HubVirtualNetworkConnection. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _hubVirtualNetworkConnectionClientDiagnostics.CreateScope("HubVirtualNetworkConnection.Delete");
scope.Start();
try
{
var response = _hubVirtualNetworkConnectionRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new NetworkArmOperation(_hubVirtualNetworkConnectionClientDiagnostics, Pipeline, _hubVirtualNetworkConnectionRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 54.517647 | 290 | 0.685801 | [
"MIT"
] | vidai-msft/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/HubVirtualNetworkConnection.cs | 9,268 | C# |
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace MaterialDesignThemes.Wpf
{
[TemplateVisualState(GroupName = DirectionGroupName, Name = NoneStateName)]
[TemplateVisualState(GroupName = DirectionGroupName, Name = AscendingStateName)]
[TemplateVisualState(GroupName = DirectionGroupName, Name = DescendingStateName)]
public class ListSortDirectionIndicator : Control
{
public const string DirectionGroupName = "Direction";
public const string NoneStateName = "None";
public const string AscendingStateName = "Ascending";
public const string DescendingStateName = "Descending";
static ListSortDirectionIndicator()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ListSortDirectionIndicator), new FrameworkPropertyMetadata(typeof(ListSortDirectionIndicator)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
GotoVisualState(true, ListSortDirection);
}
public static readonly DependencyProperty ListSortDirectionProperty = DependencyProperty.Register(
nameof(ListSortDirection), typeof (ListSortDirection?), typeof (ListSortDirectionIndicator), new PropertyMetadata(default(ListSortDirection?), ListSortDirectionPropertyChangedCallback));
private static void ListSortDirectionPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var indicator = (ListSortDirectionIndicator) dependencyObject;
indicator.GotoVisualState(true, indicator.ListSortDirection);
indicator.IsNeutral = !indicator.ListSortDirection.HasValue;
}
public ListSortDirection? ListSortDirection
{
get { return (ListSortDirection?) GetValue(ListSortDirectionProperty); }
set { SetValue(ListSortDirectionProperty, value); }
}
private static readonly DependencyPropertyKey IsNeutralPropertyKey =
DependencyProperty.RegisterReadOnly(
"IsNeutral", typeof (bool), typeof (ListSortDirectionIndicator),
new PropertyMetadata(true));
public static readonly DependencyProperty IsNeutralProperty =
IsNeutralPropertyKey.DependencyProperty;
public bool IsNeutral
{
get { return (bool) GetValue(IsNeutralProperty); }
private set { SetValue(IsNeutralPropertyKey, value); }
}
private void GotoVisualState(bool useTransitions, ListSortDirection? direction)
{
var stateName = direction.HasValue
? (direction.Value == System.ComponentModel.ListSortDirection.Ascending
? AscendingStateName
: DescendingStateName)
: NoneStateName;
VisualStateManager.GoToState(this, stateName, useTransitions);
}
}
} | 43.380282 | 199 | 0.680844 | [
"MIT"
] | Alex4me/MDSerialPortHelper | packages/MaterialDesignThemes.2.6.0/src/net45/ListSortDirectionIndicator.cs | 3,080 | C# |
namespace Dawn
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JetBrains.Annotations;
/// <content>Provides preconditions for <see cref="System.Enum" /> arguments.</content>
public static partial class Guard
{
/// <summary>Exposes the enum preconditions.</summary>
/// <typeparam name="T">Type of the enum argument.</typeparam>
/// <param name="argument">The enum argument.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// argument type is not an enum.
/// </param>
/// <returns>A new <see cref="EnumArgumentInfo{T}" />.</returns>
/// <exception cref="ArgumentException"><typeparamref name="T" /> is not an enum.</exception>
[AssertionMethod]
[DebuggerStepThrough]
[Obsolete("Use the enum preconditions directly, e.g. `arg.Defined()` instead of `arg.Enum().Defined()`.")]
public static EnumArgumentInfo<T> Enum<T>(
in this ArgumentInfo<T> argument, Func<T, string> message = null)
where T : struct, IComparable, IFormattable
{
if (!typeof(T).IsEnum())
{
var m = message?.Invoke(argument.Value) ?? Messages.Enum(argument);
throw new ArgumentException(m, argument.Name);
}
return new EnumArgumentInfo<T>(argument);
}
/// <summary>Exposes the nullable enum preconditions.</summary>
/// <typeparam name="T">Type of the enum argument.</typeparam>
/// <param name="argument">The enum argument.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// argument type is not an enum.
/// </param>
/// <returns>A new <see cref="NullableEnumArgumentInfo{T}" />.</returns>
/// <exception cref="ArgumentException"><typeparamref name="T" /> is not an enum.</exception>
[AssertionMethod]
[DebuggerStepThrough]
[Obsolete("Use the enum preconditions directly, e.g. `arg.Defined()` instead of `arg.Enum().Defined()`.")]
public static NullableEnumArgumentInfo<T> Enum<T>(
in this ArgumentInfo<T?> argument, Func<T?, string> message = null)
where T : struct, IComparable, IFormattable
{
if (!typeof(T).IsEnum())
{
var m = message?.Invoke(argument.Value) ?? Messages.Enum(argument);
throw new ArgumentException(m, argument.Name);
}
return new NullableEnumArgumentInfo<T>(argument);
}
/// <summary>Represents a method argument with an enumeration value.</summary>
/// <typeparam name="T">The type of the enum.</typeparam>
[DebuggerStepThrough]
[Obsolete("Use the enum preconditions directly, e.g. `arg.Defined()` instead of `arg.Enum().Defined()`.")]
public readonly struct EnumArgumentInfo<T>
where T : struct, IComparable, IFormattable
{
/// <summary>
/// Initializes a new instance of the <see cref="EnumArgumentInfo{T}" /> struct.
/// </summary>
/// <param name="argument">The original argument.</param>
internal EnumArgumentInfo(ArgumentInfo<T> argument)
=> this.Argument = argument;
/// <summary>Gets the original argument.</summary>
public ArgumentInfo<T> Argument { get; }
/// <summary>Gets the value of an enum argument.</summary>
/// <param name="argument">The argument whose value to return.</param>
/// <returns>The value of <see cref="Argument" />.</returns>
public static implicit operator T(EnumArgumentInfo<T> argument)
=> argument.Argument.Value;
/// <summary>
/// Requires the enum argument to be a defined member of the enum type <typeparamref name="T" />.
/// </summary>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is not a defined member of the enum type <typeparamref name="T" />.
/// </exception>
/// <returns>The current instance.</returns>
[AssertionMethod]
[DebuggerStepThrough]
public EnumArgumentInfo<T> Defined(Func<T, string> message = null)
{
if (!EnumInfo<T>.Values.Contains(this.Argument.Value))
{
var m = message?.Invoke(this.Argument.Value) ?? Messages.EnumDefined(this.Argument);
throw new ArgumentException(m, this.Argument.Name);
}
return this;
}
/// <summary>Requires the enum argument to have none of its bits set.</summary>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value has one or more of its bits set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public EnumArgumentInfo<T> None(Func<T, string> message = null)
{
if (!EqualityComparer<T>.Default.Equals(this.Argument.Value, default))
{
var m = message?.Invoke(this.Argument.Value) ?? Messages.EnumNone(this.Argument);
throw new ArgumentException(m, this.Argument.Name);
}
return this;
}
/// <summary>Requires the enum argument to have at least one of its bits set.</summary>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value has none of its bits set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public EnumArgumentInfo<T> NotNone(Func<T, string> message = null)
{
if (EqualityComparer<T>.Default.Equals(this.Argument.Value, default))
{
var m = message?.Invoke(this.Argument.Value) ?? Messages.EnumNotNone(this.Argument);
throw new ArgumentException(m, this.Argument.Name);
}
return this;
}
/// <summary>Requires the enum argument to have the specified value.</summary>
/// <param name="other">The value to compare the argument value to.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is different than <paramref name="other" />.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public EnumArgumentInfo<T> Equal(T other, Func<T, T, string> message = null)
{
if (!EqualityComparer<T>.Default.Equals(this.Argument.Value, other))
{
var m = message?.Invoke(this.Argument.Value, other) ?? Messages.Equal(this.Argument, other);
throw new ArgumentException(m, this.Argument.Name);
}
return this;
}
/// <summary>
/// Requires the enum argument to have a value is different than the specified value.
/// </summary>
/// <param name="other">The value to compare the argument value to.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is equal to <paramref name="other" />.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public EnumArgumentInfo<T> NotEqual(T other, Func<T, string> message = null)
{
if (EqualityComparer<T>.Default.Equals(this.Argument.Value, other))
{
var m = message?.Invoke(this.Argument.Value) ?? Messages.NotEqual(this.Argument, other);
throw new ArgumentException(m, this.Argument.Name);
}
return this;
}
/// <summary>Requires the enum argument to have the specified flag bits set.</summary>
/// <param name="flag">The flags to check.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> does not have the bits specified in
/// <paramref name="flag" /> set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public EnumArgumentInfo<T> HasFlag(T flag, Func<T, T, string> message = null)
{
if (!EnumInfo<T>.HasFlag(this.Argument.Value, flag))
{
var m = message?.Invoke(this.Argument.Value, flag) ?? Messages.EnumHasFlag(this.Argument, flag);
throw new ArgumentException(m, this.Argument.Name);
}
return this;
}
/// <summary>Requires the enum argument to have the specified flag bits unset.</summary>
/// <param name="flag">The flags to check.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> have the bits specified in <paramref name="flag" /> set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public EnumArgumentInfo<T> DoesNotHaveFlag(T flag, Func<T, T, string> message = null)
{
if (EnumInfo<T>.HasFlag(this.Argument.Value, flag))
{
var m = message?.Invoke(this.Argument.Value, flag) ?? Messages.EnumDoesNotHaveFlag(this.Argument, flag);
throw new ArgumentException(m, this.Argument.Name);
}
return this;
}
}
/// <summary>Represents a method argument with a nullable enumeration value.</summary>
/// <typeparam name="T">The type of the enum.</typeparam>
[Obsolete("Use the enum preconditions directly, e.g. `arg.Defined()` instead of `arg.Enum().Defined()`.")]
public readonly struct NullableEnumArgumentInfo<T>
where T : struct, IComparable, IFormattable
{
/// <summary>
/// Initializes a new instance of the <see cref="NullableEnumArgumentInfo{T}" /> struct.
/// </summary>
/// <param name="argument">The original argument.</param>
internal NullableEnumArgumentInfo(ArgumentInfo<T?> argument)
=> this.Argument = argument;
/// <summary>Gets the original argument.</summary>
public ArgumentInfo<T?> Argument { get; }
/// <summary>Gets the value of a nullable enum argument.</summary>
/// <param name="argument">The argument whose value to return.</param>
/// <returns>The value of <see cref="Argument" />.</returns>
public static implicit operator T? (NullableEnumArgumentInfo<T> argument)
=> argument.Argument.Value;
/// <summary>Requires the nullable enum argument to be <c>null</c>.</summary>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns><see cref="Argument" />.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is not <c>null</c>.
/// </exception>
public ArgumentInfo<T?> Null(Func<T, string> message = null)
{
if (this.Argument.HasValue())
{
var m = message?.Invoke(this.Argument.Value.Value) ?? Messages.Null(this.Argument);
throw new ArgumentException(m, this.Argument.Name);
}
return this.Argument;
}
/// <summary>Requires the nullable enum argument to be not <c>null</c>.</summary>
/// <param name="message">
/// The message of the exception that will be thrown if the precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentNullException">
/// <see cref="Argument" /> value is <c>null</c> and the argument is not modified
/// since it is initialized.
/// </exception>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is <c>null</c> and the argument is modified after
/// its initialization.
/// </exception>
public EnumArgumentInfo<T> NotNull(string message = null)
#pragma warning disable CS0618 // Type or member is obsolete
=> this.Argument.NotNull(message).Enum();
#pragma warning restore CS0618 // Type or member is obsolete
/// <summary>
/// Requires the nullable enum argument to be either a defined member of the enum
/// type <typeparamref name="T" /> or <c>null</c>.
/// </summary>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is not <c>null</c> and is not a defined member of
/// the enum type <typeparamref name="T" />.
/// </exception>
/// <returns>The current instance.</returns>
[AssertionMethod]
[DebuggerStepThrough]
public NullableEnumArgumentInfo<T> Defined(Func<T, string> message = null)
{
if (this.NotNull(out var a))
a.Defined(message);
return this;
}
/// <summary>
/// Requires the nullable enum argument to either have none of its bits set or be <c>null</c>.
/// </summary>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is not <c>null</c> and has one or more of its bits set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public NullableEnumArgumentInfo<T> None(Func<T, string> message = null)
{
if (this.NotNull(out var a))
a.None(message);
return this;
}
/// <summary>Requires the enum argument to have at least one of its bits set.</summary>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is not <c>null</c> and has none of its bits set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public NullableEnumArgumentInfo<T> NotNone(Func<T, string> message = null)
{
if (this.NotNull(out var a))
a.NotNone(message);
return this;
}
/// <summary>
/// Requires the nullable enum argument to either have the specified value or be <c>null</c>.
/// </summary>
/// <param name="other">The value to compare the argument value to.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is not <c>null</c> and is different than <paramref name="other" />.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public NullableEnumArgumentInfo<T> Equal(T other, Func<T, T, string> message = null)
{
if (this.NotNull(out var a))
a.Equal(other, message);
return this;
}
/// <summary>
/// Requires the nullable enum argument to have a value that is either different than
/// the specified value or <c>null</c>.
/// </summary>
/// <param name="other">The value to compare the argument value to.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> value is not <c>null</c> and is equal to <paramref name="other" />.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public NullableEnumArgumentInfo<T> NotEqual(T other, Func<T, string> message = null)
{
if (this.NotNull(out var a))
a.NotEqual(other, message);
return this;
}
/// <summary>
/// Requires the nullable enum argument to either have the specified flag bits set or
/// be <c>null</c>.
/// </summary>
/// <param name="flag">The flags to check.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> is not <c>null</c> and does not have the bits specified
/// in <paramref name="flag" /> set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public NullableEnumArgumentInfo<T> HasFlag(T flag, Func<T, T, string> message = null)
{
if (this.NotNull(out var a))
a.HasFlag(flag, message);
return this;
}
/// <summary>
/// Requires the nullable enum argument to either have the specified flag bits unset
/// or be <c>null</c>.
/// </summary>
/// <param name="flag">The flags to check.</param>
/// <param name="message">
/// The factory to initialize the message of the exception that will be thrown if the
/// precondition is not satisfied.
/// </param>
/// <returns>The current instance.</returns>
/// <exception cref="ArgumentException">
/// <see cref="Argument" /> is not <c>null</c> and have the bits specified in
/// <paramref name="flag" /> set.
/// </exception>
[AssertionMethod]
[DebuggerStepThrough]
public NullableEnumArgumentInfo<T> DoesNotHaveFlag(T flag, Func<T, T, string> message = null)
{
if (this.NotNull(out var a))
a.DoesNotHaveFlag(flag, message);
return this;
}
/// <summary>
/// Initializes an <see cref="EnumArgumentInfo{T}" /> if the <see cref="Argument" />
/// is not <c>null</c>. A return value indicates whether the new argument is created.
/// </summary>
/// <param name="result">
/// The new enum argument, if the <see cref="Argument" /> is not <c>null</c>;
/// otherwise, the uninitialized argument.
/// </param>
/// <returns>
/// <c>true</c>, if the <see cref="Argument" /> is not <c>null</c>; otherwise, <c>false</c>.
/// </returns>
private bool NotNull(out EnumArgumentInfo<T> result)
{
if (this.Argument.Value.HasValue)
{
result = new EnumArgumentInfo<T>(
new ArgumentInfo<T>(
this.Argument.Value.Value,
this.Argument.Name,
this.Argument.Modified,
this.Argument.Secure));
return true;
}
result = default;
return false;
}
}
}
}
| 46.921371 | 124 | 0.532463 | [
"MIT"
] | adamecr/guard | src/Guard.Enums.Legacy.cs | 23,275 | C# |
using System.Collections;
using System.Data;
using Dapper;
using Newtonsoft.Json;
using Npgsql;
using Tools.Tools;
namespace EventStoreBasics;
public class EventStore: IDisposable, IEventStore
{
private readonly NpgsqlConnection databaseConnection;
private readonly IList<ISnapshot> snapshots = new List<ISnapshot>();
private const string Apply = "Apply";
public EventStore(NpgsqlConnection databaseConnection)
{
this.databaseConnection = databaseConnection;
}
public void Init()
{
// See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/
CreateStreamsTable();
CreateEventsTable();
CreateAppendEventFunction();
}
public void AddSnapshot(ISnapshot snapshot)
{
snapshots.Add(snapshot);
}
public bool Store<TStream>(TStream aggregate) where TStream : IAggregate
{
//TODO Add storing snapshot of aggregate
var events = aggregate.DequeueUncommittedEvents();
var initialVersion = aggregate.Version - events.Count();
foreach (var @event in events)
{
AppendEvent<TStream>(aggregate.Id, @event, initialVersion++);
}
return true;
}
public bool AppendEvent<TStream>(Guid streamId, object @event, long? expectedVersion = null)
where TStream : notnull
{
return databaseConnection.QuerySingle<bool>(
"SELECT append_event(@Id, @Data::jsonb, @Type, @StreamId, @StreamType, @ExpectedVersion)",
new
{
Id = Guid.NewGuid(),
Data = JsonConvert.SerializeObject(@event),
Type = @event.GetType().AssemblyQualifiedName,
StreamId = streamId,
StreamType = typeof(TStream).AssemblyQualifiedName,
ExpectedVersion = expectedVersion
},
commandType: CommandType.Text
);
}
public T AggregateStream<T>(Guid streamId, long? atStreamVersion = null, DateTime? atTimestamp = null) where T: notnull
{
var aggregate = (T)Activator.CreateInstance(typeof(T), true)!;
var events = GetEvents(streamId, atStreamVersion, atTimestamp);
var version = 0;
foreach (var @event in events)
{
aggregate.InvokeIfExists(Apply, @event);
aggregate.SetIfExists(nameof(IAggregate.Version), ++version);
}
return aggregate;
}
public StreamState? GetStreamState(Guid streamId)
{
const string getStreamSql =
@"SELECT id, type, version
FROM streams
WHERE id = @streamId";
return databaseConnection
.Query<dynamic>(getStreamSql, new { streamId })
.Select(streamData =>
new StreamState(
streamData.id,
Type.GetType(streamData.type),
streamData.version
))
.SingleOrDefault();
}
public IEnumerable GetEvents(Guid streamId, long? atStreamVersion = null, DateTime? atTimestamp = null)
{
const string getStreamSql =
@"SELECT id, data, stream_id, type, version, created
FROM events
WHERE stream_id = @streamId
AND (@atStreamVersion IS NULL OR version <= @atStreamVersion)
AND (@atTimestamp IS NULL OR created <= @atTimestamp)
ORDER BY version";
return databaseConnection
.Query<dynamic>(getStreamSql, new { streamId, atStreamVersion, atTimestamp })
.Select(@event =>
JsonConvert.DeserializeObject(
@event.data,
Type.GetType(@event.type)
))
.ToList();
}
private void CreateStreamsTable()
{
const string creatStreamsTableSql =
@"CREATE TABLE IF NOT EXISTS streams(
id UUID NOT NULL PRIMARY KEY,
type TEXT NOT NULL,
version BIGINT NOT NULL
);";
databaseConnection.Execute(creatStreamsTableSql);
}
private void CreateEventsTable()
{
const string creatEventsTableSql =
@"CREATE TABLE IF NOT EXISTS events(
id UUID NOT NULL PRIMARY KEY,
data JSONB NOT NULL,
stream_id UUID NOT NULL,
type TEXT NOT NULL,
version BIGINT NOT NULL,
created timestamp with time zone NOT NULL default (now()),
FOREIGN KEY(stream_id) REFERENCES streams(id),
CONSTRAINT events_stream_and_version UNIQUE(stream_id, version)
);";
databaseConnection.Execute(creatEventsTableSql);
}
private void CreateAppendEventFunction()
{
const string appendEventFunctionSql =
@"CREATE OR REPLACE FUNCTION append_event(id uuid, data jsonb, type text, stream_id uuid, stream_type text, expected_stream_version bigint default null) RETURNS boolean
LANGUAGE plpgsql
AS $$
DECLARE
stream_version int;
BEGIN
-- get stream version
SELECT
version INTO stream_version
FROM streams as s
WHERE
s.id = stream_id FOR UPDATE;
-- if stream doesn't exist - create new one with version 0
IF stream_version IS NULL THEN
stream_version := 0;
INSERT INTO streams
(id, type, version)
VALUES
(stream_id, stream_type, stream_version);
END IF;
-- check optimistic concurrency
IF expected_stream_version IS NOT NULL AND stream_version != expected_stream_version THEN
RETURN FALSE;
END IF;
-- increment event_version
stream_version := stream_version + 1;
-- append event
INSERT INTO events
(id, data, stream_id, type, version)
VALUES
(id, data, stream_id, type, stream_version);
-- update stream version
UPDATE streams as s
SET version = stream_version
WHERE
s.id = stream_id;
RETURN TRUE;
END;
$$;";
databaseConnection.Execute(appendEventFunctionSql);
}
public void Dispose()
{
databaseConnection.Dispose();
}
}
| 35.087379 | 180 | 0.526425 | [
"MIT"
] | MaciejWolf/EventSourcing.NetCore | Workshops/BuildYourOwnEventStore/08-Snapshots/EventStore.cs | 7,228 | C# |
namespace Steamworks
{
/// Store an IP and port. IPv6 is always used; IPv4 is represented using
/// "IPv4-mapped" addresses: IPv4 aa.bb.cc.dd => IPv6 ::ffff:aabb:ccdd
/// (RFC 4291 section 2.5.5.2.)
[System.Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SteamNetworkingIPAddr : System.IEquatable<SteamNetworkingIPAddr>
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] m_ipv6;
public ushort m_port; // Host byte order
// Max length of the buffer needed to hold IP formatted using ToString, including '\0'
// ([0123:4567:89ab:cdef:0123:4567:89ab:cdef]:12345)
public const int k_cchMaxString = 48;
// Set everything to zero. E.g. [::]:0
public void Clear() {
NativeMethods.SteamAPI_SteamNetworkingIPAddr_Clear(ref this);
}
// Return true if the IP is ::0. (Doesn't check port.)
public bool IsIPv6AllZeros() {
return NativeMethods.SteamAPI_SteamNetworkingIPAddr_IsIPv6AllZeros(ref this);
}
// Set IPv6 address. IP is interpreted as bytes, so there are no endian issues. (Same as inaddr_in6.) The IP can be a mapped IPv4 address
public void SetIPv6(byte[] ipv6, ushort nPort) {
NativeMethods.SteamAPI_SteamNetworkingIPAddr_SetIPv6(ref this, ipv6, nPort);
}
// Sets to IPv4 mapped address. IP and port are in host byte order.
public void SetIPv4(uint nIP, ushort nPort) {
NativeMethods.SteamAPI_SteamNetworkingIPAddr_SetIPv4(ref this, nIP, nPort);
}
// Return true if IP is mapped IPv4
public bool IsIPv4() {
return NativeMethods.SteamAPI_SteamNetworkingIPAddr_IsIPv4(ref this);
}
// Returns IP in host byte order (e.g. aa.bb.cc.dd as 0xaabbccdd). Returns 0 if IP is not mapped IPv4.
public uint GetIPv4() {
return NativeMethods.SteamAPI_SteamNetworkingIPAddr_GetIPv4(ref this);
}
// Set to the IPv6 localhost address ::1, and the specified port.
public void SetIPv6LocalHost(ushort nPort = 0) {
NativeMethods.SteamAPI_SteamNetworkingIPAddr_SetIPv6LocalHost(ref this, nPort);
}
// Return true if this identity is localhost. (Either IPv6 ::1, or IPv4 127.0.0.1)
public bool IsLocalHost() {
return NativeMethods.SteamAPI_SteamNetworkingIPAddr_IsLocalHost(ref this);
}
/// Print to a string, with or without the port. Mapped IPv4 addresses are printed
/// as dotted decimal (12.34.56.78), otherwise this will print the canonical
/// form according to RFC5952. If you include the port, IPv6 will be surrounded by
/// brackets, e.g. [::1:2]:80. Your buffer should be at least k_cchMaxString bytes
/// to avoid truncation
///
/// See also SteamNetworkingIdentityRender
public void ToString(out string buf, bool bWithPort) {
IntPtr buf2 = Marshal.AllocHGlobal(k_cchMaxString);
NativeMethods.SteamAPI_SteamNetworkingIPAddr_ToString(ref this, buf2, k_cchMaxString, bWithPort);
buf = InteropHelp.PtrToStringUTF8(buf2);
Marshal.FreeHGlobal(buf2);
}
/// Parse an IP address and optional port. If a port is not present, it is set to 0.
/// (This means that you cannot tell if a zero port was explicitly specified.)
public bool ParseString(string pszStr) {
using (var pszStr2 = new InteropHelp.UTF8StringHandle(pszStr)) {
return NativeMethods.SteamAPI_SteamNetworkingIPAddr_ParseString(ref this, pszStr2);
}
}
/// See if two addresses are identical
public bool Equals(SteamNetworkingIPAddr x) {
return NativeMethods.SteamAPI_SteamNetworkingIPAddr_IsEqualTo(ref this, ref x);
}
/// Classify address as FakeIP. This function never returns
/// k_ESteamNetworkingFakeIPType_Invalid.
public ESteamNetworkingFakeIPType GetFakeIPType() {
return NativeMethods.SteamAPI_SteamNetworkingIPAddr_GetFakeIPType(ref this);
}
/// Return true if we are a FakeIP
public bool IsFakeIP() {
return GetFakeIPType() > ESteamNetworkingFakeIPType.k_ESteamNetworkingFakeIPType_NotFake;
}
}
}
#endif // !DISABLESTEAMWORKS
| 39.636364 | 142 | 0.74159 | [
"MIT"
] | LambdaCmplx/Steamworks.NET | CodeGen/templates/custom_types/SteamNetworkingTypes/SteamNetworkingIPAddr.cs | 3,924 | C# |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public static class SaveDataHandler {
static string settingsPath = Application.persistentDataPath + "/settings.rpg";
public static void SaveSettings() {
BinaryFormatter binFormatter = new BinaryFormatter();
FileStream fileStream = new FileStream(settingsPath, FileMode.Create);
binFormatter.Serialize(fileStream, Settings.INSTANCE);
fileStream.Close();
}
public static void LoadSettings() {
}
internal static Settings LoadSettingsAndReturn() {
if (File.Exists(settingsPath)) {
BinaryFormatter binFormatter = new BinaryFormatter();
FileStream fileStream = new FileStream(settingsPath, FileMode.Open);
Settings settings = binFormatter.Deserialize(fileStream) as Settings;
return settings;
} else return Settings.INSTANCE;
}
}
| 26.2 | 79 | 0.777535 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | RyanAnayaMc/rpg-game | Assets/Scripts/MainMenu/SaveDataHandler.cs | 917 | C# |
using SYMB2C.Foundation.DependencyInjection;
namespace SYMB2C.Foundation.Settings.Services
{
[Service(typeof(IReCaptchaSettings))]
public class ReCaptchaSettings : BaseSettings, IReCaptchaSettings
{
public ReCaptchaSettings(ISettingsProvider settingsProvider) : base(settingsProvider)
{
}
public string PrivateKey()
{
return settingsProvider.GetSetting<string>("GoogleCaptchaPrivateKey");
}
public string PublicKey()
{
return settingsProvider.GetSetting<string>("GoogleCaptchaPublicKey");
}
}
} | 25.458333 | 93 | 0.671031 | [
"Unlicense"
] | digitalParkour/SitecoreSYM-AzureB2C | src/Foundation/Settings/website/Services/ReCaptchaSettings.cs | 611 | C# |
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace DCSoft.Writer.Dom
{
/// <summary>PageImageInfoList 的COM接口</summary>
[Guid("26CA71E1-18BD-4532-A9BD-A1111A93F003")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
public interface IPageImageInfoList
{
/// <summary>属性Count</summary>
[DispId(5)]
int Count
{
get;
}
/// <summary>属性Item</summary>
[DispId(6)]
PageImageInfo this[int index]
{
get;
set;
}
/// <summary>方法Add</summary>
[DispId(2)]
void Add(PageImageInfo item);
/// <summary>方法RemoveAt</summary>
[DispId(4)]
void RemoveAt(int index);
}
}
| 18.763158 | 50 | 0.698457 | [
"MIT"
] | h1213159982/HDF | Example/WinForm/Editor/DCWriter/DCSoft.Writer.Cleaned/DCSoft.Writer.Dom/IPageImageInfoList.cs | 735 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MitapV1._0.Core
{
class Student
{
}
}
| 11.727273 | 33 | 0.689922 | [
"MIT"
] | bircan39/Est--Mimarl-kPlatformu | MitapV1.0.Core/Models/Student.cs | 131 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3521
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Ookii.Dialogs.Sample.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.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;
}
}
}
}
| 34.612903 | 150 | 0.582479 | [
"MIT"
] | DanielWJudge/ActiGraphWorkflowApp | OokiiDialogs/src/Ookii.Dialogs.Sample/Properties/Settings.Designer.cs | 1,075 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SharePointPnP.Modernization.Framework.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharePointPnP.Modernization.Framework.Cache;
using SharePointPnP.Modernization.Framework.Publishing;
using SharePointPnP.Modernization.Framework.Telemetry.Observers;
using Microsoft.SharePoint.Client;
using SharePointPnP.Modernization.Framework.Transform;
using Microsoft.SqlServer.Server;
namespace SharePointPnP.Modernization.Framework.Tests.Transform.Mapping
{
[TestClass]
public class UrlMappingTests
{
[TestMethod]
public void UrlMappingFileLoadTest()
{
FileManager fm = new FileManager();
var mapping = fm.LoadUrlMappingFile(@"..\..\Transform\Mapping\urlmapping_sample.csv");
Assert.IsTrue(mapping.Count > 0);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void UrlMappingFileNotFoundTest()
{
FileManager fm = new FileManager();
var mapping = fm.LoadUrlMappingFile(@"..\..\Transform\Mapping\idontexist_sample.csv");
}
[TestMethod]
public void PublishingPageUrlTest()
{
using (var targetClientContext = TestCommon.CreateClientContext("https://capadevtest.sharepoint.com/sites/PnPSauceModern"))
{
using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevSiteUrl")))
{
var pageTransformator = new PublishingPageTransformator(sourceClientContext, targetClientContext);
pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true));
//pageTransformator.RegisterObserver(new MarkdownToSharePointObserver(targetClientContext, includeVerbose: true));
var pages = sourceClientContext.Web.GetPagesFromList("Pages", folder: "News", pageNameStartsWith: "Hot-Off-The-Press");
foreach (var page in pages)
{
PublishingPageTransformationInformation pti = new PublishingPageTransformationInformation(page)
{
// If target page exists, then overwrite it
Overwrite = true,
// Don't log test runs
SkipTelemetry = true,
KeepPageCreationModificationInformation = false,
};
pti.MappingProperties["SummaryLinksToQuickLinks"] = "true";
pti.MappingProperties["UseCommunityScriptEditor"] = "true";
var result = pageTransformator.Transform(pti);
}
pageTransformator.FlushObservers();
}
}
}
[TestMethod]
public void UrlTransformatorRewriteTest_SrcSubSite()
{
var input = "/sites/PnPSauce/en/Pages/The-Cherry-on-the-Cake,-Transforming-to-Modern.aspx";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce/en";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "/sites/PnPSauceModern/sitepages/The-Cherry-on-the-Cake,-Transforming-to-Modern.aspx";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_SrcRoot()
{
var input = "/sites/PnPSauce/Pages/The-Cherry-on-the-Cake,-Transforming-to-Modern.aspx";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "/sites/PnPSauceModern/sitepages/The-Cherry-on-the-Cake,-Transforming-to-Modern.aspx";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_SrcAbs()
{
var input = "https://capadevtest.sharepoint.com/sites/PnPSauce/Pages/The-Cherry-on-the-Cake,-Transforming-to-Modern.aspx";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "https://capadevtest.sharepoint.com/sites/PnPSauceModern/sitepages/The-Cherry-on-the-Cake,-Transforming-to-Modern.aspx";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_SiteOnly()
{
var input = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_SiteOnlyWithSlash()
{
var input = "https://capadevtest.sharepoint.com/sites/PnPSauce/";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "https://capadevtest.sharepoint.com/sites/PnPSauceModern/";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_Doc()
{
var input = "https://capadevtest.sharepoint.com/sites/PnPSauce/Documents/Employee-Handbook.docx";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "https://capadevtest.sharepoint.com/sites/PnPSauceModern/Documents/Employee-Handbook.docx";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_DocSubSite()
{
var input = "/sites/PnPSauce/en/Documents/Employee-Handbook.docx";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce/en";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "/sites/PnPSauceModern/Documents/Employee-Handbook.docx";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_DocFolder()
{
var input = "/sites/PnPSauce/Documents/Folder/Employee-Handbook.docx";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = "/sites/PnPSauceModern/Documents/Folder/Employee-Handbook.docx";
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
[TestMethod]
public void UrlTransformatorRewriteTest_HtmlBody()
{
var input = @"<div data-automation-id=""textBox"" class=""cke_editable rte--read isFluentRTE cke_editableBulletCounterReset cke_editable cke_editableBulletCounterReset rteEmphasis root-305""><p><span></span></p><p style=""margin - left:0; text - align:left; "">Capsaicin is produced by the plant as a defense against mammalian predators and <a title=""Microbe"" class=""mw - redirect"" href=""https://en.wikipedia.org/wiki/Microbe"">microbes</a>, in particular a <a title=""Fusarium"" href=""https://en.wikipedia.org/wiki/Fusarium"">fusarium</a> fungus carried by <a title=""Hemipteran"" class=""mw-redirect""
href=""https://en.wikipedia.org/wiki/Hemipteran"">hemipteran</a><span> insects that attack certain species of chili peppers, according to one study. Peppers increased the quantity of capsaicin in proportion to the damage caused by fungal predation on the plant's seeds. This is <a href=""/sites/PnPSauce/Documents/Employee%20Handbook.docx"">another link</a> to the document.</span></p><span><p style=""margin-left:0;text-align:left;"">Source: https://en.wikipedia.org/wiki/Chili_pepper </p></span><p></p></div>";
var sourceSite = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var sourceWeb = "https://capadevtest.sharepoint.com/sites/PnPSauce";
var targetWeb = "https://capadevtest.sharepoint.com/sites/PnPSauceModern";
var pagesLibrary = "pages";
// Must be relative result
var expected = @"<div data-automation-id=""textBox"" class=""cke_editable rte--read isFluentRTE cke_editableBulletCounterReset cke_editable cke_editableBulletCounterReset rteEmphasis root-305""><p><span></span></p><p style=""margin - left:0; text - align:left; "">Capsaicin is produced by the plant as a defense against mammalian predators and <a title=""Microbe"" class=""mw - redirect"" href=""https://en.wikipedia.org/wiki/Microbe"">microbes</a>, in particular a <a title=""Fusarium"" href=""https://en.wikipedia.org/wiki/Fusarium"">fusarium</a> fungus carried by <a title=""Hemipteran"" class=""mw-redirect""
href=""https://en.wikipedia.org/wiki/Hemipteran"">hemipteran</a><span> insects that attack certain species of chili peppers, according to one study. Peppers increased the quantity of capsaicin in proportion to the damage caused by fungal predation on the plant's seeds. This is <a href=""/sites/PnPSauceModern/Documents/Employee%20Handbook.docx"">another link</a> to the document.</span></p><span><p style=""margin-left:0;text-align:left;"">Source: https://en.wikipedia.org/wiki/Chili_pepper </p></span><p></p></div>"; ;
CommonUrlReWriteTest(input, sourceSite, sourceWeb, targetWeb, pagesLibrary, expected);
}
/// <summary>
/// Common Test for URL Rewriting
/// </summary>
/// <param name="input"></param>
/// <param name="sourceSite"></param>
/// <param name="sourceWeb"></param>
/// <param name="targetWeb"></param>
/// <param name="pagesLibrary"></param>
/// <param name="expected"></param>
public void CommonUrlReWriteTest(string input, string sourceSite, string sourceWeb, string targetWeb, string pagesLibrary, string expected)
{
//Pre-requisite objects
using (var targetClientContext = TestCommon.CreateClientContext("https://capadevtest.sharepoint.com/sites/PnPSauceModern"))
{
using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevSiteUrl")))
{
PublishingPageTransformationInformation pti = new PublishingPageTransformationInformation()
{
// If target page exists, then overwrite it
Overwrite = true,
// Don't log test runs
SkipTelemetry = true,
KeepPageCreationModificationInformation = false,
};
UrlTransformator urlTransform = new UrlTransformator(pti, sourceClientContext, targetClientContext);
var result = urlTransform.ReWriteUrls(input, sourceSite, sourceWeb, targetWeb, pagesLibrary);
Assert.AreEqual(expected, result);
}
}
}
}
}
| 51.849421 | 625 | 0.645022 | [
"MIT"
] | Chipzter/sp-dev-modernization | Tools/SharePoint.Modernization/SharePointPnP.Modernization.Framework.Tests/Transform/Mapping/UrlMappingTests.cs | 13,431 | C# |
// Copyright (c) 2021 EPAM Systems
//
// 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 Epam.FixAntenna.NetCore.Common;
using Epam.FixAntenna.NetCore.Common.ResourceLoading;
using Epam.FixAntenna.NetCore.Configuration;
using Epam.FixAntenna.NetCore.Dictionary;
using Epam.FixAntenna.NetCore.Validation.Entities;
using NUnit.Framework;
namespace Epam.FixAntenna.Dictionary.Tests.Dictionary
{
[TestFixture]
public class DictionaryLoadingTests
{
private readonly DictionaryBuilder _builder = new DictionaryBuilder();
[Test]
public void EmbeddedDictionaryLoaded()
{
Assert.DoesNotThrow(() =>
{
var fix40 = new FixVersionContainer("myfix40_embedded_resource", FixVersion.Fix40,
"Loading/EmbeddedResources/base40.xml");
_builder.BuildDictionary(fix40, false);
});
}
[Test]
public void OutputDictionaryLoaded()
{
Assert.DoesNotThrow(() =>
{
var fix40 = new FixVersionContainer("myfix40_output_resource", FixVersion.Fix40,
"Loading/OutputResources/base40.xml");
_builder.BuildDictionary(fix40, false);
});
}
[Test]
public void OutputDictionaryTakenInsteadOfEmbedded()
{
// Loading/LoadingOrder/base40.xml is embedded resource and is not copied to the output dir
// Loading/LoadingOrder/base40_output.xml is embedded resource and copied to the output dir with the name of base40.xml
// These files have the same path but contain different titles; test checks that output dictionary is taken
var fix40 = new FixVersionContainer("myfix40_loading_order_resource", FixVersion.Fix40,
"Loading/LoadingOrder/base40.xml");
var dictionary = (Fixdic)_builder.BuildDictionary(fix40, false);
Assert.AreEqual("FIX 4.0 Output Resource", dictionary.Title);
}
[Test]
public void DictionaryNotFound()
{
Assert.Throws<ResourceNotFoundException>(() =>
{
var fix40 = new FixVersionContainer("myfix40", FixVersion.Fix40,
"Loading/does_not_exist.xml");
_builder.BuildDictionary(fix40, false);
});
}
}
}
| 33.078947 | 122 | 0.747812 | [
"Apache-2.0"
] | epam/fix-antenna-net-core | Tests/Dictionary.Tests/Dictionary/DictionaryLoadingTests.cs | 2,516 | C# |
using MinecraftMappings.Internal;
using MinecraftMappings.Internal.Textures.Block;
namespace MinecraftMappings.Minecraft.Java.Textures.Block
{
public class IronDoorTop : JavaBlockTexture
{
public IronDoorTop() : base("Iron Door Top")
{
BlendMode = BlendModes.Cutout;
AddVersion("iron_door_top")
.WithDefaultModel<Java.Models.Block.IronDoorTop>();
//.MapsToBedrockBlock<MinecraftMappings.Minecraft.Bedrock.Textures.Block.DoorIronUpper>();
}
}
}
| 29.944444 | 106 | 0.671614 | [
"MIT"
] | null511/MinecraftMappings.NET | MinecraftMappings.NET/Minecraft/Java/Textures/Block/IronDoorTop.cs | 541 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 16.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete.Double.NullableInt32{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Double;
using T_DATA2 =System.Nullable<System.Int32>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__02__VN
public static class TestSet_504__param__02__VN
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002
};//class TestSet_504__param__02__VN
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete.Double.NullableInt32
| 26.043796 | 136 | 0.527466 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/NotEqual/Complete/Double/NullableInt32/TestSet_504__param__02__VN.cs | 3,570 | C# |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BizHawk.Client.Common;
using BizHawk.Common;
using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk
{
public partial class PlayMovie : Form
{
private readonly MainForm _mainForm;
private readonly Config _config;
private readonly GameInfo _game;
private readonly IEmulator _emulator;
private readonly IMovieSession _movieSession;
private readonly PlatformFrameRates _platformFrameRates = new PlatformFrameRates();
private List<IMovie> _movieList = new List<IMovie>();
private bool _sortReverse;
private string _sortedCol;
private bool _sortDetailsReverse;
private string _sortedDetailsCol;
public PlayMovie(
MainForm mainForm,
Config config,
GameInfo game,
IEmulator emulator,
IMovieSession movieSession)
{
_mainForm = mainForm;
_config = config;
_game = game;
_emulator = emulator;
_movieSession = movieSession;
InitializeComponent();
MovieView.RetrieveVirtualItem += MovieView_QueryItemText;
MovieView.VirtualMode = true;
_sortReverse = false;
_sortedCol = "";
_sortDetailsReverse = false;
_sortedDetailsCol = "";
}
private void PlayMovie_Load(object sender, EventArgs e)
{
IncludeSubDirectories.Checked = _config.PlayMovieIncludeSubDir;
MatchHashCheckBox.Checked = _config.PlayMovieMatchHash;
ScanFiles();
PreHighlightMovie();
TurboCheckbox.Checked = _config.TurboSeek;
}
private void MovieView_QueryItemText(object sender, RetrieveVirtualItemEventArgs e)
{
var entry = _movieList[e.ItemIndex];
e.Item = new ListViewItem(entry.Filename);
e.Item.SubItems.Add(entry.SystemID);
e.Item.SubItems.Add(entry.GameName);
e.Item.SubItems.Add(_platformFrameRates.MovieTime(entry).ToString(@"hh\:mm\:ss\.fff"));
}
private void Run()
{
var indices = MovieView.SelectedIndices;
if (indices.Count > 0) // Import file if necessary
{
_mainForm.StartNewMovie(_movieList[MovieView.SelectedIndices[0]], false);
}
}
private int? AddMovieToList(string filename, bool force)
{
using var file = new HawkFile(filename);
if (!file.Exists)
{
return null;
}
var movie = PreLoadMovieFile(file, force);
if (movie == null)
{
return null;
}
int? index;
lock (_movieList)
{
// need to check IsDuplicateOf within the lock
index = IsDuplicateOf(filename);
if (index.HasValue)
{
return index;
}
_movieList.Add(movie);
index = _movieList.Count - 1;
}
_sortReverse = false;
_sortedCol = "";
return index;
}
private int? IsDuplicateOf(string filename)
{
for (var i = 0; i < _movieList.Count; i++)
{
if (_movieList[i].Filename == filename)
{
return i;
}
}
return null;
}
private IMovie PreLoadMovieFile(HawkFile hf, bool force)
{
var movie = MovieService.Get(hf.CanonicalFullPath);
try
{
movie.PreLoadHeaderAndLength(hf);
// Don't do this from browse
if (movie.Hash == _game.Hash
|| _config.PlayMovieMatchHash == false || force)
{
return movie;
}
}
catch (Exception ex)
{
// TODO: inform the user that a movie failed to parse in some way
Console.WriteLine(ex.Message);
}
return null;
}
private void UpdateList()
{
MovieView.Refresh();
MovieCount.Text = $"{_movieList.Count} {(_movieList.Count == 1 ? "movie" : "movies")}";
}
private void PreHighlightMovie()
{
if (_game.IsNullInstance())
{
return;
}
var indices = new List<int>();
// Pull out matching names
for (var i = 0; i < _movieList.Count; i++)
{
if (PathManager.FilesystemSafeName(_game) == _movieList[i].GameName)
{
indices.Add(i);
}
}
if (indices.Count == 0)
{
return;
}
if (indices.Count == 1)
{
HighlightMovie(indices[0]);
return;
}
// Prefer tas files
var tas = new List<int>();
for (var i = 0; i < indices.Count; i++)
{
foreach (var ext in MovieService.MovieExtensions)
{
if (Path.GetExtension(_movieList[indices[i]].Filename)?.ToUpper() == $".{ext}")
{
tas.Add(i);
}
}
}
if (tas.Count == 1)
{
HighlightMovie(tas[0]);
return;
}
if (tas.Count > 1)
{
indices = new List<int>(tas);
}
// Final tie breaker - Last used file
var file = new FileInfo(_movieList[indices[0]].Filename);
var time = file.LastAccessTime;
var mostRecent = indices.First();
for (var i = 1; i < indices.Count; i++)
{
file = new FileInfo(_movieList[indices[0]].Filename);
if (file.LastAccessTime > time)
{
time = file.LastAccessTime;
mostRecent = indices[i];
}
}
HighlightMovie(mostRecent);
}
private void HighlightMovie(int index)
{
MovieView.SelectedIndices.Clear();
MovieView.Items[index].Selected = true;
}
private void ScanFiles()
{
_movieList.Clear();
MovieView.VirtualListSize = 0;
MovieView.Update();
var directory = PathManager.MakeAbsolutePath(_config.PathEntries.MoviesPathFragment, null);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var dpTodo = new Queue<string>();
var fpTodo = new List<string>();
dpTodo.Enqueue(directory);
var ordinals = new Dictionary<string, int>();
while (dpTodo.Count > 0)
{
string dp = dpTodo.Dequeue();
// enqueue subdirectories if appropriate
if (_config.PlayMovieIncludeSubDir)
{
foreach (var subDir in Directory.GetDirectories(dp))
{
dpTodo.Enqueue(subDir);
}
}
// add movies
fpTodo.AddRange(Directory.GetFiles(dp, $"*.{MovieService.DefaultExtension}"));
fpTodo.AddRange(Directory.GetFiles(dp, $"*.{TasMovie.Extension}"));
}
// in parallel, scan each movie
Parallel.For(0, fpTodo.Count, i =>
{
var file = fpTodo[i];
lock (ordinals)
{
ordinals[file] = i;
}
AddMovieToList(file, force: false);
});
// sort by the ordinal key to maintain relatively stable results when rescanning
_movieList.Sort((a, b) => ordinals[a.Filename].CompareTo(ordinals[b.Filename]));
RefreshMovieList();
}
#region Events
#region Movie List
private void RefreshMovieList()
{
MovieView.VirtualListSize = _movieList.Count;
UpdateList();
}
private void MovieView_DragEnter(object sender, DragEventArgs e)
{
e.Set(DragDropEffects.Copy);
}
private void MovieView_DragDrop(object sender, DragEventArgs e)
{
var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (var path in filePaths.Where(path => MovieService.MovieExtensions.Contains(Path.GetExtension(path)?.Replace(".", ""))))
{
AddMovieToList(path, force: true);
}
RefreshMovieList();
}
private void MovieView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
var indexes = MovieView.SelectedIndices;
if (indexes.Count > 0)
{
var copyStr = new StringBuilder();
foreach (int index in indexes)
{
copyStr
.Append(_movieList[index].Filename).Append('\t')
.Append(_movieList[index].SystemID).Append('\t')
.Append(_movieList[index].GameName).Append('\t')
.Append(_platformFrameRates.MovieTime(_movieList[index]).ToString(@"hh\:mm\:ss\.fff"))
.AppendLine();
}
Clipboard.SetDataObject(copyStr.ToString());
}
}
}
private void MovieView_DoubleClick(object sender, EventArgs e)
{
Run();
Close();
}
private void MovieView_ColumnClick(object sender, ColumnClickEventArgs e)
{
var columnName = MovieView.Columns[e.Column].Text;
switch (columnName)
{
case "File":
default:
_movieList = _movieList.OrderBy(x => Path.GetFileName(x.Filename))
.ThenBy(x => x.SystemID)
.ThenBy(x => x.GameName)
.ThenBy(x => x.FrameCount)
.ToList();
break;
case "SysID":
_movieList = _movieList.OrderBy(x => x.SystemID)
.ThenBy(x => Path.GetFileName(x.Filename))
.ThenBy(x => x.GameName)
.ThenBy(x => x.FrameCount)
.ToList();
break;
case "Game":
_movieList = _movieList.OrderBy(x => x.GameName)
.ThenBy(x => Path.GetFileName(x.Filename))
.ThenBy(x => x.SystemID)
.ThenBy(x => x.FrameCount)
.ToList();
break;
case "Length (est.)":
_movieList = _movieList.OrderBy(x => x.FrameCount)
.ThenBy(x => Path.GetFileName(x.Filename))
.ThenBy(x => x.SystemID)
.ThenBy(x => x.GameName)
.ToList();
break;
}
if (_sortedCol == columnName && _sortReverse)
{
_movieList.Reverse();
_sortReverse = false;
}
else
{
_sortReverse = true;
_sortedCol = columnName;
}
MovieView.Refresh();
}
private void MovieView_SelectedIndexChanged(object sender, EventArgs e)
{
toolTip1.SetToolTip(DetailsView, "");
DetailsView.Items.Clear();
if (MovieView.SelectedIndices.Count < 1)
{
OK.Enabled = false;
return;
}
OK.Enabled = true;
var firstIndex = MovieView.SelectedIndices[0];
MovieView.EnsureVisible(firstIndex);
foreach (var kvp in _movieList[firstIndex].HeaderEntries)
{
var item = new ListViewItem(kvp.Key);
item.SubItems.Add(kvp.Value);
switch (kvp.Key)
{
case HeaderKeys.SHA1:
if (kvp.Value != _game.Hash)
{
item.BackColor = Color.Pink;
toolTip1.SetToolTip(DetailsView, $"Current SHA1: {_game.Hash}");
}
break;
case HeaderKeys.EMULATIONVERSION:
if (kvp.Value != VersionInfo.GetEmuVersion())
{
item.BackColor = Color.Yellow;
}
break;
case HeaderKeys.PLATFORM:
// feos: previously it was compared against _game.System, but when the movie is created
// its platform is copied from _emulator.SystemId, see PopulateWithDefaultHeaderValues()
// the problem is that for GameGear and SG100, those mismatch, resulting in false positive here
// I have a patch to make GG and SG appear as platforms in movie header (issue #1246)
// but even with it, for all the old movies, this false positive would have to be worked around anyway
// TODO: actually check header flags like "IsGGMode" and "IsSegaCDMode" (those are never parsed by BizHawk)
if (kvp.Value != _emulator.SystemId)
{
item.BackColor = Color.Pink;
}
break;
}
DetailsView.Items.Add(item);
}
var fpsItem = new ListViewItem("Fps");
fpsItem.SubItems.Add($"{Fps(_movieList[firstIndex]):0.#######}");
DetailsView.Items.Add(fpsItem);
var framesItem = new ListViewItem("Frames");
framesItem.SubItems.Add(_movieList[firstIndex].FrameCount.ToString());
DetailsView.Items.Add(framesItem);
CommentsBtn.Enabled = _movieList[firstIndex].Comments.Any();
SubtitlesBtn.Enabled = _movieList[firstIndex].Subtitles.Any();
}
public double Fps(IMovie movie)
{
var system = movie.HeaderEntries[HeaderKeys.PLATFORM];
var pal = movie.HeaderEntries.ContainsKey(HeaderKeys.PAL)
&& movie.HeaderEntries[HeaderKeys.PAL] == "1";
return new PlatformFrameRates()[system, pal];
}
private void EditMenuItem_Click(object sender, EventArgs e)
{
foreach (var movie in MovieView.SelectedIndices.Cast<int>()
.Select(index => _movieList[index]))
{
System.Diagnostics.Process.Start(movie.Filename);
}
}
#endregion
#region Details
private void DetailsView_ColumnClick(object sender, ColumnClickEventArgs e)
{
var detailsList = new List<MovieDetails>();
for (var i = 0; i < DetailsView.Items.Count; i++)
{
detailsList.Add(new MovieDetails
{
Keys = DetailsView.Items[i].Text,
Values = DetailsView.Items[i].SubItems[1].Text,
BackgroundColor = DetailsView.Items[i].BackColor
});
}
var columnName = DetailsView.Columns[e.Column].Text;
if (_sortedDetailsCol != columnName)
{
_sortDetailsReverse = false;
}
switch (columnName)
{
// Header, Value
case "Header":
if (_sortDetailsReverse)
{
detailsList = detailsList
.OrderByDescending(x => x.Keys)
.ThenBy(x => x.Values).ToList();
}
else
{
detailsList = detailsList
.OrderBy(x => x.Keys)
.ThenBy(x => x.Values).ToList();
}
break;
case "Value":
if (_sortDetailsReverse)
{
detailsList = detailsList
.OrderByDescending(x => x.Values)
.ThenBy(x => x.Keys).ToList();
}
else
{
detailsList = detailsList
.OrderBy(x => x.Values)
.ThenBy(x => x.Keys).ToList();
}
break;
}
DetailsView.Items.Clear();
foreach (var detail in detailsList)
{
var item = new ListViewItem { Text = detail.Keys, BackColor = detail.BackgroundColor };
item.SubItems.Add(detail.Values);
DetailsView.Items.Add(item);
}
_sortedDetailsCol = columnName;
_sortDetailsReverse = !_sortDetailsReverse;
}
private void CommentsBtn_Click(object sender, EventArgs e)
{
var indices = MovieView.SelectedIndices;
if (indices.Count > 0)
{
var form = new EditCommentsForm();
form.GetMovie(_movieList[MovieView.SelectedIndices[0]]);
form.Show();
}
}
private void SubtitlesBtn_Click(object sender, EventArgs e)
{
var indices = MovieView.SelectedIndices;
if (indices.Count > 0)
{
var s = new EditSubtitlesForm { ReadOnly = true };
s.GetMovie(_movieList[MovieView.SelectedIndices[0]]);
s.Show();
}
}
#endregion
#region Misc Widgets
private void BrowseMovies_Click(object sender, EventArgs e)
{
using var ofd = new OpenFileDialog
{
Filter = $"Movie Files (*.{MovieService.DefaultExtension})|*.{MovieService.DefaultExtension}|TAS project Files (*.{TasMovie.Extension})|*.{TasMovie.Extension}|All Files|*.*",
InitialDirectory = PathManager.MakeAbsolutePath(_config.PathEntries.MoviesPathFragment, null)
};
var result = ofd.ShowHawkDialog();
if (result == DialogResult.OK)
{
var file = new FileInfo(ofd.FileName);
if (!file.Exists)
{
return;
}
int? index = AddMovieToList(ofd.FileName, true);
RefreshMovieList();
if (index.HasValue)
{
MovieView.SelectedIndices.Clear();
MovieView.Items[index.Value].Selected = true;
}
}
}
private void Scan_Click(object sender, EventArgs e)
{
ScanFiles();
PreHighlightMovie();
}
private void IncludeSubDirectories_CheckedChanged(object sender, EventArgs e)
{
_config.PlayMovieIncludeSubDir = IncludeSubDirectories.Checked;
ScanFiles();
PreHighlightMovie();
}
private void MatchHashCheckBox_CheckedChanged(object sender, EventArgs e)
{
_config.PlayMovieMatchHash = MatchHashCheckBox.Checked;
ScanFiles();
PreHighlightMovie();
}
private void Ok_Click(object sender, EventArgs e)
{
_config.TurboSeek = TurboCheckbox.Checked;
Run();
_movieSession.ReadOnly = ReadOnlyCheckBox.Checked;
if (StopOnFrameCheckbox.Checked &&
(StopOnFrameTextBox.ToRawInt().HasValue || LastFrameCheckbox.Checked))
{
_mainForm.PauseOnFrame = LastFrameCheckbox.Checked
? _movieSession.Movie.InputLogLength
: StopOnFrameTextBox.ToRawInt();
}
Close();
}
private void Cancel_Click(object sender, EventArgs e)
{
Close();
}
#endregion
private bool _programmaticallyChangingStopFrameCheckbox;
private void StopOnFrameCheckbox_CheckedChanged(object sender, EventArgs e)
{
if (!_programmaticallyChangingStopFrameCheckbox)
{
StopOnFrameTextBox.Focus();
}
}
private void StopOnFrameTextBox_TextChanged_1(object sender, EventArgs e)
{
_programmaticallyChangingStopFrameCheckbox = true;
StopOnFrameCheckbox.Checked = !string.IsNullOrWhiteSpace(StopOnFrameTextBox.Text);
_programmaticallyChangingStopFrameCheckbox = false;
}
private void LastFrameCheckbox_CheckedChanged(object sender, EventArgs e)
{
if (LastFrameCheckbox.Checked)
{
_programmaticallyChangingStopFrameCheckbox = true;
StopOnFrameCheckbox.Checked = true;
_programmaticallyChangingStopFrameCheckbox = false;
}
StopOnFrameTextBox.Enabled = !LastFrameCheckbox.Checked;
}
#endregion
}
}
| 25.403875 | 179 | 0.637393 | [
"MIT"
] | m35/BizHawk | BizHawk.Client.EmuHawk/movie/PlayMovie.cs | 17,048 | C# |
using Approve.RuleCenter;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class audit_XM_xmDetailFrameset : System.Web.UI.Page
{
private RCenter rc = new RCenter();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request["XMBH"] != null && !string.IsNullOrEmpty(Request["XMBH"]))
{
Session["XMBH"] = Request["XMBH"].ToString();
string sql = "select * from JKC_V_viewDetail where XMBH='" + Session["XMBH"] + "'";
DataTable dt = rc.GetTable(sql);
if (dt != null && dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
ShowWindow(row["XMMC"].ToString());
}
else {
ShowWindow(null);
}
}
}
}
private void ShowWindow(string XMMC)
{
string projectName = XMMC;// row["XMMC"].ToString();
ltrAQJDimg.Text = "<img src=\"../images/hp_xmjd_dbl.jpg\" alt=\"安全监督备案\" width=\"12\" height=\"12\" />";
ltrZLJDImg.Text = "<img src=\"../images/hp_xmjd_dbl.jpg\" alt=\"质量监督备案\" width=\"12\" height=\"12\" />";
string SGXKZurl = "../../TempTable/SGXKZ/A2.html";
string GCGHurl = "../../TempTable/GCGH/A2.html";
string YDGHurl = "../../TempTable/YDGH/A2.html";
string XZYJSurl = "../../TempTable/XZYJS/A2.html";
string AQJDBASurl = "../../TempTable/AQJDBA/A2.html";
string JGYSBAurl = "../../TempTable/JGYSBA/A2.html";
string XMBJurl = "../../TempTable/XMBJ/A2.html";
string ZTBXXurl = "../../TempTable/ZTBXX/A2.html";
string ZLJDBAurl = "../../TempTable/ZLJDBA/A2.html";
if (projectName == "荥经县附城乡中心小学灾后重建工程")
{
SGXKZurl = "../../TempTable/SGXKZ/A.html";
GCGHurl = "../../TempTable/GCGH/A.html";
YDGHurl = "../../TempTable/YDGH/A.html";
XZYJSurl = "../../TempTable/XZYJS/A.html";
AQJDBASurl = "../../TempTable/AQJDBA/A.html";
JGYSBAurl = "../../TempTable/JGYSBA/A.html";
XMBJurl = "../../TempTable/XMBJ/A.html";
ZTBXXurl = "../../TempTable/ZTBXX/A.html";
ZLJDBAurl = "../../TempTable/ZLJDBA/A.html";
ltrAQJDimg.Text = " <img src=\"../images/hp_xmjd_ybl.jpg\" alt=\"安全监督备案\" width=\"12\" height=\"12\" />";
ltrZLJDImg.Text = "<img src=\"../images/hp_xmjd_ybl.jpg\" alt=\"质量监督备案\" width=\"12\" height=\"12\" />";
ltrZLJDBA.Text = "<a href='#' onclick=\"ShowWindow('" + ZLJDBAurl + "')\">质量监督备案</a>";
ltrAQJDBA.Text = "<a href='#' onclick=\"ShowWindow('" + AQJDBASurl + "')\">安全监督备案</a>";
}
else {
ltrZLJDBA.Text = "<span style=\"color:#d9e1e4\">质量监督备案</span>";
ltrAQJDBA.Text = "<span style=\"color:#d9e1e4\">安全监督备案</span>";
}
ltrSGXKZ.Text = "<a href='#' onclick=\"ShowWindow('" + SGXKZurl + "')\">施工许可证</a>";
ltrGCGH.Text = "<a href='#' onclick=\"ShowWindow('" + GCGHurl + "')\">工程规划许可证</a>";
ltrYDGH.Text = "<a href='#' onclick=\"ShowWindow('" + YDGHurl + "')\">用地规划许可证</a>";
ltrXZYJS.Text = "<a href='#' onclick=\"ShowWindow('" + XZYJSurl + "')\">选址意见书</a>";
ltrJGYSBA.Text = "<a href='#' onclick=\"ShowWindow('" + JGYSBAurl + "')\">竣工验收备案</a>";
ltrXMBJ.Text = "<a href='#' onclick=\"ShowWindow('" + XMBJurl + "')\">项目报建</a>";
ltrZTBXX.Text = "<a href='#' onclick=\"ShowWindow('" + ZTBXXurl + "')\">招投标备案</a>";
}
} | 48.090909 | 117 | 0.52849 | [
"MIT"
] | coojee2012/pm3 | SurveyDesign/audit/XM/xmDetailFrameset.aspx.cs | 3,911 | C# |
using Invoices.Repositories;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace Invoices.Commands.Handlers
{
public class RemoveInvoiceHandler : IRequestHandler<RemoveInvoiceCommand, RemoveInvoiceCommandResponse>
{
private readonly IInvoiceRepository _invoiceRepository;
public RemoveInvoiceHandler(IInvoiceRepository invoiceRepository)
{
_invoiceRepository = invoiceRepository;
}
public Task<RemoveInvoiceCommandResponse> Handle(RemoveInvoiceCommand request, CancellationToken cancellationToken)
{
RemoveInvoiceCommandResponse response = new RemoveInvoiceCommandResponse
{
Removed = _invoiceRepository.Remove(request.Id)
};
return Task.FromResult(response);
}
}
}
| 31.148148 | 123 | 0.70868 | [
"MIT"
] | kubagdynia/MediatR.NetCore.TestSystem | MediatRTestSystem/Invoices/Commands/Handlers/RemoveInvoiceHandler.cs | 843 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
* https://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.
*/
namespace YAF.Pages.Admin
{
#region Using
using System;
using System.Web.UI.WebControls;
using YAF.Core;
using YAF.Core.Extensions;
using YAF.Core.Model;
using YAF.Core.Utilities;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Types.Models;
using YAF.Utils;
using YAF.Web.Extensions;
#endregion
/// <summary>
/// Admin Page to Edit NNTP Forums
/// </summary>
public partial class NntpForums : AdminPage
{
#region Methods
/// <summary>
/// News the forum click.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void NewForumClick([NotNull] object sender, [NotNull] EventArgs e)
{
this.EditDialog.BindData(null);
BoardContext.Current.PageElements.RegisterJsBlockStartup(
"openModalJs",
JavaScriptBlocks.OpenModalJs("NntpForumEditDialog"));
}
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
if (!this.IsPostBack)
{
this.BindData();
}
}
/// <summary>
/// Creates page links for this page.
/// </summary>
protected override void CreatePageLinks()
{
this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, BuildLink.GetLink(ForumPages.forum));
this.PageLinks.AddLink(
this.GetText("ADMIN_ADMIN", "Administration"),
BuildLink.GetLink(ForumPages.Admin_Admin));
this.PageLinks.AddLink(this.GetText("ADMIN_NNTPFORUMS", "TITLE"), string.Empty);
this.Page.Header.Title =
$"{this.GetText("ADMIN_ADMIN", "Administration")} - {this.GetText("ADMIN_NNTPFORUMS", "TITLE")}";
}
/// <summary>
/// Ranks the list item command.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="e">The <see cref="RepeaterCommandEventArgs"/> instance containing the event data.</param>
protected void RankListItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "edit":
this.EditDialog.BindData(e.CommandArgument.ToType<int>());
BoardContext.Current.PageElements.RegisterJsBlockStartup(
"openModalJs",
JavaScriptBlocks.OpenModalJs("NntpForumEditDialog"));
break;
case "delete":
var forumId = e.CommandArgument.ToType<int>();
this.GetRepository<NntpTopic>().Delete(n => n.NntpForumID == forumId);
this.GetRepository<NntpForum>().Delete(n => n.ID == forumId);
this.BindData();
break;
}
}
/// <summary>
/// The bind data.
/// </summary>
private void BindData()
{
this.RankList.DataSource = this.GetRepository<NntpForum>().NntpForumList(this.PageContext.PageBoardID, null, null, null);
this.DataBind();
}
#endregion
}
} | 35.970149 | 134 | 0.58444 | [
"Apache-2.0"
] | dotnetframeworknewbie/YAFNET | yafsrc/YetAnotherForum.NET/Pages/Admin/NntpForums.ascx.cs | 4,688 | C# |
namespace Renderer.Controls.Base
{
public interface IUpdatable
{
void Update(GameState.GameState state);
}
} | 18.285714 | 47 | 0.679688 | [
"MIT"
] | michal-franc/EmptySpace | src/Renderer/Controls/Base/IUpdatable.cs | 128 | C# |
namespace DotNetty.Codecs.Tests
{
using DotNetty.Buffers;
using DotNetty.Transport.Channels.Embedded;
using Xunit;
public class LengthFieldBasedFrameDecoderTest
{
[Fact]
public void DiscardTooLongFrame1()
{
var buf = Unpooled.Buffer();
buf.WriteInt(32);
for (int i = 0; i < 32; i++)
{
buf.WriteByte(i);
}
buf.WriteInt(1);
buf.WriteByte('a');
EmbeddedChannel channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(16, 0, 4));
Assert.Throws<TooLongFrameException>(() => channel.WriteInbound(buf));
Assert.True(channel.Finish());
var b = channel.ReadInbound<IByteBuffer>();
Assert.Equal(5, b.ReadableBytes);
Assert.Equal(1, b.ReadInt());
Assert.Equal('a', (char)b.ReadByte());
b.Release();
Assert.Null(channel.ReadInbound<IByteBuffer>());
channel.Finish();
}
[Fact]
public void DiscardTooLongFrame2()
{
var buf = Unpooled.Buffer();
buf.WriteInt(32);
for (int i = 0; i < 32; i++)
{
buf.WriteByte(i);
}
buf.WriteInt(1);
buf.WriteByte('a');
EmbeddedChannel channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(16, 0, 4));
Assert.Throws<TooLongFrameException>(() => channel.WriteInbound(buf.ReadRetainedSlice(14)));
Assert.True(channel.WriteInbound(buf.ReadRetainedSlice(buf.ReadableBytes)));
Assert.True(channel.Finish());
var b = channel.ReadInbound<IByteBuffer>();
Assert.Equal(5, b.ReadableBytes);
Assert.Equal(1, b.ReadInt());
Assert.Equal('a', (char)b.ReadByte());
b.Release();
Assert.Null(channel.ReadInbound<IByteBuffer>());
channel.Finish();
buf.Release();
}
}
}
| 31.9375 | 104 | 0.53865 | [
"MIT"
] | cuteant/SpanNetty | test/DotNetty.Codecs.Tests/LengthFieldBasedFrameDecoderTest.cs | 2,046 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Utilities
{
internal interface IWrappedCollection : IList
{
object UnderlyingCollection { get; }
}
internal class CollectionWrapper<T> : ICollection<T>, IWrappedCollection
{
private readonly IList _list;
private readonly ICollection<T> _genericCollection;
private object _syncRoot;
public CollectionWrapper(IList list)
{
ValidationUtils.ArgumentNotNull(list, nameof(list));
if (list is ICollection<T>)
{
_genericCollection = (ICollection<T>)list;
}
else
{
_list = list;
}
}
public CollectionWrapper(ICollection<T> list)
{
ValidationUtils.ArgumentNotNull(list, nameof(list));
_genericCollection = list;
}
public virtual void Add(T item)
{
if (_genericCollection != null)
{
_genericCollection.Add(item);
}
else
{
_list.Add(item);
}
}
public virtual void Clear()
{
if (_genericCollection != null)
{
_genericCollection.Clear();
}
else
{
_list.Clear();
}
}
public virtual bool Contains(T item)
{
if (_genericCollection != null)
{
return _genericCollection.Contains(item);
}
else
{
return _list.Contains(item);
}
}
public virtual void CopyTo(T[] array, int arrayIndex)
{
if (_genericCollection != null)
{
_genericCollection.CopyTo(array, arrayIndex);
}
else
{
_list.CopyTo(array, arrayIndex);
}
}
public virtual int Count
{
get
{
if (_genericCollection != null)
{
return _genericCollection.Count;
}
else
{
return _list.Count;
}
}
}
public virtual bool IsReadOnly
{
get
{
if (_genericCollection != null)
{
return _genericCollection.IsReadOnly;
}
else
{
return _list.IsReadOnly;
}
}
}
public virtual bool Remove(T item)
{
if (_genericCollection != null)
{
return _genericCollection.Remove(item);
}
else
{
bool contains = _list.Contains(item);
if (contains)
{
_list.Remove(item);
}
return contains;
}
}
public virtual IEnumerator<T> GetEnumerator()
{
if (_genericCollection != null)
{
return _genericCollection.GetEnumerator();
}
return _list.Cast<T>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
if (_genericCollection != null)
{
return _genericCollection.GetEnumerator();
}
else
{
return _list.GetEnumerator();
}
}
int IList.Add(object value)
{
VerifyValueType(value);
Add((T)value);
return (Count - 1);
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
return false;
}
int IList.IndexOf(object value)
{
if (_genericCollection != null)
{
throw new InvalidOperationException("Wrapped ICollection<T> does not support IndexOf.");
}
if (IsCompatibleObject(value))
{
return _list.IndexOf((T)value);
}
return -1;
}
void IList.RemoveAt(int index)
{
if (_genericCollection != null)
{
throw new InvalidOperationException("Wrapped ICollection<T> does not support RemoveAt.");
}
_list.RemoveAt(index);
}
void IList.Insert(int index, object value)
{
if (_genericCollection != null)
{
throw new InvalidOperationException("Wrapped ICollection<T> does not support Insert.");
}
VerifyValueType(value);
_list.Insert(index, (T)value);
}
bool IList.IsFixedSize
{
get
{
if (_genericCollection != null)
{
// ICollection<T> only has IsReadOnly
return _genericCollection.IsReadOnly;
}
else
{
return _list.IsFixedSize;
}
}
}
void IList.Remove(object value)
{
if (IsCompatibleObject(value))
{
Remove((T)value);
}
}
object IList.this[int index]
{
get
{
if (_genericCollection != null)
{
throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer.");
}
return _list[index];
}
set
{
if (_genericCollection != null)
{
throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer.");
}
VerifyValueType(value);
_list[index] = (T)value;
}
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
CopyTo((T[])array, arrayIndex);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
private static void VerifyValueType(object value)
{
if (!IsCompatibleObject(value))
{
throw new ArgumentException("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.".FormatWith(CultureInfo.InvariantCulture, value, typeof(T)), nameof(value));
}
}
private static bool IsCompatibleObject(object value)
{
if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T)))))
{
return false;
}
return true;
}
public object UnderlyingCollection
{
get
{
if (_genericCollection != null)
{
return _genericCollection;
}
else
{
return _list;
}
}
}
}
} | 27.048851 | 206 | 0.465314 | [
"Apache-2.0"
] | Leonardo-YXH/tools | mesh_grid/WpfApplication/lib/Source/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs | 9,415 | C# |
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Documents;
namespace Urania.Desktop {
public class WireParameters : INotifyPropertyChanged, IDataErrorInfo {
private decimal? _wd;
private decimal? _od;
private decimal? _id;
private decimal? _ar;
private WireParametersValidator _wireParametersValidator;
public decimal? Wd {
get => _wd;
set {
_wd = value;
OnPropertyChanged(nameof(Wd));
}
}
public decimal? Id {
get => _id;
set {
_id = value;
OnPropertyChanged(nameof(Id));
}
}
public decimal? Od {
get => _od;
set {
_od = value;
OnPropertyChanged(nameof(Od));
}
}
public decimal? Ar {
get => _ar;
set {
_ar = value;
OnPropertyChanged(nameof(Ar));
}
}
public bool IsValid => _wireParametersValidator.Validate(this).IsValid;
public WireParameters() {
_wireParametersValidator = new WireParametersValidator();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public string Error {
get {
var results = _wireParametersValidator.Validate(this);
if (results != null && results.Errors.Any()) {
var errors = string.Join(Environment.NewLine,
results.Errors.Select(x => x.ErrorMessage).ToArray());
return errors;
}
return string.Empty;
}
}
public string this[string columnName] {
get {
var firstOrDefault = _wireParametersValidator.Validate(this).Errors
.FirstOrDefault(a => a.PropertyName == columnName);
if (firstOrDefault != null) {
return firstOrDefault.ErrorMessage;
}
return null;
}
}
}
} | 28.488095 | 83 | 0.51776 | [
"MIT"
] | MossPiglets/Urania | Urania/Urania.Desktop/WireParameters.cs | 2,395 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using BasicApi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Serialization;
namespace BasicApi
{
public class Startup
{
public Startup(IHostingEnvironment hosting)
{
Configuration =
new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.SetBasePath(PlatformServices.Default.Application.ApplicationBasePath)
.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var rsa = new RSACryptoServiceProvider(2048);
var key = new RsaSecurityKey(rsa.ExportParameters(true));
services.AddSingleton(new SigningCredentials(
key,
SecurityAlgorithms.RsaSha256Signature));
services.Configure<JwtBearerOptions>(options =>
{
options.AutomaticAuthenticate = false;
options.AutomaticChallenge = false;
options.TokenValidationParameters.IssuerSigningKey = key;
options.TokenValidationParameters.ValidAudience = "Myself";
options.TokenValidationParameters.ValidIssuer = "BasicApi";
});
services.AddEntityFrameworkSqlServer().AddDbContext<BasicApiContext>(options =>
{
var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
options.UseSqlServer(connectionString);
});
services.AddAuthorization(options =>
{
options.AddPolicy(
"pet-store-reader",
builder => builder
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireClaim("scope", "pet-store-reader"));
options.AddPolicy(
"pet-store-writer",
builder => builder
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireClaim("scope", "pet-store-writer"));
});
services
.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters(json => json.ContractResolver = new CamelCasePropertyNamesContractResolver())
.AddDataAnnotations();
services.AddSingleton<PetRepository>(new PetRepository());
}
public void Configure(IApplicationBuilder app)
{
CreateDatabase(app.ApplicationServices);
app.Use(next => async context =>
{
try
{
await next(context);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
});
app.UseJwtBearerAuthentication();
app.UseMvc();
}
private void CreateDatabase(IServiceProvider services)
{
using (var serviceScope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var dbContext = services.GetRequiredService<BasicApiContext>();
dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();
using (var connection = dbContext.Database.GetDbConnection())
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = File.ReadAllText("seed.sql");
command.ExecuteNonQuery();
}
}
}
public static void Main(string[] args)
{
var application = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://+:5000")
.UseDefaultHostingConfiguration(args)
.UseStartup<Startup>()
.Build();
application.Run();
}
}
}
| 34.432624 | 112 | 0.571988 | [
"Apache-2.0"
] | dnelly/Performance | testapp/BasicApi/Startup.cs | 4,863 | C# |
using System.Collections.Generic;
using System.Xml.Serialization;
#region dynamo
using Autodesk.DesignScript.Runtime;
#endregion
namespace FemDesign.Loads
{
[IsVisibleInDynamoLibrary(false)]
public partial class LoadCombination: EntityBase
{
#region dynamo
/// <summary>Create LoadCombination from a LoadCase or a list of LoadCases.</summary>
/// <remarks>Create</remarks>
/// <param name="name">Name of LoadCombination</param>
/// <param name="type">LoadCombination type. "ultimate_ordinary"/"ultimate_accidental"/"ultimate_seismic"/"serviceability_quasi_permanent"/"serviceability_frequent"/"serviceability_characteristic"</param>
/// <param name="loadCases">LoadCases to include in load combination. Single LoadCase or list of LoadCases. Nested lists are not supported - use flatten.</param>
/// <param name="gammas">Gamma values for respective LoadCase. Single value or list of values. Nested lists are not supported - use flatten.</param>
[IsVisibleInDynamoLibrary(true)]
public static LoadCombination CreateLoadCombination(string name, [DefaultArgument("\"ultimate_ordinary\"")] string type, List<LoadCase> loadCases, List<double> gammas)
{
var _type = FemDesign.GenericClasses.EnumParser.Parse<LoadCombType>(type);
LoadCombination loadCombination = new LoadCombination(name, _type, loadCases, gammas);
return loadCombination;
}
#endregion
}
} | 50 | 212 | 0.719333 | [
"MIT"
] | AmalieRask131/femdesign-api | FemDesign.Dynamo/Dynamo/Loads/LoadCombination.cs | 1,500 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyStik.TimeTable.Data
{
public class ContentChannel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string TokenName { get; set; }
public string Token { get; set; }
public string AccessUrl { get; set; }
public bool ParticipientsOnly { get; set; }
public virtual Activity Activity { get; set; }
}
}
| 22.16129 | 61 | 0.663755 | [
"MIT"
] | AccelerateX-org/NINE | Sources/TimeTable/MyStik.TimeTable.Data/ContentChannel.cs | 689 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawn : MonoBehaviour {
[SerializeField]
private GameObject[] spicyObjects;
void Start ()
{
spawnRandom();
}
public void spawnRandom()
{
int index = Random.Range(0, spicyObjects.Length);
Instantiate(spicyObjects[index], transform.position, Quaternion.identity);
}
}
| 19.666667 | 82 | 0.680387 | [
"MIT"
] | Avodhel/Unity_Learn_Projects | Tetris/Assets/Scripts/Spawn.cs | 415 | C# |
/*
* Copyright 2018 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : SCADA-Communicator Control
* Summary : About form
*
* Author : Mikhail Shiryaev
* Created : 2008
* Modified : 2018
*/
using Scada.UI;
using System;
using System.Diagnostics;
using System.Windows.Forms;
using Utils;
namespace Scada.Comm.Ctrl
{
/// <summary>
/// About form
/// <para>Форма о программе</para>
/// </summary>
public partial class FrmAbout : Form
{
private static FrmAbout frmAbout = null; // форма о программе
private string exeDir; // директория исполняемого файла приложения
private Log errLog; // журнал ошибок приложения
private bool inited; // форма инициализирована
private string linkUrl; // гиперссылка
/// <summary>
/// Конструктор, ограничивающий создание объекта без параметров
/// </summary>
private FrmAbout()
{
InitializeComponent();
inited = false;
linkUrl = "";
}
/// <summary>
/// Отобразить форму о программе
/// </summary>
public static void ShowAbout(string exeDir, Log errLog)
{
if (exeDir == null)
throw new ArgumentNullException("exeDir");
if (errLog == null)
throw new ArgumentNullException("errLog");
if (frmAbout == null)
{
frmAbout = new FrmAbout();
frmAbout.exeDir = exeDir;
frmAbout.errLog = errLog;
}
frmAbout.Init();
frmAbout.ShowDialog();
}
/// <summary>
/// Инициализировать форму
/// </summary>
private void Init()
{
// инициализация формы
if (!inited)
{
inited = true;
// настройка элементов управления в зависимости от локализации
PictureBox activePictureBox;
if (Localization.UseRussian)
{
activePictureBox = pbAboutRu;
pbAboutEn.Visible = false;
lblVersionEn.Visible = false;
lblVersionRu.Text = "Версия " + CommUtils.AppVersion;
}
else
{
activePictureBox = pbAboutEn;
pbAboutRu.Visible = false;
lblVersionRu.Visible = false;
lblVersionEn.Text = "Version " + CommUtils.AppVersion;
}
// изменение родительских элементов для работы прозрачности
lblWebsite.Parent = activePictureBox;
lblVersionRu.Parent = pbAboutRu;
lblVersionEn.Parent = pbAboutEn;
// загрузка изображения и гиперссылки из файлов, если они существуют
bool imgLoaded;
string errMsg;
if (ScadaUiUtils.LoadAboutForm(exeDir, this, activePictureBox, lblWebsite,
out imgLoaded, out linkUrl, out errMsg))
{
if (imgLoaded)
{
lblVersionRu.Visible = false;
lblVersionEn.Visible = false;
}
}
else
{
errLog.WriteAction(errMsg);
ScadaUiUtils.ShowError(errMsg);
}
}
}
private void FrmAbout_Click(object sender, EventArgs e)
{
Close();
}
private void FrmAbout_KeyPress(object sender, KeyPressEventArgs e)
{
Close();
}
private void lblLink_Click(object sender, EventArgs e)
{
if (ScadaUtils.IsValidUrl(linkUrl))
{
Process.Start(linkUrl);
Close();
}
}
}
} | 29.329032 | 90 | 0.526617 | [
"Apache-2.0"
] | Arvid-new/scada | ScadaComm/ScadaComm/ScadaCommCtrl/FrmAbout.cs | 4,952 | C# |
/** Samples.AssetLib.AssetImporter
*/
namespace Samples.AssetLib.AssetImporter
{
/** MenuItem
*/
#if(UNITY_EDITOR)
public class MenuItem
{
/** GetAssetImporterWithAssetsPath
*/
[UnityEditor.MenuItem("サンプル/BlueBack.AssetLib/AssetImporter/GetAssetImporterWithAssetsPath")]
private static void MenuItem_GetAssetImporterWithAssetsPath()
{
//事前処理。
{
BlueBack.AssetLib.Editor.CreateDirectoryWithAssetsPath.Create("Out");
BlueBack.AssetLib.Editor.SaveAssetWithAssetsPath.SaveConverter(UnityEngine.Texture2D.whiteTexture,new BlueBack.AssetLib.PngConverterAssetToBinary(),"Out/test.png");
BlueBack.AssetLib.Editor.RefreshAssetDatabase.Refresh();
}
//GetAssetImporterWithAssetsPath
{
UnityEditor.TextureImporter t_textureimporter = BlueBack.AssetLib.Editor.GetAssetImporterWithAssetsPath.Get<UnityEditor.TextureImporter>("Out/test.png");
UnityEngine.Debug.Log(t_textureimporter.filterMode.ToString());
}
}
}
#endif
}
| 28.470588 | 168 | 0.778926 | [
"MIT"
] | bluebackblue/AssetLib | BlueBackAssetLib/Assets/Samples/BlueBack.AssetLib/000/AssetImporter/Editor/MenuItem.cs | 986 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace SkeletonWpfApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.222222 | 42 | 0.707317 | [
"MIT"
] | massimobonanni/ProjectPragueSamples | SkeletonWpfApp/App.xaml.cs | 330 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
//using MalbersAnimations.Animals;
namespace MalbersAnimations.Controller
{
[CustomPropertyDrawer(typeof(JumpProfile))]
public class JumpProfileDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var name = property.FindPropertyRelative("name");
var VerticalSpeed = property.FindPropertyRelative("VerticalSpeed");
// var fallRay = property.FindPropertyRelative("fallRay");
// var stepHeight = property.FindPropertyRelative("stepHeight");
var JumpLandDistance = property.FindPropertyRelative("JumpLandDistance");
var fallingTime = property.FindPropertyRelative("fallingTime");
var CliffTime = property.FindPropertyRelative("CliffTime");
var CliffLandDistance = property.FindPropertyRelative("CliffLandDistance");
var HeightMultiplier = property.FindPropertyRelative("HeightMultiplier");
var ForwardMultiplier = property.FindPropertyRelative("ForwardMultiplier");
// helpBox.height = helpBox.height * 3;
GUI.Box(position, GUIContent.none, EditorStyles.helpBox);
position.y += 2;
EditorGUI.BeginProperty(position, label, property);
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
var height = EditorGUIUtility.singleLineHeight;
var line = position;
line.x += 4;
line.width -= 8;
line.height = height;
var lineParameter = line;
var foldout = lineParameter;
foldout.width = 10;
foldout.x += 10;
lineParameter.y -= 2;
lineParameter.x += 13;
lineParameter.width -= 10;
lineParameter.height += 5;
//GUI.Label(line, label, EditorStyles.boldLabel);
//line.y += height + 2;
EditorGUIUtility.labelWidth = 16;
property.isExpanded = EditorGUI.Foldout(foldout, property.isExpanded, GUIContent.none);
EditorGUIUtility.labelWidth = 0;
if (name.stringValue == string.Empty) name.stringValue = "NameHere";
var styll = new GUIStyle(EditorStyles.largeLabel);
styll.fontStyle = FontStyle.Bold;
name.stringValue = GUI.TextField(lineParameter, name.stringValue, styll);
if (property.isExpanded)
{
line.y += height + 8;
float Division = line.width / 2;
var lineSplitted = line;
lineSplitted.width = Division + 20;
EditorGUI.PropertyField(lineSplitted, VerticalSpeed, new GUIContent("Vertical Speed", "Root Motion:\nEnable/Disable the Root Motion on the Animator"));
lineSplitted.x += Division + 42;
lineSplitted.width -= 62;
EditorGUIUtility.labelWidth = 65;
EditorGUI.PropertyField(lineSplitted, JumpLandDistance, new GUIContent("Jump Ray", "Ray Length to check if the ground is at the same level of the beginning of the jump and it allows to complete the Jump End Animation"));
EditorGUIUtility.labelWidth = 0;
/////NEW LINE
//line.y += height + 2;
//lineSplitted = line;
//lineSplitted.width = Division + 30;
//EditorGUI.PropertyField(lineSplitted, JumpLandDistance, new GUIContent("Jump Min Distance", "Minimun Distance to Complete the Jump Exit when the Jump is on the Highest Point"));
//lineSplitted.x += Division + 35;
//lineSplitted.width -= 65;
//EditorGUIUtility.labelWidth = 55;
//EditorGUI.PropertyField(lineSplitted, stepHeight, new GUIContent(" Step", "Step Height:\nTerrain minimum difference to be sure the animal will fall"));
//EditorGUIUtility.labelWidth = 0;
///NEW LINE
line.y += height + 2;
lineSplitted = line;
EditorGUI.PropertyField(lineSplitted, fallingTime, new GUIContent("Fall Time", "Animation normalized time to change to fall animation if the ray checks if the animal is falling"));
///NEW LINE
line.y += height + 8;
EditorGUI.PropertyField(line, CliffTime);
line.y += height + 2;
EditorGUI.PropertyField(line, CliffLandDistance);
line.y += height + 8;
EditorGUI.LabelField(line, "Jump Multipliers", EditorStyles.boldLabel);
line.y += height + 2;
lineSplitted = line;
lineSplitted.width = Division + 30;
EditorGUI.PropertyField(lineSplitted, HeightMultiplier, new GUIContent("Height", "Height multiplier for the Jump. Default:1"));
lineSplitted.x += Division + 35;
lineSplitted.width -= 65;
EditorGUIUtility.labelWidth = 55;
EditorGUI.PropertyField(lineSplitted, ForwardMultiplier, new GUIContent("Forward", "Forward multiplier for the Jump. Default:1"));
EditorGUIUtility.labelWidth = 0;
}
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
if (!property.isExpanded) return base.GetPropertyHeight(property, label)+5;
float lines = 8;
return base.GetPropertyHeight(property, label) * lines + (2 * lines) + 5;
}
}
} | 39.646259 | 236 | 0.601064 | [
"MIT"
] | Philipp-sama123/AnimalsParadise | Game/Assets/Malbers Animations/Common/Scripts/Editor/Animal/JumpProfileDrawer.cs | 5,830 | C# |
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ILCompiler.DependencyAnalysisFramework;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
public class ExternSymbolsWithIndirectionImportedNodeProvider : ImportedNodeProvider
{
public override IEETypeNode ImportedEETypeNode(NodeFactory factory, TypeDesc type)
{
return new ImportedEETypeSymbolNode(factory, type);
}
public override ISortableSymbolNode ImportedGCStaticNode(NodeFactory factory, MetadataType type)
{
return new ImportedGCStaticsNode(factory, type);
}
public override ISortableSymbolNode ImportedNonGCStaticNode(NodeFactory factory, MetadataType type)
{
return new ImportedNonGCStaticsNode(factory, type);
}
public override ISortableSymbolNode ImportedThreadStaticOffsetNode(NodeFactory factory, MetadataType type)
{
return new ImportedThreadStaticsOffsetNode(type, factory);
}
public override ISortableSymbolNode ImportedThreadStaticIndexNode(NodeFactory factory, MetadataType type)
{
return new ImportedThreadStaticsIndexNode(factory);
}
public override ISortableSymbolNode ImportedTypeDictionaryNode(NodeFactory factory, TypeDesc type)
{
return new ImportedTypeGenericDictionaryNode(factory, type);
}
public override ISortableSymbolNode ImportedMethodDictionaryNode(NodeFactory factory, MethodDesc method)
{
return new ImportedMethodGenericDictionaryNode(factory, method);
}
public override IMethodNode ImportedMethodCodeNode(NodeFactory factory, MethodDesc method, bool unboxingStub)
{
return new ExternMethodSymbolNode(factory, method, unboxingStub);
}
}
}
| 37.053571 | 117 | 0.726747 | [
"MIT"
] | Dotnet-GitSync-Bot/corert | src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternSymbolsWithIndirectionImportedNodeProvider.cs | 2,077 | C# |
namespace LiveSplit.View
{
partial class SettingsDialog
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsDialog));
this.tplCore = new System.Windows.Forms.TableLayoutPanel();
this.labelRefreshRate = new System.Windows.Forms.Label();
this.labelLogOut = new System.Windows.Forms.Label();
this.btnLogOut = new System.Windows.Forms.Button();
this.grpHotkey = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.chkDeactivateForOtherPrograms = new System.Windows.Forms.CheckBox();
this.labelStartSplit = new System.Windows.Forms.Label();
this.chkGlobalHotkeys = new System.Windows.Forms.CheckBox();
this.chkDoubleTap = new System.Windows.Forms.CheckBox();
this.txtStartSplit = new System.Windows.Forms.TextBox();
this.labelReset = new System.Windows.Forms.Label();
this.labelPause = new System.Windows.Forms.Label();
this.txtReset = new System.Windows.Forms.TextBox();
this.txtPause = new System.Windows.Forms.TextBox();
this.labelSkip = new System.Windows.Forms.Label();
this.labelUndo = new System.Windows.Forms.Label();
this.txtSkip = new System.Windows.Forms.TextBox();
this.txtUndo = new System.Windows.Forms.TextBox();
this.labelToggle = new System.Windows.Forms.Label();
this.txtToggle = new System.Windows.Forms.TextBox();
this.labelSwitchPrevious = new System.Windows.Forms.Label();
this.labelSwitchNext = new System.Windows.Forms.Label();
this.txtSwitchPrevious = new System.Windows.Forms.TextBox();
this.txtSwitchNext = new System.Windows.Forms.TextBox();
this.grpHotkeyProfiles = new System.Windows.Forms.GroupBox();
this.tlpHotkeyProfiles = new System.Windows.Forms.TableLayoutPanel();
this.tlpActiveHotkeyProfile = new System.Windows.Forms.TableLayoutPanel();
this.labelActiveHotkeyProfiles = new System.Windows.Forms.Label();
this.cmbHotkeyProfiles = new System.Windows.Forms.ComboBox();
this.panel1 = new System.Windows.Forms.Panel();
this.btnRemoveProfile = new System.Windows.Forms.Button();
this.btnNewProfile = new System.Windows.Forms.Button();
this.btnRenameProfile = new System.Windows.Forms.Button();
this.panelDelay = new System.Windows.Forms.Panel();
this.labelDelay = new System.Windows.Forms.Label();
this.txtDelay = new System.Windows.Forms.TextBox();
this.cbxRaceViewer = new System.Windows.Forms.ComboBox();
this.labelRaceViewer = new System.Windows.Forms.Label();
this.labelChooseComparisons = new System.Windows.Forms.Label();
this.btnChooseComparisons = new System.Windows.Forms.Button();
this.chkSimpleSOB = new System.Windows.Forms.CheckBox();
this.chkWarnOnReset = new System.Windows.Forms.CheckBox();
this.panelOkCancel = new System.Windows.Forms.Panel();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.panelRefreshRate = new System.Windows.Forms.Panel();
this.txtRefreshRate = new System.Windows.Forms.TextBox();
this.tplCore.SuspendLayout();
this.grpHotkey.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.grpHotkeyProfiles.SuspendLayout();
this.tlpHotkeyProfiles.SuspendLayout();
this.tlpActiveHotkeyProfile.SuspendLayout();
this.panel1.SuspendLayout();
this.panelDelay.SuspendLayout();
this.panelOkCancel.SuspendLayout();
this.panelRefreshRate.SuspendLayout();
this.SuspendLayout();
//
// tplCore
//
this.tplCore.ColumnCount = 2;
this.tplCore.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 184F));
this.tplCore.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tplCore.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tplCore.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tplCore.Controls.Add(this.labelLogOut, 0, 4);
this.tplCore.Controls.Add(this.btnLogOut, 1, 4);
this.tplCore.Controls.Add(this.grpHotkey, 0, 0);
this.tplCore.Controls.Add(this.cbxRaceViewer, 1, 2);
this.tplCore.Controls.Add(this.labelRaceViewer, 0, 2);
this.tplCore.Controls.Add(this.labelChooseComparisons, 0, 3);
this.tplCore.Controls.Add(this.btnChooseComparisons, 1, 3);
this.tplCore.Controls.Add(this.chkSimpleSOB, 0, 1);
this.tplCore.Controls.Add(this.chkWarnOnReset, 1, 1);
this.tplCore.Controls.Add(this.panelOkCancel, 1, 5);
this.tplCore.Controls.Add(this.panelRefreshRate, 0, 5);
this.tplCore.Location = new System.Drawing.Point(7, 7);
this.tplCore.Name = "tplCore";
this.tplCore.RowCount = 6;
this.tplCore.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tplCore.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tplCore.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tplCore.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tplCore.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tplCore.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tplCore.Size = new System.Drawing.Size(380, 544);
this.tplCore.TabIndex = 0;
//
// labelRefreshRate
//
this.labelRefreshRate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelRefreshRate.AutoSize = true;
this.labelRefreshRate.Location = new System.Drawing.Point(3, 9);
this.labelRefreshRate.Name = "labelRefreshRate";
this.labelRefreshRate.Size = new System.Drawing.Size(73, 13);
this.labelRefreshRate.TabIndex = 19;
this.labelRefreshRate.Text = "Refresh Rate:";
//
// labelLogOut
//
this.labelLogOut.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelLogOut.AutoSize = true;
this.labelLogOut.Location = new System.Drawing.Point(3, 493);
this.labelLogOut.Name = "labelLogOut";
this.labelLogOut.Size = new System.Drawing.Size(178, 13);
this.labelLogOut.TabIndex = 10;
this.labelLogOut.Text = "Saved Accounts:";
//
// btnLogOut
//
this.btnLogOut.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.btnLogOut.Location = new System.Drawing.Point(187, 488);
this.btnLogOut.Name = "btnLogOut";
this.btnLogOut.Size = new System.Drawing.Size(190, 23);
this.btnLogOut.TabIndex = 5;
this.btnLogOut.Text = "Log Out of All Accounts";
this.btnLogOut.UseVisualStyleBackColor = true;
this.btnLogOut.Click += new System.EventHandler(this.btnLogOut_Click);
//
// grpHotkey
//
this.grpHotkey.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tplCore.SetColumnSpan(this.grpHotkey, 2);
this.grpHotkey.Controls.Add(this.tableLayoutPanel2);
this.grpHotkey.Location = new System.Drawing.Point(3, 3);
this.grpHotkey.Name = "grpHotkey";
this.grpHotkey.Size = new System.Drawing.Size(374, 392);
this.grpHotkey.TabIndex = 0;
this.grpHotkey.TabStop = false;
this.grpHotkey.Text = "Hotkeys";
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel2.ColumnCount = 2;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 180F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.Controls.Add(this.chkDeactivateForOtherPrograms, 1, 8);
this.tableLayoutPanel2.Controls.Add(this.labelStartSplit, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.chkGlobalHotkeys, 0, 8);
this.tableLayoutPanel2.Controls.Add(this.chkDoubleTap, 0, 9);
this.tableLayoutPanel2.Controls.Add(this.txtStartSplit, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.labelReset, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.labelPause, 0, 4);
this.tableLayoutPanel2.Controls.Add(this.txtReset, 1, 1);
this.tableLayoutPanel2.Controls.Add(this.txtPause, 1, 4);
this.tableLayoutPanel2.Controls.Add(this.labelSkip, 0, 3);
this.tableLayoutPanel2.Controls.Add(this.labelUndo, 0, 2);
this.tableLayoutPanel2.Controls.Add(this.txtSkip, 1, 3);
this.tableLayoutPanel2.Controls.Add(this.txtUndo, 1, 2);
this.tableLayoutPanel2.Controls.Add(this.labelToggle, 0, 7);
this.tableLayoutPanel2.Controls.Add(this.txtToggle, 1, 7);
this.tableLayoutPanel2.Controls.Add(this.labelSwitchPrevious, 0, 5);
this.tableLayoutPanel2.Controls.Add(this.labelSwitchNext, 0, 6);
this.tableLayoutPanel2.Controls.Add(this.txtSwitchPrevious, 1, 5);
this.tableLayoutPanel2.Controls.Add(this.txtSwitchNext, 1, 6);
this.tableLayoutPanel2.Controls.Add(this.grpHotkeyProfiles, 0, 10);
this.tableLayoutPanel2.Controls.Add(this.panelDelay, 1, 9);
this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 11;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 83F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(368, 373);
this.tableLayoutPanel2.TabIndex = 0;
//
// chkDeactivateForOtherPrograms
//
this.chkDeactivateForOtherPrograms.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.chkDeactivateForOtherPrograms.Location = new System.Drawing.Point(187, 238);
this.chkDeactivateForOtherPrograms.Margin = new System.Windows.Forms.Padding(7, 3, 3, 3);
this.chkDeactivateForOtherPrograms.Name = "chkDeactivateForOtherPrograms";
this.chkDeactivateForOtherPrograms.Size = new System.Drawing.Size(178, 17);
this.chkDeactivateForOtherPrograms.TabIndex = 9;
this.chkDeactivateForOtherPrograms.Text = "Deactivate For Other Programs";
this.chkDeactivateForOtherPrograms.UseVisualStyleBackColor = true;
//
// labelStartSplit
//
this.labelStartSplit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelStartSplit.AutoSize = true;
this.labelStartSplit.Location = new System.Drawing.Point(3, 8);
this.labelStartSplit.Name = "labelStartSplit";
this.labelStartSplit.Size = new System.Drawing.Size(174, 13);
this.labelStartSplit.TabIndex = 4;
this.labelStartSplit.Text = "Start / Split:";
//
// chkGlobalHotkeys
//
this.chkGlobalHotkeys.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.chkGlobalHotkeys.Location = new System.Drawing.Point(7, 238);
this.chkGlobalHotkeys.Margin = new System.Windows.Forms.Padding(7, 3, 3, 3);
this.chkGlobalHotkeys.Name = "chkGlobalHotkeys";
this.chkGlobalHotkeys.Size = new System.Drawing.Size(170, 17);
this.chkGlobalHotkeys.TabIndex = 8;
this.chkGlobalHotkeys.Text = "Global Hotkeys";
this.chkGlobalHotkeys.UseVisualStyleBackColor = true;
this.chkGlobalHotkeys.CheckedChanged += new System.EventHandler(this.chkGlobalHotkeys_CheckedChanged);
//
// chkDoubleTap
//
this.chkDoubleTap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.chkDoubleTap.Location = new System.Drawing.Point(7, 267);
this.chkDoubleTap.Margin = new System.Windows.Forms.Padding(7, 3, 3, 3);
this.chkDoubleTap.Name = "chkDoubleTap";
this.chkDoubleTap.Size = new System.Drawing.Size(170, 17);
this.chkDoubleTap.TabIndex = 10;
this.chkDoubleTap.Text = "Double Tap Prevention";
this.chkDoubleTap.UseVisualStyleBackColor = true;
//
// txtStartSplit
//
this.txtStartSplit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtStartSplit.Location = new System.Drawing.Point(183, 4);
this.txtStartSplit.Name = "txtStartSplit";
this.txtStartSplit.ReadOnly = true;
this.txtStartSplit.Size = new System.Drawing.Size(182, 20);
this.txtStartSplit.TabIndex = 0;
this.txtStartSplit.Enter += new System.EventHandler(this.Split_Set_Enter);
//
// labelReset
//
this.labelReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelReset.AutoSize = true;
this.labelReset.Location = new System.Drawing.Point(3, 37);
this.labelReset.Name = "labelReset";
this.labelReset.Size = new System.Drawing.Size(174, 13);
this.labelReset.TabIndex = 5;
this.labelReset.Text = "Reset:";
//
// labelPause
//
this.labelPause.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelPause.AutoSize = true;
this.labelPause.Location = new System.Drawing.Point(3, 124);
this.labelPause.Name = "labelPause";
this.labelPause.Size = new System.Drawing.Size(174, 13);
this.labelPause.TabIndex = 8;
this.labelPause.Text = "Pause:";
//
// txtReset
//
this.txtReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtReset.Location = new System.Drawing.Point(183, 33);
this.txtReset.Name = "txtReset";
this.txtReset.ReadOnly = true;
this.txtReset.Size = new System.Drawing.Size(182, 20);
this.txtReset.TabIndex = 1;
this.txtReset.Enter += new System.EventHandler(this.Reset_Set_Enter);
//
// txtPause
//
this.txtPause.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtPause.Location = new System.Drawing.Point(183, 120);
this.txtPause.Name = "txtPause";
this.txtPause.ReadOnly = true;
this.txtPause.Size = new System.Drawing.Size(182, 20);
this.txtPause.TabIndex = 4;
this.txtPause.Enter += new System.EventHandler(this.Pause_Set_Enter);
//
// labelSkip
//
this.labelSkip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelSkip.AutoSize = true;
this.labelSkip.Location = new System.Drawing.Point(3, 95);
this.labelSkip.Name = "labelSkip";
this.labelSkip.Size = new System.Drawing.Size(174, 13);
this.labelSkip.TabIndex = 6;
this.labelSkip.Text = "Skip Split:";
//
// labelUndo
//
this.labelUndo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelUndo.AutoSize = true;
this.labelUndo.Location = new System.Drawing.Point(3, 66);
this.labelUndo.Name = "labelUndo";
this.labelUndo.Size = new System.Drawing.Size(174, 13);
this.labelUndo.TabIndex = 7;
this.labelUndo.Text = "Undo Split:";
//
// txtSkip
//
this.txtSkip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtSkip.Location = new System.Drawing.Point(183, 91);
this.txtSkip.Name = "txtSkip";
this.txtSkip.ReadOnly = true;
this.txtSkip.Size = new System.Drawing.Size(182, 20);
this.txtSkip.TabIndex = 3;
this.txtSkip.Enter += new System.EventHandler(this.Skip_Set_Enter);
//
// txtUndo
//
this.txtUndo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtUndo.Location = new System.Drawing.Point(183, 62);
this.txtUndo.Name = "txtUndo";
this.txtUndo.ReadOnly = true;
this.txtUndo.Size = new System.Drawing.Size(182, 20);
this.txtUndo.TabIndex = 2;
this.txtUndo.Enter += new System.EventHandler(this.Undo_Set_Enter);
//
// labelToggle
//
this.labelToggle.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelToggle.AutoSize = true;
this.labelToggle.Location = new System.Drawing.Point(3, 211);
this.labelToggle.Name = "labelToggle";
this.labelToggle.Size = new System.Drawing.Size(174, 13);
this.labelToggle.TabIndex = 9;
this.labelToggle.Text = "Toggle Global Hotkeys:";
//
// txtToggle
//
this.txtToggle.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtToggle.Location = new System.Drawing.Point(183, 207);
this.txtToggle.Name = "txtToggle";
this.txtToggle.ReadOnly = true;
this.txtToggle.Size = new System.Drawing.Size(182, 20);
this.txtToggle.TabIndex = 7;
this.txtToggle.Enter += new System.EventHandler(this.Toggle_Set_Enter);
//
// labelSwitchPrevious
//
this.labelSwitchPrevious.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelSwitchPrevious.AutoSize = true;
this.labelSwitchPrevious.Location = new System.Drawing.Point(3, 153);
this.labelSwitchPrevious.Name = "labelSwitchPrevious";
this.labelSwitchPrevious.Size = new System.Drawing.Size(174, 13);
this.labelSwitchPrevious.TabIndex = 10;
this.labelSwitchPrevious.Text = "Switch Comparison (Previous):";
//
// labelSwitchNext
//
this.labelSwitchNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelSwitchNext.AutoSize = true;
this.labelSwitchNext.Location = new System.Drawing.Point(3, 182);
this.labelSwitchNext.Name = "labelSwitchNext";
this.labelSwitchNext.Size = new System.Drawing.Size(174, 13);
this.labelSwitchNext.TabIndex = 12;
this.labelSwitchNext.Text = "Switch Comparison (Next):";
//
// txtSwitchPrevious
//
this.txtSwitchPrevious.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtSwitchPrevious.Location = new System.Drawing.Point(183, 149);
this.txtSwitchPrevious.Name = "txtSwitchPrevious";
this.txtSwitchPrevious.ReadOnly = true;
this.txtSwitchPrevious.Size = new System.Drawing.Size(182, 20);
this.txtSwitchPrevious.TabIndex = 5;
this.txtSwitchPrevious.Enter += new System.EventHandler(this.Switch_Previous_Set_Enter);
//
// txtSwitchNext
//
this.txtSwitchNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.txtSwitchNext.Location = new System.Drawing.Point(183, 178);
this.txtSwitchNext.Name = "txtSwitchNext";
this.txtSwitchNext.ReadOnly = true;
this.txtSwitchNext.Size = new System.Drawing.Size(182, 20);
this.txtSwitchNext.TabIndex = 6;
this.txtSwitchNext.Enter += new System.EventHandler(this.Switch_Next_Set_Enter);
//
// grpHotkeyProfiles
//
this.grpHotkeyProfiles.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel2.SetColumnSpan(this.grpHotkeyProfiles, 2);
this.grpHotkeyProfiles.Controls.Add(this.tlpHotkeyProfiles);
this.grpHotkeyProfiles.Location = new System.Drawing.Point(3, 293);
this.grpHotkeyProfiles.Name = "grpHotkeyProfiles";
this.grpHotkeyProfiles.Size = new System.Drawing.Size(362, 77);
this.grpHotkeyProfiles.TabIndex = 12;
this.grpHotkeyProfiles.TabStop = false;
this.grpHotkeyProfiles.Text = "Hotkey Profiles";
//
// tlpHotkeyProfiles
//
this.tlpHotkeyProfiles.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tlpHotkeyProfiles.ColumnCount = 1;
this.tlpHotkeyProfiles.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tlpHotkeyProfiles.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tlpHotkeyProfiles.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tlpHotkeyProfiles.Controls.Add(this.tlpActiveHotkeyProfile, 0, 0);
this.tlpHotkeyProfiles.Controls.Add(this.panel1, 0, 1);
this.tlpHotkeyProfiles.Location = new System.Drawing.Point(3, 16);
this.tlpHotkeyProfiles.Name = "tlpHotkeyProfiles";
this.tlpHotkeyProfiles.RowCount = 2;
this.tlpHotkeyProfiles.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tlpHotkeyProfiles.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tlpHotkeyProfiles.Size = new System.Drawing.Size(356, 58);
this.tlpHotkeyProfiles.TabIndex = 0;
//
// tlpActiveHotkeyProfile
//
this.tlpActiveHotkeyProfile.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tlpActiveHotkeyProfile.ColumnCount = 2;
this.tlpActiveHotkeyProfile.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tlpActiveHotkeyProfile.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tlpActiveHotkeyProfile.Controls.Add(this.labelActiveHotkeyProfiles, 0, 0);
this.tlpActiveHotkeyProfile.Controls.Add(this.cmbHotkeyProfiles, 1, 0);
this.tlpActiveHotkeyProfile.Location = new System.Drawing.Point(0, 0);
this.tlpActiveHotkeyProfile.Margin = new System.Windows.Forms.Padding(0);
this.tlpActiveHotkeyProfile.Name = "tlpActiveHotkeyProfile";
this.tlpActiveHotkeyProfile.RowCount = 1;
this.tlpActiveHotkeyProfile.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tlpActiveHotkeyProfile.Size = new System.Drawing.Size(356, 29);
this.tlpActiveHotkeyProfile.TabIndex = 0;
//
// labelActiveHotkeyProfiles
//
this.labelActiveHotkeyProfiles.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelActiveHotkeyProfiles.AutoSize = true;
this.labelActiveHotkeyProfiles.Location = new System.Drawing.Point(3, 8);
this.labelActiveHotkeyProfiles.Name = "labelActiveHotkeyProfiles";
this.labelActiveHotkeyProfiles.Size = new System.Drawing.Size(172, 13);
this.labelActiveHotkeyProfiles.TabIndex = 0;
this.labelActiveHotkeyProfiles.Text = "Active Hotkey Profile:";
//
// cmbHotkeyProfiles
//
this.cmbHotkeyProfiles.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.cmbHotkeyProfiles.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbHotkeyProfiles.FormattingEnabled = true;
this.cmbHotkeyProfiles.Location = new System.Drawing.Point(181, 4);
this.cmbHotkeyProfiles.Name = "cmbHotkeyProfiles";
this.cmbHotkeyProfiles.Size = new System.Drawing.Size(172, 21);
this.cmbHotkeyProfiles.TabIndex = 0;
this.cmbHotkeyProfiles.SelectedIndexChanged += new System.EventHandler(this.cmbHotkeyProfiles_SelectedIndexChanged);
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.Controls.Add(this.btnRemoveProfile);
this.panel1.Controls.Add(this.btnNewProfile);
this.panel1.Controls.Add(this.btnRenameProfile);
this.panel1.Location = new System.Drawing.Point(0, 29);
this.panel1.Margin = new System.Windows.Forms.Padding(0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(356, 29);
this.panel1.TabIndex = 1;
//
// btnRemoveProfile
//
this.btnRemoveProfile.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.btnRemoveProfile.Location = new System.Drawing.Point(278, 3);
this.btnRemoveProfile.Name = "btnRemoveProfile";
this.btnRemoveProfile.Size = new System.Drawing.Size(75, 23);
this.btnRemoveProfile.TabIndex = 3;
this.btnRemoveProfile.Text = "Remove";
this.btnRemoveProfile.UseVisualStyleBackColor = true;
this.btnRemoveProfile.Click += new System.EventHandler(this.btnRemoveProfile_Click);
//
// btnNewProfile
//
this.btnNewProfile.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.btnNewProfile.Location = new System.Drawing.Point(116, 3);
this.btnNewProfile.Name = "btnNewProfile";
this.btnNewProfile.Size = new System.Drawing.Size(75, 23);
this.btnNewProfile.TabIndex = 1;
this.btnNewProfile.Text = "New";
this.btnNewProfile.UseVisualStyleBackColor = true;
this.btnNewProfile.Click += new System.EventHandler(this.btnNewProfile_Click);
//
// btnRenameProfile
//
this.btnRenameProfile.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.btnRenameProfile.Location = new System.Drawing.Point(197, 3);
this.btnRenameProfile.Name = "btnRenameProfile";
this.btnRenameProfile.Size = new System.Drawing.Size(75, 23);
this.btnRenameProfile.TabIndex = 2;
this.btnRenameProfile.Text = "Rename";
this.btnRenameProfile.UseVisualStyleBackColor = true;
this.btnRenameProfile.Click += new System.EventHandler(this.btnRenameProfile_Click);
//
// panelDelay
//
this.panelDelay.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panelDelay.Controls.Add(this.labelDelay);
this.panelDelay.Controls.Add(this.txtDelay);
this.panelDelay.Location = new System.Drawing.Point(180, 261);
this.panelDelay.Margin = new System.Windows.Forms.Padding(0);
this.panelDelay.Name = "panelDelay";
this.panelDelay.Size = new System.Drawing.Size(188, 29);
this.panelDelay.TabIndex = 13;
//
// labelDelay
//
this.labelDelay.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.labelDelay.Location = new System.Drawing.Point(3, 7);
this.labelDelay.Name = "labelDelay";
this.labelDelay.Size = new System.Drawing.Size(125, 13);
this.labelDelay.TabIndex = 14;
this.labelDelay.Text = "Hotkey Delay (Seconds):";
//
// txtDelay
//
this.txtDelay.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.txtDelay.Location = new System.Drawing.Point(134, 4);
this.txtDelay.Name = "txtDelay";
this.txtDelay.Size = new System.Drawing.Size(51, 20);
this.txtDelay.TabIndex = 11;
this.txtDelay.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// cbxRaceViewer
//
this.cbxRaceViewer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.cbxRaceViewer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbxRaceViewer.FormattingEnabled = true;
this.cbxRaceViewer.Items.AddRange(new object[] {
"SpeedRunsLive",
"MultiTwitch",
"Kadgar",
"Speedrun.tv"});
this.cbxRaceViewer.Location = new System.Drawing.Point(187, 431);
this.cbxRaceViewer.Name = "cbxRaceViewer";
this.cbxRaceViewer.Size = new System.Drawing.Size(190, 21);
this.cbxRaceViewer.TabIndex = 3;
//
// labelRaceViewer
//
this.labelRaceViewer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelRaceViewer.AutoSize = true;
this.labelRaceViewer.Location = new System.Drawing.Point(3, 435);
this.labelRaceViewer.Name = "labelRaceViewer";
this.labelRaceViewer.Size = new System.Drawing.Size(178, 13);
this.labelRaceViewer.TabIndex = 15;
this.labelRaceViewer.Text = "Race Viewer:";
//
// labelChooseComparisons
//
this.labelChooseComparisons.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.labelChooseComparisons.AutoSize = true;
this.labelChooseComparisons.Location = new System.Drawing.Point(3, 464);
this.labelChooseComparisons.Name = "labelChooseComparisons";
this.labelChooseComparisons.Size = new System.Drawing.Size(178, 13);
this.labelChooseComparisons.TabIndex = 17;
this.labelChooseComparisons.Text = "Active Comparisons:";
//
// btnChooseComparisons
//
this.btnChooseComparisons.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.btnChooseComparisons.Location = new System.Drawing.Point(187, 459);
this.btnChooseComparisons.Name = "btnChooseComparisons";
this.btnChooseComparisons.Size = new System.Drawing.Size(190, 23);
this.btnChooseComparisons.TabIndex = 4;
this.btnChooseComparisons.Text = "Choose Active Comparisons...";
this.btnChooseComparisons.UseVisualStyleBackColor = true;
this.btnChooseComparisons.Click += new System.EventHandler(this.btnChooseComparisons_Click);
//
// chkSimpleSOB
//
this.chkSimpleSOB.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.chkSimpleSOB.AutoSize = true;
this.chkSimpleSOB.Location = new System.Drawing.Point(7, 404);
this.chkSimpleSOB.Margin = new System.Windows.Forms.Padding(7, 3, 3, 3);
this.chkSimpleSOB.Name = "chkSimpleSOB";
this.chkSimpleSOB.Size = new System.Drawing.Size(174, 17);
this.chkSimpleSOB.TabIndex = 1;
this.chkSimpleSOB.Text = "Simple Sum of Best Calculation";
this.chkSimpleSOB.UseVisualStyleBackColor = true;
this.chkSimpleSOB.CheckedChanged += new System.EventHandler(this.chkSimpleSOB_CheckedChanged);
//
// chkWarnOnReset
//
this.chkWarnOnReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.chkWarnOnReset.AutoSize = true;
this.chkWarnOnReset.Location = new System.Drawing.Point(191, 404);
this.chkWarnOnReset.Margin = new System.Windows.Forms.Padding(7, 3, 3, 3);
this.chkWarnOnReset.Name = "chkWarnOnReset";
this.chkWarnOnReset.Size = new System.Drawing.Size(186, 17);
this.chkWarnOnReset.TabIndex = 2;
this.chkWarnOnReset.Text = "Warn On Reset If Better Times";
this.chkWarnOnReset.UseVisualStyleBackColor = true;
//
// panelOkCancel
//
this.panelOkCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panelOkCancel.Controls.Add(this.btnOK);
this.panelOkCancel.Controls.Add(this.btnCancel);
this.panelOkCancel.Location = new System.Drawing.Point(184, 514);
this.panelOkCancel.Margin = new System.Windows.Forms.Padding(0);
this.panelOkCancel.Name = "panelOkCancel";
this.panelOkCancel.Size = new System.Drawing.Size(196, 30);
this.panelOkCancel.TabIndex = 18;
//
// btnOK
//
this.btnOK.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.btnOK.Location = new System.Drawing.Point(35, 4);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 6;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(116, 4);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(77, 23);
this.btnCancel.TabIndex = 7;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// panelRefreshRate
//
this.panelRefreshRate.Controls.Add(this.txtRefreshRate);
this.panelRefreshRate.Controls.Add(this.labelRefreshRate);
this.panelRefreshRate.Location = new System.Drawing.Point(0, 514);
this.panelRefreshRate.Margin = new System.Windows.Forms.Padding(0);
this.panelRefreshRate.Name = "panelRefreshRate";
this.panelRefreshRate.Size = new System.Drawing.Size(184, 30);
this.panelRefreshRate.TabIndex = 19;
//
// txtRefreshRate
//
this.txtRefreshRate.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.txtRefreshRate.Location = new System.Drawing.Point(128, 6);
this.txtRefreshRate.Name = "txtRefreshRate";
this.txtRefreshRate.Size = new System.Drawing.Size(51, 20);
this.txtRefreshRate.TabIndex = 15;
this.txtRefreshRate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// SettingsDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(394, 559);
this.Controls.Add(this.tplCore);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SettingsDialog";
this.Padding = new System.Windows.Forms.Padding(7);
this.Text = "Settings";
this.Load += new System.EventHandler(this.SettingsDialog_Load);
this.tplCore.ResumeLayout(false);
this.tplCore.PerformLayout();
this.grpHotkey.ResumeLayout(false);
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.grpHotkeyProfiles.ResumeLayout(false);
this.tlpHotkeyProfiles.ResumeLayout(false);
this.tlpActiveHotkeyProfile.ResumeLayout(false);
this.tlpActiveHotkeyProfile.PerformLayout();
this.panel1.ResumeLayout(false);
this.panelDelay.ResumeLayout(false);
this.panelDelay.PerformLayout();
this.panelOkCancel.ResumeLayout(false);
this.panelRefreshRate.ResumeLayout(false);
this.panelRefreshRate.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tplCore;
private System.Windows.Forms.TextBox txtStartSplit;
private System.Windows.Forms.TextBox txtReset;
private System.Windows.Forms.TextBox txtSkip;
private System.Windows.Forms.TextBox txtUndo;
private System.Windows.Forms.Label labelUndo;
private System.Windows.Forms.Label labelSkip;
private System.Windows.Forms.Label labelReset;
private System.Windows.Forms.Label labelStartSplit;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.CheckBox chkGlobalHotkeys;
private System.Windows.Forms.Label labelPause;
private System.Windows.Forms.TextBox txtPause;
private System.Windows.Forms.CheckBox chkWarnOnReset;
private System.Windows.Forms.TextBox txtToggle;
private System.Windows.Forms.Label labelToggle;
private System.Windows.Forms.CheckBox chkDoubleTap;
private System.Windows.Forms.GroupBox grpHotkey;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Label labelSwitchPrevious;
private System.Windows.Forms.TextBox txtSwitchPrevious;
private System.Windows.Forms.Label labelSwitchNext;
private System.Windows.Forms.TextBox txtSwitchNext;
private System.Windows.Forms.Label labelDelay;
private System.Windows.Forms.TextBox txtDelay;
private System.Windows.Forms.ComboBox cbxRaceViewer;
private System.Windows.Forms.Label labelRaceViewer;
private System.Windows.Forms.CheckBox chkDeactivateForOtherPrograms;
private System.Windows.Forms.CheckBox chkSimpleSOB;
private System.Windows.Forms.Button btnChooseComparisons;
private System.Windows.Forms.GroupBox grpHotkeyProfiles;
private System.Windows.Forms.TableLayoutPanel tlpHotkeyProfiles;
private System.Windows.Forms.Label labelActiveHotkeyProfiles;
private System.Windows.Forms.ComboBox cmbHotkeyProfiles;
private System.Windows.Forms.Button btnRemoveProfile;
private System.Windows.Forms.Button btnRenameProfile;
private System.Windows.Forms.Button btnNewProfile;
private System.Windows.Forms.Label labelLogOut;
private System.Windows.Forms.Button btnLogOut;
private System.Windows.Forms.Label labelChooseComparisons;
private System.Windows.Forms.Panel panelDelay;
private System.Windows.Forms.Panel panelOkCancel;
private System.Windows.Forms.TableLayoutPanel tlpActiveHotkeyProfile;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label labelRefreshRate;
private System.Windows.Forms.Panel panelRefreshRate;
private System.Windows.Forms.TextBox txtRefreshRate;
}
} | 61.464146 | 178 | 0.647943 | [
"MIT"
] | ROMaster2/LiveSpl | LiveSplit/LiveSplit.View/View/SettingsDialog.Designer.cs | 47,145 | C# |
// Copyright (c) 2016 The Decred developers
// Licensed under the ISC license. See LICENSE file in the project root for full license information.
using Paymetheus.Decred;
using Paymetheus.Decred.Util;
using Paymetheus.Decred.Wallet;
using Paymetheus.Framework;
using Paymetheus.Rpc;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Threading.Tasks;
using System.Windows;
namespace Paymetheus.ViewModels
{
public sealed class SynchronizerViewModel : ViewModelBase
{
private SynchronizerViewModel(Process walletProcess, WalletClient client)
{
WalletRpcProcess = walletProcess;
WalletRpcClient = client;
Messenger.RegisterSingleton<SynchronizerViewModel>(OnMessageReceived);
}
public Process WalletRpcProcess { get; }
public WalletClient WalletRpcClient { get; }
public Mutex<Wallet> WalletMutex { get; private set; }
public static async Task<SynchronizerViewModel> Startup(BlockChainIdentity activeNetwork, string walletAppDataDir,
bool searchPath, string extraArgs)
{
if (activeNetwork == null)
throw new ArgumentNullException(nameof(activeNetwork));
if (walletAppDataDir == null)
throw new ArgumentNullException(nameof(walletAppDataDir));
if (extraArgs == null)
throw new ArgumentNullException(nameof(extraArgs));
// Begin the asynchronous reading of the certificate before starting the wallet
// process. This uses filesystem events to know when to begin reading the certificate,
// and if there is too much delay between wallet writing the cert and this process
// beginning to observe the change, the event may never fire and the cert won't be read.
var rootCertificateTask = TransportSecurity.ReadModifiedCertificateAsync(walletAppDataDir);
string walletProcessPath = null;
if (!searchPath)
{
walletProcessPath = Portability.ExecutableInstallationPath(
Environment.OSVersion.Platform, AssemblyResources.Organization, WalletProcess.ProcessName);
}
KillLeftoverWalletProcess(activeNetwork);
var walletProcess = WalletProcess.Start(activeNetwork, walletAppDataDir, walletProcessPath, extraArgs);
WalletClient walletClient;
try
{
var listenAddress = WalletProcess.RpcListenAddress("localhost", activeNetwork);
var rootCertificate = await rootCertificateTask;
walletClient = await WalletClient.ConnectAsync(listenAddress, rootCertificate);
}
catch (Exception)
{
if (walletProcess.HasExited)
{
throw new Exception("Wallet process closed unexpectedly");
}
walletProcess.KillIfExecuting();
throw;
}
return new SynchronizerViewModel(walletProcess, walletClient);
}
private static void KillLeftoverWalletProcess(BlockChainIdentity intendedNetwork)
{
var v4ListenAddress = WalletProcess.RpcListenAddress("127.0.0.1", intendedNetwork);
var walletProcesses = new ManagementObjectSearcher($"SELECT * FROM Win32_Process WHERE Name='{WalletProcess.ProcessName}.exe'").Get();
foreach (var walletProcessInfo in walletProcesses)
{
var commandLine = (string)walletProcessInfo["CommandLine"];
if (commandLine.Contains($" --experimentalrpclisten={v4ListenAddress}"))
{
var process = Process.GetProcessById((int)(uint)walletProcessInfo["ProcessID"]);
process.KillIfExecuting();
break;
}
}
}
private Amount _totalBalance;
public Amount TotalBalance
{
get { return _totalBalance; }
set { _totalBalance = value; RaisePropertyChanged(); }
}
private int _transactionCount;
public int TransactionCount
{
get { return _transactionCount; }
set { _transactionCount = value; RaisePropertyChanged(); }
}
private int _syncedBlockHeight;
public int SyncedBlockHeight
{
get { return _syncedBlockHeight; }
set { _syncedBlockHeight = value; RaisePropertyChanged(); }
}
private Amount _ticketPrice;
public Amount TicketPrice
{
get { return _ticketPrice; }
set { _ticketPrice = value; RaisePropertyChanged(); }
}
private int _blocksUntilTicketPriceRetarget;
public int BlocksUntilTicketPriceRetarget
{
get { return _blocksUntilTicketPriceRetarget; }
set { _blocksUntilTicketPriceRetarget = value; RaisePropertyChanged(); }
}
public ObservableCollection<AccountViewModel> Accounts { get; } = new ObservableCollection<AccountViewModel>();
private AccountViewModel _selectedAccount;
public AccountViewModel SelectedAccount
{
get { return _selectedAccount; }
set { _selectedAccount = value; RaisePropertyChanged(); }
}
public IEnumerable<string> AccountNames => Accounts.Select(a => a.AccountProperties.AccountName);
private async void OnMessageReceived(IViewModelMessage message)
{
var startupWizardFinishedMessage = message as StartupWizardFinishedMessage;
if (startupWizardFinishedMessage != null)
{
await OnWalletProcessOpenedWallet();
}
}
private async Task OnWalletProcessOpenedWallet()
{
try
{
var sdiff = await WalletRpcClient.TicketPriceAsync();
await App.Current.Dispatcher.InvokeAsync(() => TicketPrice = sdiff);
var syncingWallet = await WalletRpcClient.Synchronize(OnWalletChangesProcessed);
WalletMutex = syncingWallet.Item1;
using (var guard = await WalletMutex.LockAsync())
{
OnSyncedWallet(guard.Instance);
}
var syncTask = syncingWallet.Item2;
await syncTask;
}
catch (ConnectTimeoutException)
{
MessageBox.Show("Unable to connect to wallet");
}
catch (Grpc.Core.RpcException) when (WalletRpcClient.CancellationRequested) { }
catch (Exception ex)
{
var ae = ex as AggregateException;
if (ae != null)
{
Exception inner;
if (ae.TryUnwrap(out inner))
ex = inner;
}
await HandleSyncFault(ex);
}
finally
{
if (WalletMutex != null)
{
using (var walletGuard = await WalletMutex.LockAsync())
{
walletGuard.Instance.ChangesProcessed -= OnWalletChangesProcessed;
}
}
var shell = (ShellViewModel)ViewModelLocator.ShellViewModel;
shell.StartupWizardVisible = true;
}
}
private static async Task HandleSyncFault(Exception ex)
{
string message;
var shutdown = false;
// Sync task ended. Decide whether to restart the task and sync a
// fresh wallet, or error out with an explanation.
if (ErrorHandling.IsTransient(ex))
{
// This includes network issues reaching the wallet, like disconnects.
message = $"A temporary error occurred, but reconnecting is not implemented.\n\n{ex}";
shutdown = true; // TODO: implement reconnect logic.
}
else if (ErrorHandling.IsServerError(ex))
{
message = $"The wallet failed to service a request.\n\n{ex}";
}
else if (ErrorHandling.IsClientError(ex))
{
message = $"A client request could not be serviced.\n\n{ex}";
}
else
{
message = $"An unexpected error occurred:\n\n{ex}";
shutdown = true;
}
await App.Current.Dispatcher.InvokeAsync(() =>
{
MessageBox.Show(message, "Error");
if (shutdown)
App.Current.Shutdown();
});
}
private void OnWalletChangesProcessed(object sender, Wallet.ChangesProcessedEventArgs e)
{
var wallet = (Wallet)sender;
var currentHeight = e.NewChainTip?.Height ?? SyncedBlockHeight;
// TODO: The OverviewViewModel should probably connect to this event. This could be
// done after the wallet is synced.
var overviewViewModel = ViewModelLocator.OverviewViewModel as OverviewViewModel;
if (overviewViewModel != null)
{
var movedTxViewModels = overviewViewModel.RecentTransactions
.Where(txvm => e.MovedTransactions.ContainsKey(txvm.TxHash))
.Select(txvm => Tuple.Create(txvm, e.MovedTransactions[txvm.TxHash]));
var newTxViewModels = e.AddedTransactions.Select(tx => new TransactionViewModel(wallet, tx.Item1, tx.Item2)).ToList();
foreach (var movedTx in movedTxViewModels)
{
var txvm = movedTx.Item1;
var location = movedTx.Item2;
txvm.Location = location;
txvm.Depth = BlockChain.Depth(currentHeight, location);
}
App.Current.Dispatcher.Invoke(() =>
{
foreach (var txvm in newTxViewModels)
{
overviewViewModel.RecentTransactions.Insert(0, txvm);
}
while (overviewViewModel.RecentTransactions.Count > 10)
{
overviewViewModel.RecentTransactions.RemoveAt(10);
}
});
}
// TODO: same.. in fact these tx viewmodels should be reused so changes don't need to be recalculated.
// It would be a good idea for this synchronzier viewmodel to manage these and hand them out to other
// viewmodels for sorting and organization.
var transactionHistoryViewModel = ViewModelLocator.TransactionHistoryViewModel as TransactionHistoryViewModel;
if (transactionHistoryViewModel != null)
{
foreach (var tx in transactionHistoryViewModel.Transactions)
{
var txvm = tx.Transaction;
BlockIdentity newLocation;
if (e.MovedTransactions.TryGetValue(txvm.TxHash, out newLocation))
{
txvm.Location = newLocation;
}
txvm.Depth = BlockChain.Depth(currentHeight, txvm.Location);
}
transactionHistoryViewModel.AppendNewTransactions(wallet, e.AddedTransactions);
}
foreach (var modifiedAccount in e.ModifiedAccountProperties)
{
var accountNumber = checked((int)modifiedAccount.Key.AccountNumber);
var accountProperties = modifiedAccount.Value;
if (accountNumber < Accounts.Count)
{
Accounts[accountNumber].AccountProperties = accountProperties;
}
}
// TODO: this would be better if all new accounts were a field in the event message.
var newAccounts = e.ModifiedAccountProperties.
Where(kvp => kvp.Key.AccountNumber >= Accounts.Count && kvp.Key.AccountNumber != Wallet.ImportedAccountNumber).
OrderBy(kvp => kvp.Key.AccountNumber);
foreach (var modifiedAccount in newAccounts)
{
var accountNumber = checked((int)modifiedAccount.Key.AccountNumber);
var accountProperties = modifiedAccount.Value;
// TODO: This is very inefficient because it recalculates balances of every account, for each new account.
var accountBalance = wallet.CalculateBalances(2)[accountNumber];
var accountViewModel = new AccountViewModel(modifiedAccount.Key, accountProperties, accountBalance);
App.Current.Dispatcher.Invoke(() => Accounts.Add(accountViewModel));
}
if (e.NewChainTip != null)
{
SyncedBlockHeight = e.NewChainTip.Value.Height;
var oldRetarget = BlocksUntilTicketPriceRetarget;
BlocksUntilTicketPriceRetarget = BlockChain.BlocksUntilTicketPriceRetarget(SyncedBlockHeight, wallet.ActiveChain);
if (BlocksUntilTicketPriceRetarget > oldRetarget)
{
Task.Run(async () =>
{
var sdiff = await WalletRpcClient.TicketPriceAsync();
await App.Current.Dispatcher.InvokeAsync(() => TicketPrice = sdiff);
}).ContinueWith(t =>
{
if (t.Exception != null)
MessageBox.Show(t.Exception.InnerException.Message, "Error querying ticket price");
});
}
}
if (e.AddedTransactions.Count != 0 || e.RemovedTransactions.Count != 0 || e.NewChainTip != null)
{
TotalBalance = wallet.TotalBalance;
TransactionCount += e.AddedTransactions.Count - e.RemovedTransactions.Count;
var balances = wallet.CalculateBalances(2); // TODO: don't hardcode confs
for (var i = 0; i < balances.Length; i++)
{
Accounts[i].Balances = balances[i];
}
}
}
private void OnSyncedWallet(Wallet wallet)
{
var accountBalances = wallet.CalculateBalances(2); // TODO: configurable confirmations
var accountViewModels = wallet.EnumerateAccounts()
.Zip(accountBalances, (a, bals) => new AccountViewModel(a.Item1, a.Item2, bals))
.ToList();
var txSet = wallet.RecentTransactions;
var recentTx = txSet.UnminedTransactions
.Select(x => new TransactionViewModel(wallet, x.Value, BlockIdentity.Unmined))
.Concat(txSet.MinedTransactions.ReverseList().SelectMany(b => b.Transactions.Select(tx => new TransactionViewModel(wallet, tx, b.Identity))))
.Take(10);
var overviewViewModel = (OverviewViewModel)SingletonViewModelLocator.Resolve("Overview");
App.Current.Dispatcher.Invoke(() =>
{
foreach (var vm in accountViewModels)
Accounts.Add(vm);
foreach (var tx in recentTx)
overviewViewModel.RecentTransactions.Add(tx);
});
TotalBalance = wallet.TotalBalance;
TransactionCount = txSet.TransactionCount();
SyncedBlockHeight = wallet.ChainTip.Height;
SelectedAccount = accountViewModels[0];
BlocksUntilTicketPriceRetarget = BlockChain.BlocksUntilTicketPriceRetarget(SyncedBlockHeight, wallet.ActiveChain);
RaisePropertyChanged(nameof(TotalBalance));
RaisePropertyChanged(nameof(AccountNames));
overviewViewModel.AccountsCount = accountViewModels.Count();
var shell = (ShellViewModel)ViewModelLocator.ShellViewModel;
shell.StartupWizardVisible = false;
}
}
}
| 42.597911 | 157 | 0.581796 | [
"ISC"
] | decred/Paymetheus | Paymetheus/ViewModels/SynchronizerViewModel.cs | 16,317 | C# |
using System;
using Xunit;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PalindromeDetector.ConsoleApp;
namespace UnitTestPalindrome
{
public class UnitTest1
{
[Fact]
private int Ispalindrome()
{
Assert(Ispalindrome(string1, or, string2);
Assert(Ispalindrome("racecaR"());
}
}
public class VSTests
{
[TestMethod]
public void PalindromeDetectorCanUnderstandPalindrome()
{
bool expected = true;
bool actual;
actual = Program.IsPalindromeNonRecursive("racecaR");
Assert.(expected, actual);
}
[TestMethod]
public void PalindromeDetecotryCanUnderstandNonPalindrome()
{
bool notExpected = true;
actual = Program.IsPalindromeNonRecursive("123abccba123");
Assert.(notExpected, actual);
}
}
}
| 23.948718 | 70 | 0.59636 | [
"MIT"
] | 2002-feb24-net/brendan-code | UnitTestPalindrome/UnitTest1.cs | 934 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using ICSharpCode.PythonBinding;
using ICSharpCode.SharpDevelop.Dom;
using NUnit.Framework;
namespace PythonBinding.Tests.Expressions
{
/// <summary>
/// Tests the PythonExpressionFinder can find the System.Console
/// expression in various forms.
/// </summary>
[TestFixture]
public class FindSystemConsoleExpressionTestFixture
{
PythonExpressionFinder expressionFinder;
[TestFixtureSetUp]
public void SetUpFixture()
{
expressionFinder = new PythonExpressionFinder();
}
[Test]
public void NullTextExpression()
{
ExpressionResult result = expressionFinder.FindExpression(null, 10);
Assert.IsNull(result.Expression);
}
/// <summary>
/// The offset passed to the expression finder points to the
/// last character in the expression. In the string below this is the
/// 'e'.
/// </summary>
[Test]
public void SystemConsoleOnly()
{
string text = "System.Console";
AssertSystemConsoleExpressionFound(text, text.Length);
}
[Test]
public void MultipleLinesContainingCarriageReturnAndNewLine()
{
string text = "\r\nSystem.Console";
AssertSystemConsoleExpressionFound(text, text.Length);
}
[Test]
public void MultipleLinesContainingCarriageReturn()
{
string text = "\rSystem.Console";
AssertSystemConsoleExpressionFound(text, text.Length);
}
/// <summary>
/// Should find an empty string since the offset is after the carriage return character.
/// </summary>
[Test]
public void CarriageReturnAfterLastCharacter()
{
string text = "System.Console\r";
ExpressionResult result = expressionFinder.FindExpression(text, text.Length);
Assert.AreEqual(String.Empty, result.Expression);
}
[Test]
public void SpaceBeforeSystemConsoleText()
{
string text = " System.Console";
AssertSystemConsoleExpressionFound(text, text.Length);
}
[Test]
public void TabBeforeSystemConsoleText()
{
string text = "\tSystem.Console";
AssertSystemConsoleExpressionFound(text, text.Length);
}
[Test]
public void EmptyString()
{
string text = String.Empty;
ExpressionResult result = expressionFinder.FindExpression(text, 0);
Assert.IsNull(result.Expression);
}
[Test]
public void OffsetTooSmall()
{
string text = "a";
ExpressionResult result = expressionFinder.FindExpression(text, 0);
Assert.IsNull(result.Expression);
}
[Test]
public void OffsetTooLarge()
{
string text = "a";
ExpressionResult result = expressionFinder.FindExpression(text, text.Length + 1);
Assert.IsNull(result.Expression);
}
[Test]
public void NegativeOffset()
{
string text = "a";
ExpressionResult result = expressionFinder.FindExpression(text, -1);
Assert.IsNull(result.Expression);
}
/// <summary>
/// Checks that the System.Console expression is found in the
/// text before the specified offset.
/// </summary>
void AssertSystemConsoleExpressionFound(string text, int offset)
{
ExpressionResult result = expressionFinder.FindExpression(text, offset);
Assert.AreEqual("System.Console", result.Expression);
}
}
}
| 25.953125 | 103 | 0.718844 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | src/AddIns/BackendBindings/Python/PythonBinding/Test/Expressions/FindSystemConsoleExpressionTestFixture.cs | 3,324 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
namespace Nest
{
public class DeleteRepositoryResponse : AcknowledgedResponseBase { }
}
| 32.777778 | 76 | 0.783051 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | src/Nest/Modules/SnapshotAndRestore/Repositories/DeleteRepository/DeleteRepositoryResponse.cs | 295 | C# |
using Volo.Abp.DependencyInjection;
namespace AElf
{
public class DividendSmartContractAddressNameProvider : ISmartContractAddressNameProvider, ISingletonDependency
{
public static readonly Hash Name = Hash.FromString("AElf.ContractNames.Dividend");
public Hash ContractName => Name;
}
} | 31.6 | 115 | 0.762658 | [
"MIT"
] | quangdo3112/AElf | src/AElf.Kernel/DividendSmartContractAddressNameProvider.cs | 316 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MassTransit;
using Microsoft.Extensions.Options;
using Cynosura.Core.Messaging;
namespace Cynosura.Messaging
{
public class MassTransitService : IMessagingService
{
private readonly MassTransitServiceOptions _options;
private readonly IBusControl _bus;
public MassTransitService(
IBusControl bus,
IOptions<MassTransitServiceOptions> options)
{
_bus = bus;
_options = options.Value;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await _bus.StartAsync(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return _bus.StopAsync(cancellationToken);
}
private string GetAddress(string queue) =>
$"{_options.ConnectionUrl}/{queue}";
private async Task<ISendEndpoint> GetEndpoint(string queue)
{
var endpoint = await _bus.GetSendEndpoint(new Uri(GetAddress(queue)));
return endpoint;
}
public async Task PublishAsync<T>(T message) where T : class
{
await _bus.Publish(message);
}
public async Task PublishAsync<T>(T message, TimeSpan timeToLive) where T : class
{
await _bus.Publish(message, x => x.TimeToLive = timeToLive);
}
public async Task SendAsync<T>(string queue, T message) where T : class
{
var endpoint = await GetEndpoint(queue);
await endpoint.Send(message);
}
}
} | 28.666667 | 89 | 0.630233 | [
"MIT"
] | CynosuraPlatform/Cynosura | Cynosura.Messaging/MassTransitService.cs | 1,720 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Storage.V1
{
/// <summary>
/// Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported.
/// </summary>
public class CSIPowerMaxSpecDriverCommonEnvsValueFromResourceFieldRefArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Container name: required for volumes, optional for env vars
/// </summary>
[Input("containerName")]
public Input<string>? ContainerName { get; set; }
/// <summary>
/// Specifies the output format of the exposed resources, defaults to "1"
/// </summary>
[Input("divisor")]
public Input<Pulumi.Kubernetes.Types.Inputs.Storage.V1.CSIPowerMaxSpecDriverCommonEnvsValueFromResourceFieldRefDivisorArgs>? Divisor { get; set; }
/// <summary>
/// Required: resource to select
/// </summary>
[Input("resource", required: true)]
public Input<string> Resource { get; set; } = null!;
public CSIPowerMaxSpecDriverCommonEnvsValueFromResourceFieldRefArgs()
{
}
}
}
| 37.097561 | 220 | 0.675871 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/dell-csi-operator/dotnet/Kubernetes/Crds/Operators/DellCsiOperator/Storage/V1/Inputs/CSIPowerMaxSpecDriverCommonEnvsValueFromResourceFieldRefArgs.cs | 1,521 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Quinto Avance
namespace Almacen.BL
{
public class SolicitudAduana
{
public int Id { get; set; }
public int ClienteId { get; set; }
public Clientes Cliente { get; set; }
public DateTime Fecha { get; set; }
public double Total { get; set; }
public bool Activo { get; set; }
public List<DetalleSolicitud> ListaDetalleSolicitud { get; set; }
public SolicitudAduana()
{
Activo = true;
Fecha = DateTime.Now;
ListaDetalleSolicitud = new List<DetalleSolicitud>();
}
}
public class DetalleSolicitud
{
public int Id { get; set; }
public int SolicitudId { get; set; }
public SolicitudAduana Solicitud { get; set; }
public int ServicioId { get; set; }
public Servicio Servicio { get; set; }
public int Cantidad { get; set; }
public int Estadia { get; set; }
public string Espacio { get; set; }
public int Anchura { get; set; }
public int Altura { get; set; }
public double Precio { get; set; }
public double Total { get; set; }
}
}
| 27.6875 | 74 | 0.565839 | [
"MIT"
] | Jhonny96-Flores/quieropizza | ALMACEN/Almacen.BL/SolicitudAduana.cs | 1,331 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.CSharp.RuntimeBinder;
namespace Dapper
{
/// <summary>
/// Main class for Dapper.SimpleCRUD extensions
/// </summary>
public static partial class SimpleCRUD
{
static SimpleCRUD()
{
SetDialect(_dialect);
}
private static Dialect _dialect = Dialect.SQLServer;
private static string _encapsulation;
private static string _getIdentitySql;
private static string _getPagedListSql;
private static readonly ConcurrentDictionary<Type, string> TableNames = new ConcurrentDictionary<Type, string>();
private static readonly ConcurrentDictionary<string, string> ColumnNames = new ConcurrentDictionary<string, string>();
private static readonly ConcurrentDictionary<string, string> StringBuilderCacheDict = new ConcurrentDictionary<string, string>();
private static bool StringBuilderCacheEnabled = true;
private static ITableNameResolver _tableNameResolver = new TableNameResolver();
private static IColumnNameResolver _columnNameResolver = new ColumnNameResolver();
/// <summary>
/// Append a Cached version of a strinbBuilderAction result based on a cacheKey
/// </summary>
/// <param name="sb"></param>
/// <param name="cacheKey"></param>
/// <param name="stringBuilderAction"></param>
private static void StringBuilderCache(StringBuilder sb, string cacheKey, Action<StringBuilder> stringBuilderAction)
{
if (StringBuilderCacheEnabled && StringBuilderCacheDict.TryGetValue(cacheKey, out string value))
{
sb.Append(value);
return;
}
StringBuilder newSb = new StringBuilder();
stringBuilderAction(newSb);
value = newSb.ToString();
StringBuilderCacheDict.AddOrUpdate(cacheKey, value, (t, v) => value);
sb.Append(value);
}
/// <summary>
/// Returns the current dialect name
/// </summary>
/// <returns></returns>
public static string GetDialect()
{
return _dialect.ToString();
}
/// <summary>
/// Sets the database dialect
/// </summary>
/// <param name="dialect"></param>
public static void SetDialect(Dialect dialect)
{
switch (dialect)
{
case Dialect.PostgreSQL:
_dialect = Dialect.PostgreSQL;
_encapsulation = "\"{0}\"";
_getIdentitySql = string.Format("SELECT LASTVAL() AS id");
_getPagedListSql = "Select {SelectColumns} from {TableName} {WhereClause} Order By {OrderBy} LIMIT {RowsPerPage} OFFSET (({PageNumber}-1) * {RowsPerPage})";
break;
case Dialect.SQLite:
_dialect = Dialect.SQLite;
_encapsulation = "\"{0}\"";
_getIdentitySql = string.Format("SELECT LAST_INSERT_ROWID() AS id");
_getPagedListSql = "Select {SelectColumns} from {TableName} {WhereClause} Order By {OrderBy} LIMIT {RowsPerPage} OFFSET (({PageNumber}-1) * {RowsPerPage})";
break;
case Dialect.MySQL:
_dialect = Dialect.MySQL;
_encapsulation = "`{0}`";
_getIdentitySql = string.Format("SELECT LAST_INSERT_ID() AS id");
_getPagedListSql = "Select {SelectColumns} from {TableName} {WhereClause} Order By {OrderBy} LIMIT {Offset},{RowsPerPage}";
break;
default:
_dialect = Dialect.SQLServer;
_encapsulation = "[{0}]";
_getIdentitySql = string.Format("SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [id]");
_getPagedListSql = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY {OrderBy}) AS PagedNumber, {SelectColumns} FROM {TableName} {WhereClause}) AS u WHERE PagedNumber BETWEEN (({PageNumber}-1) * {RowsPerPage} + 1) AND ({PageNumber} * {RowsPerPage})";
break;
}
}
/// <summary>
/// Sets the table name resolver
/// </summary>
/// <param name="resolver">The resolver to use when requesting the format of a table name</param>
public static void SetTableNameResolver(ITableNameResolver resolver)
{
_tableNameResolver = resolver;
}
/// <summary>
/// Sets the column name resolver
/// </summary>
/// <param name="resolver">The resolver to use when requesting the format of a column name</param>
public static void SetColumnNameResolver(IColumnNameResolver resolver)
{
_columnNameResolver = resolver;
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>By default filters on the Id column</para>
/// <para>-Id column name can be overridden by adding an attribute on your primary key property [Key]</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns a single entity by a single id from table T</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="id"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Returns a single entity by a single id from table T.</returns>
public static T Get<T>(this IDbConnection connection, object id, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var idProps = GetIdProperties(currenttype).ToList();
if (!idProps.Any())
throw new ArgumentException("Get<T> only supports an entity with a [Key] or Id property");
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.Append("Select ");
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
sb.AppendFormat(" from {0} where ", name);
for (var i = 0; i < idProps.Count; i++)
{
if (i > 0)
sb.Append(" and ");
sb.AppendFormat("{0} = @{1}", GetColumnName(idProps[i]), idProps[i].Name);
}
var dynParms = new DynamicParameters();
if (idProps.Count == 1)
dynParms.Add("@" + idProps.First().Name, id);
else
{
foreach (var prop in idProps)
dynParms.Add("@" + prop.Name, id.GetType().GetProperty(prop.Name).GetValue(id, null));
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Get<{0}>: {1} with Id: {2}", currenttype, sb, id));
return connection.Query<T>(sb.ToString(), dynParms, transaction, true, commandTimeout).FirstOrDefault();
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>whereConditions is an anonymous type to filter the results ex: new {Category = 1, SubCategory=2}</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns a list of entities that match where conditions</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="whereConditions"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Gets a list of entities with optional exact match where conditions</returns>
public static IEnumerable<T> GetList<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
var whereprops = GetAllProperties(whereConditions).ToArray();
sb.Append("Select ");
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
sb.AppendFormat(" from {0}", name);
if (whereprops.Any())
{
sb.Append(" where ");
BuildWhere<T>(sb, whereprops, whereConditions);
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("GetList<{0}>: {1}", currenttype, sb));
return connection.Query<T>(sb.ToString(), whereConditions, transaction, true, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>conditions is an SQL where clause and/or order by clause ex: "where name='bob'" or "where age>=@Age"</para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns a list of entities that match where conditions</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="conditions"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Gets a list of entities with optional SQL where conditions</returns>
public static IEnumerable<T> GetList<T>(this IDbConnection connection, string conditions, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.Append("Select ");
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
sb.AppendFormat(" from {0}", name);
sb.Append(" " + conditions);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("GetList<{0}>: {1}", currenttype, sb));
return connection.Query<T>(sb.ToString(), parameters, transaction, true, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Returns a list of all entities</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <returns>Gets a list of all entities</returns>
public static IEnumerable<T> GetList<T>(this IDbConnection connection)
{
return connection.GetList<T>(new { });
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>conditions is an SQL where clause ex: "where name='bob'" or "where age>=@Age" - not required </para>
/// <para>orderby is a column or list of columns to order by ex: "lastname, age desc" - not required - default is by primary key</para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns a list of entities that match where conditions</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="pageNumber"></param>
/// <param name="rowsPerPage"></param>
/// <param name="conditions"></param>
/// <param name="orderby"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Gets a paged list of entities with optional exact match where conditions</returns>
public static IEnumerable<T> GetListPaged<T>(this IDbConnection connection, int pageNumber, int rowsPerPage, string conditions, string orderby, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
if (string.IsNullOrEmpty(_getPagedListSql))
throw new Exception("GetListPage is not supported with the current SQL Dialect");
if (pageNumber < 1)
throw new Exception("Page must be greater than 0");
var currenttype = typeof(T);
var idProps = GetIdProperties(currenttype).ToList();
if (!idProps.Any())
throw new ArgumentException("Entity must have at least one [Key] property");
var name = GetTableName(currenttype);
var sb = new StringBuilder();
var query = _getPagedListSql;
if (string.IsNullOrEmpty(orderby))
{
orderby = GetColumnName(idProps.First());
}
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
query = query.Replace("{SelectColumns}", sb.ToString());
query = query.Replace("{TableName}", name);
query = query.Replace("{PageNumber}", pageNumber.ToString());
query = query.Replace("{RowsPerPage}", rowsPerPage.ToString());
query = query.Replace("{OrderBy}", orderby);
query = query.Replace("{WhereClause}", conditions);
query = query.Replace("{Offset}", ((pageNumber - 1) * rowsPerPage).ToString());
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("GetListPaged<{0}>: {1}", currenttype, query));
return connection.Query<T>(query, parameters, transaction, true, commandTimeout);
}
/// <summary>
/// <para>Inserts a row into the database</para>
/// <para>By default inserts into the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Insert filters out Id column and any columns with the [Key] attribute</para>
/// <para>Properties marked with attribute [Editable(false)] and complex types are ignored</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns the ID (primary key) of the newly inserted record if it is identity using the int? type, otherwise null</para>
/// </summary>
/// <param name="connection"></param>
/// <param name="entityToInsert"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The ID (primary key) of the newly inserted record if it is identity using the int? type, otherwise null</returns>
public static int? Insert<TEntity>(this IDbConnection connection, TEntity entityToInsert, IDbTransaction transaction = null, int? commandTimeout = null)
{
return Insert<int?, TEntity>(connection, entityToInsert, transaction, commandTimeout);
}
/// <summary>
/// <para>Inserts a row into the database, using ONLY the properties defined by TEntity</para>
/// <para>By default inserts into the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Insert filters out Id column and any columns with the [Key] attribute</para>
/// <para>Properties marked with attribute [Editable(false)] and complex types are ignored</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns the ID (primary key) of the newly inserted record if it is identity using the defined type, otherwise null</para>
/// </summary>
/// <param name="connection"></param>
/// <param name="entityToInsert"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The ID (primary key) of the newly inserted record if it is identity using the defined type, otherwise null</returns>
public static TKey Insert<TKey, TEntity>(this IDbConnection connection, TEntity entityToInsert, IDbTransaction transaction = null, int? commandTimeout = null)
{
var idProps = GetIdProperties(entityToInsert).ToList();
if (!idProps.Any())
throw new ArgumentException("Insert<T> only supports an entity with a [Key] or Id property");
var keyHasPredefinedValue = false;
var baseType = typeof(TKey);
var underlyingType = Nullable.GetUnderlyingType(baseType);
var keytype = underlyingType ?? baseType;
if (keytype != typeof(int) && keytype != typeof(uint) && keytype != typeof(long) && keytype != typeof(ulong) && keytype != typeof(short) && keytype != typeof(ushort) && keytype != typeof(Guid) && keytype != typeof(string))
{
throw new Exception("Invalid return type");
}
var name = GetTableName(entityToInsert);
var sb = new StringBuilder();
sb.AppendFormat("insert into {0}", name);
sb.Append(" (");
BuildInsertParameters<TEntity>(sb);
sb.Append(") ");
sb.Append("values");
sb.Append(" (");
BuildInsertValues<TEntity>(sb);
sb.Append(")");
if (keytype == typeof(Guid))
{
var guidvalue = (Guid)idProps.First().GetValue(entityToInsert, null);
if (guidvalue == Guid.Empty)
{
var newguid = SequentialGuid();
idProps.First().SetValue(entityToInsert, newguid, null);
}
else
{
keyHasPredefinedValue = true;
}
sb.Append(";select '" + idProps.First().GetValue(entityToInsert, null) + "' as id");
}
if ((keytype == typeof(int) || keytype == typeof(long)) && Convert.ToInt64(idProps.First().GetValue(entityToInsert, null)) == 0)
{
sb.Append(";" + _getIdentitySql);
}
else
{
keyHasPredefinedValue = true;
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Insert: {0}", sb));
var r = connection.Query(sb.ToString(), entityToInsert, transaction, true, commandTimeout);
if (keytype == typeof(Guid) || keyHasPredefinedValue)
{
return (TKey)idProps.First().GetValue(entityToInsert, null);
}
return (TKey)r.First().id;
}
/// <summary>
/// <para>Updates a record or records in the database with only the properties of TEntity</para>
/// <para>By default updates records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Updates records where the Id property and properties with the [Key] attribute match those in the database.</para>
/// <para>Properties marked with attribute [Editable(false)] and complex types are ignored</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns number of rows affected</para>
/// </summary>
/// <param name="connection"></param>
/// <param name="entityToUpdate"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of affected records</returns>
public static int Update<TEntity>(this IDbConnection connection, TEntity entityToUpdate, IDbTransaction transaction = null, int? commandTimeout = null)
{
var masterSb = new StringBuilder();
StringBuilderCache(masterSb, $"{typeof(TEntity).FullName}_Update", sb =>
{
var idProps = GetIdProperties(entityToUpdate).ToList();
if (!idProps.Any())
throw new ArgumentException("Entity must have at least one [Key] or Id property");
var name = GetTableName(entityToUpdate);
sb.AppendFormat("update {0}", name);
sb.AppendFormat(" set ");
BuildUpdateSet(entityToUpdate, sb);
sb.Append(" where ");
BuildWhere<TEntity>(sb, idProps, entityToUpdate);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Update: {0}", sb));
});
return connection.Execute(masterSb.ToString(), entityToUpdate, transaction, commandTimeout);
}
/// <summary>
/// <para>Deletes a record or records in the database that match the object passed in</para>
/// <para>-By default deletes records in the table matching the class name</para>
/// <para>Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns the number of records affected</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="entityToDelete"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static int Delete<T>(this IDbConnection connection, T entityToDelete, IDbTransaction transaction = null, int? commandTimeout = null)
{
var masterSb = new StringBuilder();
StringBuilderCache(masterSb, $"{typeof(T).FullName}_Delete", sb =>
{
var idProps = GetIdProperties(entityToDelete).ToList();
if (!idProps.Any())
throw new ArgumentException("Entity must have at least one [Key] or Id property");
var name = GetTableName(entityToDelete);
sb.AppendFormat("delete from {0}", name);
sb.Append(" where ");
BuildWhere<T>(sb, idProps, entityToDelete);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Delete: {0}", sb));
});
return connection.Execute(masterSb.ToString(), entityToDelete, transaction, commandTimeout);
}
/// <summary>
/// <para>Deletes a record or records in the database by ID</para>
/// <para>By default deletes records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Deletes records where the Id property and properties with the [Key] attribute match those in the database</para>
/// <para>The number of records affected</para>
/// <para>Supports transaction and command timeout</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="id"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static int Delete<T>(this IDbConnection connection, object id, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var idProps = GetIdProperties(currenttype).ToList();
if (!idProps.Any())
throw new ArgumentException("Delete<T> only supports an entity with a [Key] or Id property");
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.AppendFormat("Delete from {0} where ", name);
for (var i = 0; i < idProps.Count; i++)
{
if (i > 0)
sb.Append(" and ");
sb.AppendFormat("{0} = @{1}", GetColumnName(idProps[i]), idProps[i].Name);
}
var dynParms = new DynamicParameters();
if (idProps.Count == 1)
dynParms.Add("@" + idProps.First().Name, id);
else
{
foreach (var prop in idProps)
dynParms.Add("@" + prop.Name, id.GetType().GetProperty(prop.Name).GetValue(id, null));
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Delete<{0}> {1}", currenttype, sb));
return connection.Execute(sb.ToString(), dynParms, transaction, commandTimeout);
}
/// <summary>
/// <para>Deletes a list of records in the database</para>
/// <para>By default deletes records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Deletes records where that match the where clause</para>
/// <para>whereConditions is an anonymous type to filter the results ex: new {Category = 1, SubCategory=2}</para>
/// <para>The number of records affected</para>
/// <para>Supports transaction and command timeout</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="whereConditions"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static int DeleteList<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null)
{
var masterSb = new StringBuilder();
StringBuilderCache(masterSb, $"{typeof(T).FullName}_DeleteWhere{whereConditions?.GetType()?.FullName}", sb =>
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var whereprops = GetAllProperties(whereConditions).ToArray();
sb.AppendFormat("Delete from {0}", name);
if (whereprops.Any())
{
sb.Append(" where ");
BuildWhere<T>(sb, whereprops);
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("DeleteList<{0}> {1}", currenttype, sb));
});
return connection.Execute(masterSb.ToString(), whereConditions, transaction, commandTimeout);
}
/// <summary>
/// <para>Deletes a list of records in the database</para>
/// <para>By default deletes records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Deletes records where that match the where clause</para>
/// <para>conditions is an SQL where clause ex: "where name='bob'" or "where age>=@Age"</para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// <para>Supports transaction and command timeout</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="conditions"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static int DeleteList<T>(this IDbConnection connection, string conditions, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
var masterSb = new StringBuilder();
StringBuilderCache(masterSb, $"{typeof(T).FullName}_DeleteWhere{conditions}", sb =>
{
if (string.IsNullOrEmpty(conditions))
throw new ArgumentException("DeleteList<T> requires a where clause");
if (!conditions.ToLower().Contains("where"))
throw new ArgumentException("DeleteList<T> requires a where clause and must contain the WHERE keyword");
var currenttype = typeof(T);
var name = GetTableName(currenttype);
sb.AppendFormat("Delete from {0}", name);
sb.Append(" " + conditions);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("DeleteList<{0}> {1}", currenttype, sb));
});
return connection.Execute(masterSb.ToString(), parameters, transaction, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Returns a number of records entity by a single id from table T</para>
/// <para>Supports transaction and command timeout</para>
/// <para>conditions is an SQL where clause ex: "where name='bob'" or "where age>=@Age" - not required </para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="conditions"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Returns a count of records.</returns>
public static int RecordCount<T>(this IDbConnection connection, string conditions = "", object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.Append("Select count(1)");
sb.AppendFormat(" from {0}", name);
sb.Append(" " + conditions);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("RecordCount<{0}>: {1}", currenttype, sb));
return connection.ExecuteScalar<int>(sb.ToString(), parameters, transaction, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Returns a number of records entity by a single id from table T</para>
/// <para>Supports transaction and command timeout</para>
/// <para>whereConditions is an anonymous type to filter the results ex: new {Category = 1, SubCategory=2}</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="whereConditions"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Returns a count of records.</returns>
public static int RecordCount<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
var whereprops = GetAllProperties(whereConditions).ToArray();
sb.Append("Select count(1)");
sb.AppendFormat(" from {0}", name);
if (whereprops.Any())
{
sb.Append(" where ");
BuildWhere<T>(sb, whereprops);
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("RecordCount<{0}>: {1}", currenttype, sb));
return connection.ExecuteScalar<int>(sb.ToString(), whereConditions, transaction, commandTimeout);
}
//build update statement based on list on an entity
private static void BuildUpdateSet<T>(T entityToUpdate, StringBuilder masterSb)
{
StringBuilderCache(masterSb, $"{typeof(T).FullName}_BuildUpdateSet", sb =>
{
var nonIdProps = GetUpdateableProperties(entityToUpdate).ToArray();
for (var i = 0; i < nonIdProps.Length; i++)
{
var property = nonIdProps[i];
sb.AppendFormat("{0} = @{1}", GetColumnName(property), property.Name);
if (i < nonIdProps.Length - 1)
sb.AppendFormat(", ");
}
});
}
//build select clause based on list of properties skipping ones with the IgnoreSelect and NotMapped attribute
private static void BuildSelect(StringBuilder masterSb, IEnumerable<PropertyInfo> props)
{
StringBuilderCache(masterSb, $"{props.CacheKey()}_BuildSelect", sb =>
{
var propertyInfos = props as IList<PropertyInfo> ?? props.ToList();
var addedAny = false;
for (var i = 0; i < propertyInfos.Count(); i++)
{
var property = propertyInfos.ElementAt(i);
if (property.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(IgnoreSelectAttribute).Name || attr.GetType().Name == typeof(NotMappedAttribute).Name)) continue;
if (addedAny)
sb.Append(",");
sb.Append(GetColumnName(property));
//if there is a custom column name add an "as customcolumnname" to the item so it maps properly
if (property.GetCustomAttributes(true).SingleOrDefault(attr => attr.GetType().Name == typeof(ColumnAttribute).Name) != null)
sb.Append(" as " + Encapsulate(property.Name));
addedAny = true;
}
});
}
private static void BuildWhere<TEntity>(StringBuilder sb, IEnumerable<PropertyInfo> idProps, object whereConditions = null)
{
var propertyInfos = idProps.ToArray();
for (var i = 0; i < propertyInfos.Count(); i++)
{
var useIsNull = false;
//match up generic properties to source entity properties to allow fetching of the column attribute
//the anonymous object used for search doesn't have the custom attributes attached to them so this allows us to build the correct where clause
//by converting the model type to the database column name via the column attribute
var propertyToUse = propertyInfos.ElementAt(i);
var sourceProperties = GetScaffoldableProperties<TEntity>().ToArray();
for (var x = 0; x < sourceProperties.Count(); x++)
{
if (sourceProperties.ElementAt(x).Name == propertyToUse.Name)
{
if (whereConditions != null && propertyToUse.CanRead && (propertyToUse.GetValue(whereConditions, null) == null || propertyToUse.GetValue(whereConditions, null) == DBNull.Value))
{
useIsNull = true;
}
propertyToUse = sourceProperties.ElementAt(x);
break;
}
}
sb.AppendFormat(
useIsNull ? "{0} is null" : "{0} = @{1}",
GetColumnName(propertyToUse),
propertyToUse.Name);
if (i < propertyInfos.Count() - 1)
sb.AppendFormat(" and ");
}
}
//build insert values which include all properties in the class that are:
//Not named Id
//Not marked with the Editable(false) attribute
//Not marked with the [Key] attribute (without required attribute)
//Not marked with [IgnoreInsert]
//Not marked with [NotMapped]
private static void BuildInsertValues<T>(StringBuilder masterSb)
{
StringBuilderCache(masterSb, $"{typeof(T).FullName}_BuildInsertValues", sb =>
{
var props = GetScaffoldableProperties<T>().ToArray();
for (var i = 0; i < props.Count(); i++)
{
var property = props.ElementAt(i);
if (property.PropertyType != typeof(Guid) && property.PropertyType != typeof(string)
&& property.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(KeyAttribute).Name)
&& property.GetCustomAttributes(true).All(attr => attr.GetType().Name != typeof(RequiredAttribute).Name))
continue;
if (property.GetCustomAttributes(true).Any(attr =>
attr.GetType().Name == typeof(IgnoreInsertAttribute).Name ||
attr.GetType().Name == typeof(NotMappedAttribute).Name ||
attr.GetType().Name == typeof(ReadOnlyAttribute).Name && IsReadOnly(property))
) continue;
if (property.Name.Equals("Id", StringComparison.OrdinalIgnoreCase) && property.GetCustomAttributes(true).All(attr => attr.GetType().Name != typeof(RequiredAttribute).Name) && property.PropertyType != typeof(Guid)) continue;
sb.AppendFormat("@{0}", property.Name);
if (i < props.Count() - 1)
sb.Append(", ");
}
if (sb.ToString().EndsWith(", "))
sb.Remove(sb.Length - 2, 2);
});
}
//build insert parameters which include all properties in the class that are not:
//marked with the Editable(false) attribute
//marked with the [Key] attribute
//marked with [IgnoreInsert]
//named Id
//marked with [NotMapped]
private static void BuildInsertParameters<T>(StringBuilder masterSb)
{
StringBuilderCache(masterSb, $"{typeof(T).FullName}_BuildInsertParameters", sb =>
{
var props = GetScaffoldableProperties<T>().ToArray();
for (var i = 0; i < props.Count(); i++)
{
var property = props.ElementAt(i);
if (property.PropertyType != typeof(Guid) && property.PropertyType != typeof(string)
&& property.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(KeyAttribute).Name)
&& property.GetCustomAttributes(true).All(attr => attr.GetType().Name != typeof(RequiredAttribute).Name))
continue;
if (property.GetCustomAttributes(true).Any(attr =>
attr.GetType().Name == typeof(IgnoreInsertAttribute).Name ||
attr.GetType().Name == typeof(NotMappedAttribute).Name ||
attr.GetType().Name == typeof(ReadOnlyAttribute).Name && IsReadOnly(property))) continue;
if (property.Name.Equals("Id", StringComparison.OrdinalIgnoreCase) && property.GetCustomAttributes(true).All(attr => attr.GetType().Name != typeof(RequiredAttribute).Name) && property.PropertyType != typeof(Guid)) continue;
sb.Append(GetColumnName(property));
if (i < props.Count() - 1)
sb.Append(", ");
}
if (sb.ToString().EndsWith(", "))
sb.Remove(sb.Length - 2, 2);
});
}
//Get all properties in an entity
private static IEnumerable<PropertyInfo> GetAllProperties<T>(T entity) where T : class
{
if (entity == null) return new PropertyInfo[0];
return entity.GetType().GetProperties();
}
//Get all properties that are not decorated with the Editable(false) attribute
private static IEnumerable<PropertyInfo> GetScaffoldableProperties<T>()
{
IEnumerable<PropertyInfo> props = typeof(T).GetProperties();
props = props.Where(p => p.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(EditableAttribute).Name && !IsEditable(p)) == false);
return props.Where(p => p.PropertyType.IsSimpleType() || IsEditable(p));
}
//Determine if the Attribute has an AllowEdit key and return its boolean state
//fake the funk and try to mimic EditableAttribute in System.ComponentModel.DataAnnotations
//This allows use of the DataAnnotations property in the model and have the SimpleCRUD engine just figure it out without a reference
private static bool IsEditable(PropertyInfo pi)
{
var attributes = pi.GetCustomAttributes(false);
if (attributes.Length > 0)
{
dynamic write = attributes.FirstOrDefault(x => x.GetType().Name == typeof(EditableAttribute).Name);
if (write != null)
{
return write.AllowEdit;
}
}
return false;
}
//Determine if the Attribute has an IsReadOnly key and return its boolean state
//fake the funk and try to mimic ReadOnlyAttribute in System.ComponentModel
//This allows use of the DataAnnotations property in the model and have the SimpleCRUD engine just figure it out without a reference
private static bool IsReadOnly(PropertyInfo pi)
{
var attributes = pi.GetCustomAttributes(false);
if (attributes.Length > 0)
{
dynamic write = attributes.FirstOrDefault(x => x.GetType().Name == typeof(ReadOnlyAttribute).Name);
if (write != null)
{
return write.IsReadOnly;
}
}
return false;
}
//Get all properties that are:
//Not named Id
//Not marked with the Key attribute
//Not marked ReadOnly
//Not marked IgnoreInsert
//Not marked NotMapped
private static IEnumerable<PropertyInfo> GetUpdateableProperties<T>(T entity)
{
var updateableProperties = GetScaffoldableProperties<T>();
//remove ones with ID
updateableProperties = updateableProperties.Where(p => !p.Name.Equals("Id", StringComparison.OrdinalIgnoreCase));
//remove ones with key attribute
updateableProperties = updateableProperties.Where(p => p.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(KeyAttribute).Name) == false);
//remove ones that are readonly
updateableProperties = updateableProperties.Where(p => p.GetCustomAttributes(true).Any(attr => (attr.GetType().Name == typeof(ReadOnlyAttribute).Name) && IsReadOnly(p)) == false);
//remove ones with IgnoreUpdate attribute
updateableProperties = updateableProperties.Where(p => p.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(IgnoreUpdateAttribute).Name) == false);
//remove ones that are not mapped
updateableProperties = updateableProperties.Where(p => p.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(NotMappedAttribute).Name) == false);
return updateableProperties;
}
//Get all properties that are named Id or have the Key attribute
//For Inserts and updates we have a whole entity so this method is used
private static IEnumerable<PropertyInfo> GetIdProperties(object entity)
{
var type = entity.GetType();
return GetIdProperties(type);
}
//Get all properties that are named Id or have the Key attribute
//For Get(id) and Delete(id) we don't have an entity, just the type so this method is used
private static IEnumerable<PropertyInfo> GetIdProperties(Type type)
{
var tp = type.GetProperties().Where(p => p.GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(KeyAttribute).Name)).ToList();
return tp.Any() ? tp : type.GetProperties().Where(p => p.Name.Equals("Id", StringComparison.OrdinalIgnoreCase));
}
//Gets the table name for this entity
//For Inserts and updates we have a whole entity so this method is used
//Uses class name by default and overrides if the class has a Table attribute
private static string GetTableName(object entity)
{
var type = entity.GetType();
return GetTableName(type);
}
//Gets the table name for this type
//For Get(id) and Delete(id) we don't have an entity, just the type so this method is used
//Use dynamic type to be able to handle both our Table-attribute and the DataAnnotation
//Uses class name by default and overrides if the class has a Table attribute
private static string GetTableName(Type type)
{
string tableName;
if (TableNames.TryGetValue(type, out tableName))
return tableName;
tableName = _tableNameResolver.ResolveTableName(type);
TableNames.AddOrUpdate(type, tableName, (t, v) => tableName);
return tableName;
}
private static string GetColumnName(PropertyInfo propertyInfo)
{
string columnName, key = string.Format("{0}.{1}", propertyInfo.DeclaringType, propertyInfo.Name);
if (ColumnNames.TryGetValue(key, out columnName))
return columnName;
columnName = _columnNameResolver.ResolveColumnName(propertyInfo);
ColumnNames.AddOrUpdate(key, columnName, (t, v) => columnName);
return columnName;
}
private static string Encapsulate(string databaseword)
{
return string.Format(_encapsulation, databaseword);
}
/// <summary>
/// Generates a GUID based on the current date/time
/// http://stackoverflow.com/questions/1752004/sequential-guid-generator-c-sharp
/// </summary>
/// <returns></returns>
public static Guid SequentialGuid()
{
var tempGuid = Guid.NewGuid();
var bytes = tempGuid.ToByteArray();
var time = DateTime.Now;
bytes[3] = (byte)time.Year;
bytes[2] = (byte)time.Month;
bytes[1] = (byte)time.Day;
bytes[0] = (byte)time.Hour;
bytes[5] = (byte)time.Minute;
bytes[4] = (byte)time.Second;
return new Guid(bytes);
}
/// <summary>
/// Database server dialects
/// </summary>
public enum Dialect
{
SQLServer,
PostgreSQL,
SQLite,
MySQL,
}
public interface ITableNameResolver
{
string ResolveTableName(Type type);
}
public interface IColumnNameResolver
{
string ResolveColumnName(PropertyInfo propertyInfo);
}
public class TableNameResolver : ITableNameResolver
{
public virtual string ResolveTableName(Type type)
{
var tableName = Encapsulate(type.Name);
var tableattr = type.GetCustomAttributes(true).SingleOrDefault(attr => attr.GetType().Name == typeof(TableAttribute).Name) as dynamic;
if (tableattr != null)
{
tableName = Encapsulate(tableattr.Name);
try
{
if (!String.IsNullOrEmpty(tableattr.Schema))
{
string schemaName = Encapsulate(tableattr.Schema);
tableName = String.Format("{0}.{1}", schemaName, tableName);
}
}
catch (RuntimeBinderException)
{
//Schema doesn't exist on this attribute.
}
}
return tableName;
}
}
public class ColumnNameResolver : IColumnNameResolver
{
public virtual string ResolveColumnName(PropertyInfo propertyInfo)
{
var columnName = Encapsulate(propertyInfo.Name);
var columnattr = propertyInfo.GetCustomAttributes(true).SingleOrDefault(attr => attr.GetType().Name == typeof(ColumnAttribute).Name) as dynamic;
if (columnattr != null && columnattr.Name != null)
{
columnName = Encapsulate(columnattr.Name);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Column name for type overridden from {0} to {1}", propertyInfo.Name, columnName));
}
return columnName;
}
}
}
/// <summary>
/// Optional Table attribute.
/// You can use the System.ComponentModel.DataAnnotations version in its place to specify the table name of a poco
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class TableAttribute : Attribute
{
/// <summary>
/// Optional Table attribute.
/// </summary>
/// <param name="tableName"></param>
public TableAttribute(string tableName)
{
Name = tableName;
}
/// <summary>
/// Name of the table
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Name of the schema
/// </summary>
public string Schema { get; set; }
}
/// <summary>
/// Optional Column attribute.
/// You can use the System.ComponentModel.DataAnnotations version in its place to specify the table name of a poco
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
/// <summary>
/// Optional Column attribute.
/// </summary>
/// <param name="columnName"></param>
public ColumnAttribute(string columnName)
{
Name = columnName;
}
/// <summary>
/// Name of the column
/// </summary>
public string Name { get; private set; }
}
/// <summary>
/// Optional Key attribute.
/// You can use the System.ComponentModel.DataAnnotations version in its place to specify the Primary Key of a poco
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class KeyAttribute : Attribute
{
}
/// <summary>
/// Optional NotMapped attribute.
/// You can use the System.ComponentModel.DataAnnotations version in its place to specify that the property is not mapped
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class NotMappedAttribute : Attribute
{
}
/// <summary>
/// Optional Key attribute.
/// You can use the System.ComponentModel.DataAnnotations version in its place to specify a required property of a poco
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class RequiredAttribute : Attribute
{
}
/// <summary>
/// Optional Editable attribute.
/// You can use the System.ComponentModel.DataAnnotations version in its place to specify the properties that are editable
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class EditableAttribute : Attribute
{
/// <summary>
/// Optional Editable attribute.
/// </summary>
/// <param name="iseditable"></param>
public EditableAttribute(bool iseditable)
{
AllowEdit = iseditable;
}
/// <summary>
/// Does this property persist to the database?
/// </summary>
public bool AllowEdit { get; private set; }
}
/// <summary>
/// Optional Readonly attribute.
/// You can use the System.ComponentModel version in its place to specify the properties that are editable
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ReadOnlyAttribute : Attribute
{
/// <summary>
/// Optional ReadOnly attribute.
/// </summary>
/// <param name="isReadOnly"></param>
public ReadOnlyAttribute(bool isReadOnly)
{
IsReadOnly = isReadOnly;
}
/// <summary>
/// Does this property persist to the database?
/// </summary>
public bool IsReadOnly { get; private set; }
}
/// <summary>
/// Optional IgnoreSelect attribute.
/// Custom for Dapper.SimpleCRUD to exclude a property from Select methods
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class IgnoreSelectAttribute : Attribute
{
}
/// <summary>
/// Optional IgnoreInsert attribute.
/// Custom for Dapper.SimpleCRUD to exclude a property from Insert methods
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class IgnoreInsertAttribute : Attribute
{
}
/// <summary>
/// Optional IgnoreUpdate attribute.
/// Custom for Dapper.SimpleCRUD to exclude a property from Update methods
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class IgnoreUpdateAttribute : Attribute
{
}
}
internal static class TypeExtension
{
//You can't insert or update complex types. Lets filter them out.
public static bool IsSimpleType(this Type type)
{
var underlyingType = Nullable.GetUnderlyingType(type);
type = underlyingType ?? type;
var simpleTypes = new List<Type>
{
typeof(byte),
typeof(sbyte),
typeof(short),
typeof(ushort),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(float),
typeof(double),
typeof(decimal),
typeof(bool),
typeof(string),
typeof(char),
typeof(Guid),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(byte[])
};
return simpleTypes.Contains(type) || type.IsEnum;
}
public static string CacheKey(this IEnumerable<PropertyInfo> props)
{
return string.Join(",",props.Select(p=> p.DeclaringType.FullName + "." + p.Name).ToArray());
}
}
| 47.471405 | 271 | 0.567008 | [
"Apache-2.0"
] | ccrookston/Dapper.SimpleCRUD | Dapper.SimpleCRUD/SimpleCRUD.cs | 58,107 | C# |
using AutoMapper;
using Vokabular.DataEntities.Database.Entities;
using Vokabular.DataEntities.Database.Entities.Enums;
using Vokabular.MainService.DataContracts.Contracts;
using Vokabular.MainService.DataContracts.Contracts.Type;
namespace Vokabular.MainService.Core.AutoMapperProfiles
{
public class ProjectProfile : Profile
{
public ProjectProfile()
{
CreateMap<Project, ProjectContract>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.ProjectType, opt => opt.MapFrom(src => src.ProjectType))
.ForMember(dest => dest.TextType, opt => opt.MapFrom(src => src.TextType));
//.ForMember(dest => dest.ExternalId, opt => opt.MapFrom(src => src.ExternalId));
CreateMap<Project, GetProjectContract>()
.IncludeBase<Project, ProjectContract>()
.ForMember(dest => dest.CreateTime, opt => opt.MapFrom(src => src.CreateTime))
.ForMember(dest => dest.CreatedByUser, opt => opt.MapFrom(src => src.CreatedByUser));
CreateMap<Project, ProjectDetailContract>()
.IncludeBase<Project, ProjectContract>()
.ForMember(dest => dest.LatestMetadata, opt => opt.Ignore())
.ForMember(dest => dest.PageCount, opt => opt.Ignore())
.ForMember(dest => dest.Authors, opt => opt.Ignore())
.ForMember(dest => dest.ResponsiblePersons, opt => opt.Ignore())
.ForMember(dest => dest.EditedByUser, opt => opt.Ignore())
.ForMember(dest => dest.LatestChangeTime, opt => opt.Ignore())
.ForMember(dest => dest.CurrentUserPermissions, opt => opt.Ignore());
CreateMap<ProjectTypeEnum, ProjectTypeContract>().ReverseMap();
CreateMap<TextTypeEnum, TextTypeEnumContract>().ReverseMap();
}
}
}
| 47.928571 | 101 | 0.618977 | [
"BSD-3-Clause"
] | RIDICS/ITJakub | UJCSystem/Vokabular.MainService.Core/AutoMapperProfiles/ProjectProfile.cs | 2,015 | C# |
namespace MassTransit
{
using System;
using EndpointConfigurators;
public interface IReceiveConnector<out TEndpointConfigurator> :
IReceiveConnector
where TEndpointConfigurator : IReceiveEndpointConfigurator
{
/// <summary>
/// Adds a receive endpoint
/// </summary>
/// <param name="definition">
/// An endpoint definition, which abstracts specific endpoint behaviors from the transport
/// </param>
/// <param name="endpointNameFormatter"></param>
/// <param name="configureEndpoint">The configuration callback</param>
HostReceiveEndpointHandle ConnectReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter endpointNameFormatter,
Action<TEndpointConfigurator> configureEndpoint = null);
/// <summary>
/// Adds a receive endpoint
/// </summary>
/// <param name="queueName">The queue name for the receive endpoint</param>
/// <param name="configureEndpoint">The configuration callback</param>
HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<TEndpointConfigurator> configureEndpoint);
}
public interface IReceiveConnector :
IEndpointConfigurationObserverConnector
{
/// <summary>
/// Adds a receive endpoint
/// </summary>
/// <param name="definition">
/// An endpoint definition, which abstracts specific endpoint behaviors from the transport
/// </param>
/// <param name="endpointNameFormatter"></param>
/// <param name="configureEndpoint">The configuration callback</param>
HostReceiveEndpointHandle ConnectReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter endpointNameFormatter,
Action<IReceiveEndpointConfigurator> configureEndpoint = null);
/// <summary>
/// Adds a receive endpoint
/// </summary>
/// <param name="queueName">The queue name for the receive endpoint</param>
/// <param name="configureEndpoint">The configuration callback</param>
HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IReceiveEndpointConfigurator> configureEndpoint);
}
}
| 42.773585 | 134 | 0.684164 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/MassTransit/Configuration/IReceiveConnector.cs | 2,267 | C# |
using UnityEngine;
using System.Collections;
public interface IGUI {
void OnGUI();
} | 14.5 | 25 | 0.758621 | [
"MIT"
] | Lidapow/PowIoC | Assets/Example/IGUI.cs | 87 | C# |
// Copyright (c) 2012, Michael Kunz. All rights reserved.
// http://kunzmi.github.io/managedCuda
//
// This file is part of ManagedCuda.
//
// ManagedCuda 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.
//
// ManagedCuda 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 Street, Fifth Floor, Boston,
// MA 02110-1301 USA, http://www.gnu.org/licenses/.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using ManagedCuda.BasicTypes;
namespace ManagedCuda.NPP
{
/// <summary>
///
/// </summary>
public class NPPImage_32scC4 : NPPImageBase
{
#region Constructors
/// <summary>
/// Allocates new memory on device using NPP-Api.
/// </summary>
/// <param name="nWidthPixels">Image width in pixels</param>
/// <param name="nHeightPixels">Image height in pixels</param>
public NPPImage_32scC4(int nWidthPixels, int nHeightPixels)
{
_sizeOriginal.width = nWidthPixels;
_sizeOriginal.height = nHeightPixels;
_sizeRoi.width = nWidthPixels;
_sizeRoi.height = nHeightPixels;
_channels = 4;
_isOwner = true;
_typeSize = Marshal.SizeOf(typeof(Npp32sc));
_devPtr = NPPNativeMethods.NPPi.MemAlloc.nppiMalloc_32sc_C4(nWidthPixels, nHeightPixels, ref _pitch);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}, Pitch is: {3}, Number of color channels: {4}", DateTime.Now, "nppiMalloc_32sc_C4", res, _pitch, _channels));
if (_devPtr.Pointer == 0)
{
throw new NPPException("Device allocation error", null);
}
_devPtrRoi = _devPtr;
}
/// <summary>
/// Creates a new NPPImage from allocated device ptr.
/// </summary>
/// <param name="devPtr">Already allocated device ptr.</param>
/// <param name="width">Image width in pixels</param>
/// <param name="height">Image height in pixels</param>
/// <param name="pitch">Pitch / Line step</param>
/// <param name="isOwner">If TRUE, devPtr is freed when disposing</param>
public NPPImage_32scC4(CUdeviceptr devPtr, int width, int height, int pitch, bool isOwner)
{
_devPtr = devPtr;
_devPtrRoi = _devPtr;
_sizeOriginal.width = width;
_sizeOriginal.height = height;
_sizeRoi.width = width;
_sizeRoi.height = height;
_pitch = pitch;
_channels = 4;
_isOwner = isOwner;
_typeSize = Marshal.SizeOf(typeof(Npp32sc));
}
/// <summary>
/// Creates a new NPPImage from allocated device ptr. Does not take ownership of decPtr.
/// </summary>
/// <param name="devPtr">Already allocated device ptr.</param>
/// <param name="width">Image width in pixels</param>
/// <param name="height">Image height in pixels</param>
/// <param name="pitch">Pitch / Line step</param>
public NPPImage_32scC4(CUdeviceptr devPtr, int width, int height, int pitch)
: this(devPtr, width, height, pitch, false)
{
}
/// <summary>
/// Creates a new NPPImage from allocated device ptr. Does not take ownership of inner image device pointer.
/// </summary>
/// <param name="image">NPP image</param>
public NPPImage_32scC4(NPPImageBase image)
: this(image.DevicePointer, image.Width, image.Height, image.Pitch, false)
{
}
/// <summary>
/// Allocates new memory on device using NPP-Api.
/// </summary>
/// <param name="size">Image size</param>
public NPPImage_32scC4(NppiSize size)
: this(size.width, size.height)
{
}
/// <summary>
/// Creates a new NPPImage from allocated device ptr.
/// </summary>
/// <param name="devPtr">Already allocated device ptr.</param>
/// <param name="size">Image size</param>
/// <param name="pitch">Pitch / Line step</param>
/// <param name="isOwner">If TRUE, devPtr is freed when disposing</param>
public NPPImage_32scC4(CUdeviceptr devPtr, NppiSize size, int pitch, bool isOwner)
: this(devPtr, size.width, size.height, pitch, isOwner)
{
}
/// <summary>
/// Creates a new NPPImage from allocated device ptr.
/// </summary>
/// <param name="devPtr">Already allocated device ptr.</param>
/// <param name="size">Image size</param>
/// <param name="pitch">Pitch / Line step</param>
public NPPImage_32scC4(CUdeviceptr devPtr, NppiSize size, int pitch)
: this(devPtr, size.width, size.height, pitch)
{
}
/// <summary>
/// For dispose
/// </summary>
~NPPImage_32scC4()
{
Dispose (false);
}
#endregion
#region Copy
/// <summary>
/// image copy.
/// </summary>
/// <param name="dst">Destination image</param>
public void Copy(NPPImage_32scC4 dst)
{
status = NPPNativeMethods.NPPi.MemCopy.nppiCopy_32sc_C4R(_devPtrRoi, _pitch, dst.DevicePointerRoi, dst.Pitch, _sizeRoi);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiCopy_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// image copy. Not affecting Alpha channel.
/// </summary>
/// <param name="dst">Destination image</param>
public void CopyA(NPPImage_32scC4 dst)
{
status = NPPNativeMethods.NPPi.MemCopy.nppiCopy_32sc_AC4R(_devPtrRoi, _pitch, dst.DevicePointerRoi, dst.Pitch, _sizeRoi);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiCopy_32sc_AC4R", status));
NPPException.CheckNppStatus(status, this);
}
#endregion
#region Set
/// <summary>
/// Set pixel values to nValue.
/// </summary>
/// <param name="nValue">Value to be set (Array size = 4)</param>
public void Set(Npp32sc[] nValue)
{
status = NPPNativeMethods.NPPi.MemSet.nppiSet_32sc_C4R(nValue, _devPtrRoi, _pitch, _sizeRoi);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSet_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Set pixel values to nValue. <para/>
/// The 8-bit mask image affects setting of the respective pixels in the destination image. <para/>
/// If the mask value is zero (0) the pixel is not set, if the mask is non-zero, the corresponding
/// destination pixel is set to specified value. Not affecting alpha channel.
/// </summary>
/// <param name="nValue">Value to be set (Array size = 3)</param>
public void SetA(Npp32sc[] nValue)
{
status = NPPNativeMethods.NPPi.MemSet.nppiSet_32sc_AC4R(nValue, _devPtrRoi, _pitch, _sizeRoi);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSet_32sc_AC4R", status));
NPPException.CheckNppStatus(status, this);
}
#endregion
#region Add
/// <summary>
/// Image addition, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Add(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Add.nppiAdd_32sc_C4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAdd_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image addition, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Add(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Add.nppiAdd_32sc_C4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAdd_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Add constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="nConstant">Values to add</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Add(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.AddConst.nppiAddC_32sc_C4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAddC_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Add constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace.
/// </summary>
/// <param name="nConstant">Values to add</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Add(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.AddConst.nppiAddC_32sc_C4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAddC_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Image addition, scale by 2^(-nScaleFactor), then clamp to saturated value. Unmodified Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void AddA(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Add.nppiAdd_32sc_AC4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAdd_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image addition, scale by 2^(-nScaleFactor), then clamp to saturated value. Unmodified Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void AddA(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Add.nppiAdd_32sc_AC4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAdd_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Add constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Unmodified Alpha.
/// </summary>
/// <param name="nConstant">Values to add</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void AddA(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.AddConst.nppiAddC_32sc_AC4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAddC_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Add constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace. Unmodified Alpha.
/// </summary>
/// <param name="nConstant">Values to add</param>
/// <param name="nScaleFactor">scaling factor</param>
public void AddA(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.AddConst.nppiAddC_32sc_AC4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAddC_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
#endregion
#region Sub
/// <summary>
/// Image subtraction, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Sub(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Sub.nppiSub_32sc_C4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSub_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image subtraction, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Sub(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Sub.nppiSub_32sc_C4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSub_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Subtract constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="nConstant">Value to subtract</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Sub(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.SubConst.nppiSubC_32sc_C4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSubC_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Subtract constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace.
/// </summary>
/// <param name="nConstant">Value to subtract</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Sub(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.SubConst.nppiSubC_32sc_C4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSubC_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Image subtraction, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void SubA(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Sub.nppiSub_32sc_AC4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSub_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image subtraction, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void SubA(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Sub.nppiSub_32sc_AC4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSub_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Subtract constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="nConstant">Value to subtract</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void SubA(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.SubConst.nppiSubC_32sc_AC4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSubC_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Subtract constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace. Unchanged Alpha.
/// </summary>
/// <param name="nConstant">Value to subtract</param>
/// <param name="nScaleFactor">scaling factor</param>
public void SubA(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.SubConst.nppiSubC_32sc_AC4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiSubC_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
#endregion
#region Mul
/// <summary>
/// Image multiplication, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Mul(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Mul.nppiMul_32sc_C4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMul_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image multiplication, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Mul(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Mul.nppiMul_32sc_C4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMul_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Multiply constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Mul(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.MulConst.nppiMulC_32sc_C4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMulC_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Multiply constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Mul(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.MulConst.nppiMulC_32sc_C4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMulC_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Image multiplication, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void MulA(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Mul.nppiMul_32sc_AC4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMul_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image multiplication, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void MulA(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Mul.nppiMul_32sc_AC4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMul_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Multiply constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void MulA(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.MulConst.nppiMulC_32sc_AC4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMulC_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Multiply constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace. Unchanged Alpha.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="nScaleFactor">scaling factor</param>
public void MulA(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.MulConst.nppiMulC_32sc_AC4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMulC_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
#endregion
#region Div
/// <summary>
/// Image division, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Div(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Div.nppiDiv_32sc_C4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDiv_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image division, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Div(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Div.nppiDiv_32sc_C4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDiv_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Divide constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Div(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.DivConst.nppiDivC_32sc_C4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDivC_32sc_C4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Divide constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="nScaleFactor">scaling factor</param>
public void Div(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.DivConst.nppiDivC_32sc_C4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDivC_32sc_C4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Image division, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void DivA(NPPImage_32scC4 src2, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Div.nppiDiv_32sc_AC4RSfs(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDiv_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// In place image division, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void DivA(NPPImage_32scC4 src2, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.Div.nppiDiv_32sc_AC4IRSfs(src2.DevicePointerRoi, src2.Pitch, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDiv_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Divide constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Unchanged Alpha.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="dest">Destination image</param>
/// <param name="nScaleFactor">scaling factor</param>
public void DivA(Npp32sc[] nConstant, NPPImage_32scC4 dest, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.DivConst.nppiDivC_32sc_AC4RSfs(_devPtrRoi, _pitch, nConstant, dest.DevicePointerRoi, dest.Pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDivC_32sc_AC4RSfs", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Divide constant to image, scale by 2^(-nScaleFactor), then clamp to saturated value. Inplace. Unchanged Alpha.
/// </summary>
/// <param name="nConstant">Value</param>
/// <param name="nScaleFactor">scaling factor</param>
public void DivA(Npp32sc[] nConstant, int nScaleFactor)
{
status = NPPNativeMethods.NPPi.DivConst.nppiDivC_32sc_AC4IRSfs(nConstant, _devPtrRoi, _pitch, _sizeRoi, nScaleFactor);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiDivC_32sc_AC4IRSfs", status));
NPPException.CheckNppStatus(status, this);
}
#endregion
#region MaxError
/// <summary>
/// image maximum error. User buffer is internally allocated and freed.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
public void MaxError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError)
{
int bufferSize = MaxErrorGetBufferHostSize();
CudaDeviceVariable<byte> buffer = new CudaDeviceVariable<byte>(bufferSize);
status = NPPNativeMethods.NPPi.MaximumError.nppiMaximumError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMaximumError_32sc_C4R", status));
buffer.Dispose();
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// image maximum error.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
/// <param name="buffer">Pointer to the user-allocated scratch buffer required for the MaxError operation.</param>
public void MaxError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError, CudaDeviceVariable<byte> buffer)
{
int bufferSize = MaxErrorGetBufferHostSize();
if (bufferSize > buffer.Size) throw new NPPException("Provided buffer is too small.");
status = NPPNativeMethods.NPPi.MaximumError.nppiMaximumError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiFilterMedian_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Device scratch buffer size (in bytes) for MaxError.
/// </summary>
/// <returns></returns>
public int MaxErrorGetBufferHostSize()
{
int bufferSize = 0;
status = NPPNativeMethods.NPPi.MaximumError.nppiMaximumErrorGetBufferHostSize_32sc_C4R(_sizeRoi, ref bufferSize);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMaximumErrorGetBufferHostSize_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
return bufferSize;
}
#endregion
#region AverageError
/// <summary>
/// image average error. User buffer is internally allocated and freed.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
public void AverageError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError)
{
int bufferSize = AverageErrorGetBufferHostSize();
CudaDeviceVariable<byte> buffer = new CudaDeviceVariable<byte>(bufferSize);
status = NPPNativeMethods.NPPi.AverageError.nppiAverageError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAverageError_32sc_C4R", status));
buffer.Dispose();
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// image average error.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
/// <param name="buffer">Pointer to the user-allocated scratch buffer required for the AverageError operation.</param>
public void AverageError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError, CudaDeviceVariable<byte> buffer)
{
int bufferSize = AverageErrorGetBufferHostSize();
if (bufferSize > buffer.Size) throw new NPPException("Provided buffer is too small.");
status = NPPNativeMethods.NPPi.AverageError.nppiAverageError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAverageError_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Device scratch buffer size (in bytes) for AverageError.
/// </summary>
/// <returns></returns>
public int AverageErrorGetBufferHostSize()
{
int bufferSize = 0;
status = NPPNativeMethods.NPPi.AverageError.nppiAverageErrorGetBufferHostSize_32sc_C4R(_sizeRoi, ref bufferSize);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAverageErrorGetBufferHostSize_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
return bufferSize;
}
#endregion
#region MaximumRelative_Error
/// <summary>
/// image maximum relative error. User buffer is internally allocated and freed.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
public void MaximumRelativeError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError)
{
int bufferSize = MaximumRelativeErrorGetBufferHostSize();
CudaDeviceVariable<byte> buffer = new CudaDeviceVariable<byte>(bufferSize);
status = NPPNativeMethods.NPPi.MaximumRelativeError.nppiMaximumRelativeError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMaximumRelativeError_32sc_C4R", status));
buffer.Dispose();
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// image maximum relative error.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
/// <param name="buffer">Pointer to the user-allocated scratch buffer required for the MaximumRelativeError operation.</param>
public void MaximumRelativeError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError, CudaDeviceVariable<byte> buffer)
{
int bufferSize = MaximumRelativeErrorGetBufferHostSize();
if (bufferSize > buffer.Size) throw new NPPException("Provided buffer is too small.");
status = NPPNativeMethods.NPPi.MaximumRelativeError.nppiMaximumRelativeError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMaximumRelativeError_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Device scratch buffer size (in bytes) for MaximumRelativeError.
/// </summary>
/// <returns></returns>
public int MaximumRelativeErrorGetBufferHostSize()
{
int bufferSize = 0;
status = NPPNativeMethods.NPPi.MaximumRelativeError.nppiMaximumRelativeErrorGetBufferHostSize_32sc_C4R(_sizeRoi, ref bufferSize);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiMaximumRelativeErrorGetBufferHostSize_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
return bufferSize;
}
#endregion
#region AverageRelative_Error
/// <summary>
/// image average relative error. User buffer is internally allocated and freed.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
public void AverageRelativeError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError)
{
int bufferSize = AverageRelativeErrorGetBufferHostSize();
CudaDeviceVariable<byte> buffer = new CudaDeviceVariable<byte>(bufferSize);
status = NPPNativeMethods.NPPi.AverageRelativeError.nppiAverageRelativeError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAverageRelativeError_32sc_C4R", status));
buffer.Dispose();
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// image average relative error.
/// </summary>
/// <param name="src2">2nd source image</param>
/// <param name="pError">Pointer to the computed error.</param>
/// <param name="buffer">Pointer to the user-allocated scratch buffer required for the AverageRelativeError operation.</param>
public void AverageRelativeError(NPPImage_32scC4 src2, CudaDeviceVariable<double> pError, CudaDeviceVariable<byte> buffer)
{
int bufferSize = AverageRelativeErrorGetBufferHostSize();
if (bufferSize > buffer.Size) throw new NPPException("Provided buffer is too small.");
status = NPPNativeMethods.NPPi.AverageRelativeError.nppiAverageRelativeError_32sc_C4R(_devPtrRoi, _pitch, src2.DevicePointerRoi, src2.Pitch, _sizeRoi, pError.DevicePointer, buffer.DevicePointer);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAverageRelativeError_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
}
/// <summary>
/// Device scratch buffer size (in bytes) for AverageRelativeError.
/// </summary>
/// <returns></returns>
public int AverageRelativeErrorGetBufferHostSize()
{
int bufferSize = 0;
status = NPPNativeMethods.NPPi.AverageRelativeError.nppiAverageRelativeErrorGetBufferHostSize_32sc_C4R(_sizeRoi, ref bufferSize);
Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiAverageRelativeErrorGetBufferHostSize_32sc_C4R", status));
NPPException.CheckNppStatus(status, this);
return bufferSize;
}
#endregion
}
}
| 47.327742 | 198 | 0.719921 | [
"MIT"
] | SciSharp/SiaNet | Library/ManagedCuda/NPP/NPPImage_32scC4.cs | 36,681 | C# |
using System;
using UnityEngine;
namespace DialogSystem.Scripts
{
public class InteractableFlag : MonoBehaviour
{
private Transform mainCamera;
public GameObject characterGameObject;
public void SetInteractable(bool value)
{
gameObject.SetActive(value);
}
private void Start()
{
mainCamera = Camera.main?.transform;
}
private void Update()
{
if (!mainCamera)
return;
var pos = new Vector3(mainCamera.position.x, transform.position.y, mainCamera.position.z);
transform.LookAt(pos);
}
}
} | 23 | 102 | 0.575712 | [
"Unlicense"
] | LaudateCorpus1/distributed-architecture-of-moba-game-server | PurificationPioneer/Assets/3rd/DialogSystem/Scripts/InteractableFlag.cs | 669 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace DeathBlossom
{
class Gunstar
{
Texture2D gunstarTex;
Rectangle gunstarRect;
Vector2 gunstarCenter;
Boolean isFiring;
double heading;
int fireCounter;
Random rand;
public double Heading
{
get
{
return heading;
}
}
public Boolean IsFiring
{
get
{
return isFiring;
}
}
public Vector2 Location
{
get
{
return gunstarCenter;
}
}
public Gunstar(Texture2D texture, Rectangle location)
{
gunstarTex = texture;
gunstarRect = location;
gunstarCenter = new Vector2(gunstarRect.X + gunstarRect.Width / 2,
gunstarRect.Y + gunstarRect.Height / 2);
isFiring = false;
heading = 0;
fireCounter = 0;
rand = new Random();
}
public void fire()
{
isFiring = true;
}
public void Update(GameTime gameTime)
{
if(isFiring)
{
fireCounter++;
if (fireCounter < 600)
{
double multiplier = (fireCounter / 600.0) * 3;
heading = (heading + rand.NextDouble() * multiplier) % 360;
}
else
{
isFiring = false;
fireCounter = 0;
heading = 0;
}
}
}
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
spriteBatch.Draw(gunstarTex, gunstarCenter, null, Color.White,
(float)heading,
new Vector2(gunstarTex.Width/2, gunstarTex.Height/2), 0.2f,
SpriteEffects.None, 0);
}
}
}
| 25.615385 | 80 | 0.486915 | [
"Unlicense"
] | hetkpatel/Video-Game-Design | DeathBlossom/DeathBlossom/DeathBlossom/Gunstar.cs | 2,333 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.AI.MetricsAdvisor.Models
{
internal partial class MongoDBDataFeed : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("dataSourceParameter");
writer.WriteObjectValue(DataSourceParameter);
writer.WritePropertyName("dataSourceType");
writer.WriteStringValue(DataSourceType.ToString());
writer.WritePropertyName("dataFeedName");
writer.WriteStringValue(DataFeedName);
if (Optional.IsDefined(DataFeedDescription))
{
writer.WritePropertyName("dataFeedDescription");
writer.WriteStringValue(DataFeedDescription);
}
writer.WritePropertyName("granularityName");
writer.WriteStringValue(GranularityName.ToString());
if (Optional.IsDefined(GranularityAmount))
{
if (GranularityAmount != null)
{
writer.WritePropertyName("granularityAmount");
writer.WriteNumberValue(GranularityAmount.Value);
}
else
{
writer.WriteNull("granularityAmount");
}
}
writer.WritePropertyName("metrics");
writer.WriteStartArray();
foreach (var item in Metrics)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
if (Optional.IsCollectionDefined(Dimension))
{
writer.WritePropertyName("dimension");
writer.WriteStartArray();
foreach (var item in Dimension)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
if (Optional.IsDefined(TimestampColumn))
{
writer.WritePropertyName("timestampColumn");
writer.WriteStringValue(TimestampColumn);
}
writer.WritePropertyName("dataStartFrom");
writer.WriteStringValue(DataStartFrom, "O");
if (Optional.IsDefined(StartOffsetInSeconds))
{
writer.WritePropertyName("startOffsetInSeconds");
writer.WriteNumberValue(StartOffsetInSeconds.Value);
}
if (Optional.IsDefined(MaxConcurrency))
{
writer.WritePropertyName("maxConcurrency");
writer.WriteNumberValue(MaxConcurrency.Value);
}
if (Optional.IsDefined(MinRetryIntervalInSeconds))
{
writer.WritePropertyName("minRetryIntervalInSeconds");
writer.WriteNumberValue(MinRetryIntervalInSeconds.Value);
}
if (Optional.IsDefined(StopRetryAfterInSeconds))
{
writer.WritePropertyName("stopRetryAfterInSeconds");
writer.WriteNumberValue(StopRetryAfterInSeconds.Value);
}
if (Optional.IsDefined(NeedRollup))
{
writer.WritePropertyName("needRollup");
writer.WriteStringValue(NeedRollup.Value.ToString());
}
if (Optional.IsDefined(RollUpMethod))
{
writer.WritePropertyName("rollUpMethod");
writer.WriteStringValue(RollUpMethod.Value.ToString());
}
if (Optional.IsCollectionDefined(RollUpColumns))
{
writer.WritePropertyName("rollUpColumns");
writer.WriteStartArray();
foreach (var item in RollUpColumns)
{
writer.WriteStringValue(item);
}
writer.WriteEndArray();
}
if (Optional.IsDefined(AllUpIdentification))
{
writer.WritePropertyName("allUpIdentification");
writer.WriteStringValue(AllUpIdentification);
}
if (Optional.IsDefined(FillMissingPointType))
{
writer.WritePropertyName("fillMissingPointType");
writer.WriteStringValue(FillMissingPointType.Value.ToString());
}
if (Optional.IsDefined(FillMissingPointValue))
{
writer.WritePropertyName("fillMissingPointValue");
writer.WriteNumberValue(FillMissingPointValue.Value);
}
if (Optional.IsDefined(ViewMode))
{
writer.WritePropertyName("viewMode");
writer.WriteStringValue(ViewMode.Value.ToString());
}
if (Optional.IsCollectionDefined(Admins))
{
writer.WritePropertyName("admins");
writer.WriteStartArray();
foreach (var item in Admins)
{
writer.WriteStringValue(item);
}
writer.WriteEndArray();
}
if (Optional.IsCollectionDefined(Viewers))
{
writer.WritePropertyName("viewers");
writer.WriteStartArray();
foreach (var item in Viewers)
{
writer.WriteStringValue(item);
}
writer.WriteEndArray();
}
if (Optional.IsDefined(ActionLinkTemplate))
{
writer.WritePropertyName("actionLinkTemplate");
writer.WriteStringValue(ActionLinkTemplate);
}
writer.WriteEndObject();
}
internal static MongoDBDataFeed DeserializeMongoDBDataFeed(JsonElement element)
{
MongoDBParameter dataSourceParameter = default;
DataFeedSourceType dataSourceType = default;
Optional<string> dataFeedId = default;
string dataFeedName = default;
Optional<string> dataFeedDescription = default;
DataFeedGranularityType granularityName = default;
Optional<int?> granularityAmount = default;
IList<DataFeedMetric> metrics = default;
Optional<IList<MetricDimension>> dimension = default;
Optional<string> timestampColumn = default;
DateTimeOffset dataStartFrom = default;
Optional<long> startOffsetInSeconds = default;
Optional<int> maxConcurrency = default;
Optional<long> minRetryIntervalInSeconds = default;
Optional<long> stopRetryAfterInSeconds = default;
Optional<DataFeedRollupType> needRollup = default;
Optional<DataFeedAutoRollupMethod> rollUpMethod = default;
Optional<IList<string>> rollUpColumns = default;
Optional<string> allUpIdentification = default;
Optional<DataFeedMissingDataPointFillType> fillMissingPointType = default;
Optional<double> fillMissingPointValue = default;
Optional<DataFeedAccessMode> viewMode = default;
Optional<IList<string>> admins = default;
Optional<IList<string>> viewers = default;
Optional<bool> isAdmin = default;
Optional<string> creator = default;
Optional<DataFeedStatus> status = default;
Optional<DateTimeOffset> createdTime = default;
Optional<string> actionLinkTemplate = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("dataSourceParameter"))
{
dataSourceParameter = MongoDBParameter.DeserializeMongoDBParameter(property.Value);
continue;
}
if (property.NameEquals("dataSourceType"))
{
dataSourceType = new DataFeedSourceType(property.Value.GetString());
continue;
}
if (property.NameEquals("dataFeedId"))
{
dataFeedId = property.Value.GetString();
continue;
}
if (property.NameEquals("dataFeedName"))
{
dataFeedName = property.Value.GetString();
continue;
}
if (property.NameEquals("dataFeedDescription"))
{
dataFeedDescription = property.Value.GetString();
continue;
}
if (property.NameEquals("granularityName"))
{
granularityName = new DataFeedGranularityType(property.Value.GetString());
continue;
}
if (property.NameEquals("granularityAmount"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
granularityAmount = null;
continue;
}
granularityAmount = property.Value.GetInt32();
continue;
}
if (property.NameEquals("metrics"))
{
List<DataFeedMetric> array = new List<DataFeedMetric>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(DataFeedMetric.DeserializeDataFeedMetric(item));
}
metrics = array;
continue;
}
if (property.NameEquals("dimension"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
List<MetricDimension> array = new List<MetricDimension>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(MetricDimension.DeserializeMetricDimension(item));
}
dimension = array;
continue;
}
if (property.NameEquals("timestampColumn"))
{
timestampColumn = property.Value.GetString();
continue;
}
if (property.NameEquals("dataStartFrom"))
{
dataStartFrom = property.Value.GetDateTimeOffset("O");
continue;
}
if (property.NameEquals("startOffsetInSeconds"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
startOffsetInSeconds = property.Value.GetInt64();
continue;
}
if (property.NameEquals("maxConcurrency"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
maxConcurrency = property.Value.GetInt32();
continue;
}
if (property.NameEquals("minRetryIntervalInSeconds"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
minRetryIntervalInSeconds = property.Value.GetInt64();
continue;
}
if (property.NameEquals("stopRetryAfterInSeconds"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
stopRetryAfterInSeconds = property.Value.GetInt64();
continue;
}
if (property.NameEquals("needRollup"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
needRollup = new DataFeedRollupType(property.Value.GetString());
continue;
}
if (property.NameEquals("rollUpMethod"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
rollUpMethod = new DataFeedAutoRollupMethod(property.Value.GetString());
continue;
}
if (property.NameEquals("rollUpColumns"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
List<string> array = new List<string>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(item.GetString());
}
rollUpColumns = array;
continue;
}
if (property.NameEquals("allUpIdentification"))
{
allUpIdentification = property.Value.GetString();
continue;
}
if (property.NameEquals("fillMissingPointType"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
fillMissingPointType = new DataFeedMissingDataPointFillType(property.Value.GetString());
continue;
}
if (property.NameEquals("fillMissingPointValue"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
fillMissingPointValue = property.Value.GetDouble();
continue;
}
if (property.NameEquals("viewMode"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
viewMode = new DataFeedAccessMode(property.Value.GetString());
continue;
}
if (property.NameEquals("admins"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
List<string> array = new List<string>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(item.GetString());
}
admins = array;
continue;
}
if (property.NameEquals("viewers"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
List<string> array = new List<string>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(item.GetString());
}
viewers = array;
continue;
}
if (property.NameEquals("isAdmin"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
isAdmin = property.Value.GetBoolean();
continue;
}
if (property.NameEquals("creator"))
{
creator = property.Value.GetString();
continue;
}
if (property.NameEquals("status"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
status = new DataFeedStatus(property.Value.GetString());
continue;
}
if (property.NameEquals("createdTime"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
createdTime = property.Value.GetDateTimeOffset("O");
continue;
}
if (property.NameEquals("actionLinkTemplate"))
{
actionLinkTemplate = property.Value.GetString();
continue;
}
}
return new MongoDBDataFeed(dataSourceType, dataFeedId.Value, dataFeedName, dataFeedDescription.Value, granularityName, Optional.ToNullable(granularityAmount), metrics, Optional.ToList(dimension), timestampColumn.Value, dataStartFrom, Optional.ToNullable(startOffsetInSeconds), Optional.ToNullable(maxConcurrency), Optional.ToNullable(minRetryIntervalInSeconds), Optional.ToNullable(stopRetryAfterInSeconds), Optional.ToNullable(needRollup), Optional.ToNullable(rollUpMethod), Optional.ToList(rollUpColumns), allUpIdentification.Value, Optional.ToNullable(fillMissingPointType), Optional.ToNullable(fillMissingPointValue), Optional.ToNullable(viewMode), Optional.ToList(admins), Optional.ToList(viewers), Optional.ToNullable(isAdmin), creator.Value, Optional.ToNullable(status), Optional.ToNullable(createdTime), actionLinkTemplate.Value, dataSourceParameter);
}
}
}
| 42.855556 | 871 | 0.499456 | [
"MIT"
] | KalyanChanumolu-MSFT/azure-sdk-for-net | sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Generated/Models/MongoDBDataFeed.Serialization.cs | 19,285 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the migrationhubstrategy-2020-02-19.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MigrationHubStrategyRecommendations.Model
{
/// <summary>
/// Information of the transformation tool that can be used to migrate and modernize
/// the application.
/// </summary>
public partial class TransformationTool
{
private string _description;
private TransformationToolName _name;
private string _tranformationToolInstallationLink;
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// Description of the tool.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// Name of the tool.
/// </para>
/// </summary>
public TransformationToolName Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property TranformationToolInstallationLink.
/// <para>
/// URL for installing the tool.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string TranformationToolInstallationLink
{
get { return this._tranformationToolInstallationLink; }
set { this._tranformationToolInstallationLink = value; }
}
// Check to see if TranformationToolInstallationLink property is set
internal bool IsSetTranformationToolInstallationLink()
{
return this._tranformationToolInstallationLink != null;
}
}
} | 30.234694 | 118 | 0.618967 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/MigrationHubStrategyRecommendations/Generated/Model/TransformationTool.cs | 2,963 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using Feedbook.Services;
using Feedbook.Helper;
namespace Feedbook.Sync
{
public class FeedSynchronizer : ISynchronizer
{
private DispatcherTimer feedSynchronizer = new DispatcherTimer();
public FeedSynchronizer()
{
this.feedSynchronizer.Interval = Constants.SysConfig.SynchronizeInterval;
this.feedSynchronizer.Tick += new EventHandler(OnTick);
}
#region ISynchronizer Members
public void Start()
{
this.feedSynchronizer.Start();
}
public void Stop()
{
this.feedSynchronizer.Stop();
}
#endregion
private void OnTick(object sender, EventArgs e)
{
this.Sychronize();
}
private void Sychronize()
{
try
{
foreach (var channel in DataStore.Channels)
SocialService.GetSocialService(null).AsyncUpdate(channel);
foreach (var account in DataStore.TwitterAccounts)
{
var service = SocialService.GetSocialService(account);
foreach (var channel in account.Channels)
service.AsyncUpdate(channel);
}
foreach (var account in DataStore.GBuzzAccounts)
{
var service = SocialService.GetSocialService(account);
foreach (var channel in account.Channels)
service.AsyncUpdate(channel);
}
}
catch (Exception ex)
{
this.LogAndNotify("Feed Synchronization failed!", ex);
}
}
}
}
| 27.782609 | 86 | 0.529995 | [
"BSD-2-Clause"
] | mysteryjeans/Feedbook | Feedbook/Sync/FeedSynchronizer.cs | 1,919 | C# |
using System;
namespace StreamPerfConsole
{
static class Program
{
static void Main(string[] args)
{
bool continu = true;
while (continu)
{
Console.WriteLine("Choose your test:");
Console.WriteLine(" -> perf test press '1',");
Console.WriteLine(" -> thread test press '2',");
Console.WriteLine(" -> quit press 'q'.");
var k = Console.ReadKey();
Console.WriteLine(Environment.NewLine);
switch (k.KeyChar)
{
case '1':
StreamPT.DoPT();
break;
case '2':
pStreamPT.ThreadTest();
break;
case 'q':
continu = false;
break;
}
}
}
}
}
| 27.657143 | 64 | 0.375 | [
"MIT"
] | GaelOn/Stream | StreamPerfConsole/Program.cs | 970 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MxNet.SciKit.Ensemble.HistGradientBoosting
{
class LeastAbsoluteDeviation
{
}
}
| 15.545455 | 52 | 0.760234 | [
"Apache-2.0"
] | SciSharp/MxNet.Sharp | src/MxNet.Scikit/Ensemble/HistGradientBoosting/LeastAbsoluteDeviation.cs | 173 | C# |
// ****************************************************************
// Copyright 2010, Charlie Poole, Rob Prouse
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
namespace NUnit.Framework.Constraints
{
public class ToStringTests
{
[Test]
public void CanDisplaySimpleConstraints_Unresolved()
{
Assert.That(Is.EqualTo(5).ToString(), Is.EqualTo("<equal 5>"));
Assert.That(Has.Property("X").ToString(), Is.EqualTo("<propertyexists X>"));
Assert.That(Has.Attribute(typeof(TestAttribute)).ToString(),
Is.EqualTo("<attributeexists NUnit.Framework.TestAttribute>"));
}
[Test]
public void CanDisplaySimpleConstraints_Resolved()
{
IResolveConstraint constraint = Is.EqualTo(5);
Assert.That(constraint.Resolve().ToString(), Is.EqualTo("<equal 5>"));
constraint = Has.Property("X");
Assert.That(constraint.Resolve().ToString(), Is.EqualTo("<propertyexists X>"));
constraint = Has.Attribute(typeof(TestAttribute)).With.Property("Description").EqualTo("smoke");
Assert.That(constraint.Resolve().ToString(),
Is.EqualTo("<attribute NUnit.Framework.TestAttribute <property Description <equal \"smoke\">>>"));
}
[Test]
public void DisplayPrefixConstraints_Unresolved()
{
Assert.That(Is.Not.EqualTo(5).ToString(), Is.EqualTo("<unresolved <equal 5>>"));
Assert.That(Is.Not.All.EqualTo(5).ToString(), Is.EqualTo("<unresolved <equal 5>>"));
Assert.That(Has.Property("X").EqualTo(5).ToString(), Is.EqualTo("<unresolved <equal 5>>"));
Assert.That(Has.Attribute(typeof(TestAttribute)).With.Property("Description").EqualTo("smoke").ToString(),
Is.EqualTo("<unresolved <equal \"smoke\">>"));
}
[Test]
public void CanDisplayPrefixConstraints_Resolved()
{
IResolveConstraint constraint = Is.Not.EqualTo(5);
Assert.That(constraint.Resolve().ToString(), Is.EqualTo("<not <equal 5>>"));
constraint = Is.Not.All.EqualTo(5);
Assert.That(constraint.Resolve().ToString(), Is.EqualTo("<not <all <equal 5>>>"));
constraint = Has.Property("X").EqualTo(5);
Assert.That(constraint.Resolve().ToString(), Is.EqualTo("<property X <equal 5>>"));
}
[Test]
public void DisplayBinaryConstraints_Resolved()
{
IResolveConstraint constraint = Is.GreaterThan(0).And.LessThan(100);
Assert.That(constraint.Resolve().ToString(), Is.EqualTo("<and <greaterthan 0> <lessthan 100>>"));
}
[Test]
public void DisplayBinaryConstraints_UnResolved()
{
IResolveConstraint constraint = Is.GreaterThan(0).And.LessThan(100);
Assert.That(constraint.ToString(), Is.EqualTo("<unresolved <lessthan 100>>"));
}
}
}
| 44.728571 | 118 | 0.586394 | [
"MIT"
] | Acidburn0zzz/nunit | src/NUnitFramework/tests/Constraints/ToStringTests.cs | 3,133 | C# |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Bb.Galileo.Files.Datas
{
public class Entities<T> : List<T>, IDocumentReferential
where T : ReferentialBase
{
[JsonRequired]
public string Target { get; set; }
public bool HasChangedOnLoading { get; internal set; }
}
}
| 17.684211 | 62 | 0.657738 | [
"MIT"
] | gaelgael5/galileo | src/ApplicationCooperationViewPoint/Black.Beard.Galileo.Tools/Referentials/Files/Datas/Entities.cs | 338 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
#nullable disable
namespace T0001
{
public partial class DatecodeStockCurrentDetail
{
public string Ids { get; set; }
public string Id { get; set; }
public decimal? Datecode { get; set; }
public decimal? Qty { get; set; }
public string Createuser { get; set; }
public DateTime? Createdate { get; set; }
public string Lockuser { get; set; }
public DateTime? Locktime { get; set; }
}
} | 31.25 | 97 | 0.6192 | [
"MIT"
] | twoutlook/BlazorServerDbContextExample | BlazorServerEFCoreSample/T0001/DatecodeStockCurrentDetail.cs | 627 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Model
{
/// <summary>
/// OnlineTimesOnDay Data Structure.
/// </summary>
[Serializable]
public class OnlineTimesOnDay
{
/// <summary>
/// 在线日期
/// </summary>
[XmlElement("online_date")]
public string OnlineDate { get; set; }
/// <summary>
/// 在线时长列表
/// </summary>
[XmlArray("online_time_by_ids")]
[XmlArrayItem("online_time_by_id")]
public List<OnlineTimeById> OnlineTimeByIds { get; set; }
}
}
| 22.444444 | 65 | 0.577558 | [
"MIT"
] | objectyan/MyTools | OY.Solution/Model/OnlineTimesOnDay.cs | 626 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace ABPProject.Migrations
{
public partial class Upgraded_To_Abp_4_7_0 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_AbpSettings_TenantId_Name",
table: "AbpSettings");
migrationBuilder.CreateIndex(
name: "IX_AbpSettings_TenantId_Name_UserId",
table: "AbpSettings",
columns: new[] { "TenantId", "Name", "UserId" },
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_AbpSettings_TenantId_Name_UserId",
table: "AbpSettings");
migrationBuilder.CreateIndex(
name: "IX_AbpSettings_TenantId_Name",
table: "AbpSettings",
columns: new[] { "TenantId", "Name" });
}
}
}
| 31.575758 | 71 | 0.577735 | [
"MIT"
] | Ryan2017-mjp/MyABPProject | aspnet-core/src/ABPProject.EntityFrameworkCore/Migrations/20190703062215_Upgraded_To_Abp_4_7_0.cs | 1,044 | C# |
using System;
namespace WhatsNewInCSharp6
{
/// <summary>
/// - Expression bodies on method-like members
/// - Expression bodies on property-like function members
/// </summary>
public class Person
{
private readonly string first;
private readonly string last;
public Person(string first, string last, uint age)
{
Age = age;
this.last = last;
this.first = first;
}
public uint Age { get; }
public string Name => first + " " + last;
public static implicit operator string(Person p) => p.Name + " " + p.Age;
public static Person operator ++(Person p) => new Person(p.first, p.last, p.Age + 1);
// Must be a statement expression in methods returning void or Task
public void Print() => Console.WriteLine(this);
public static Person Runar => new Person("Runar", "Hjerpbakk", 32);
}
} | 28.117647 | 93 | 0.582636 | [
"MIT"
] | Sankra/WhatsNewInCSharp6 | WhatsNewInCSharp6/ExpressionBodiedMemberExample.cs | 958 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NPay.Modules.Wallets.Infrastructure.DAL;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace NPay.Modules.Wallets.Infrastructure.DAL.Migrations
{
[DbContext(typeof(WalletsDbContext))]
partial class WalletsDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("wallets")
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.11")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
modelBuilder.Entity("NPay.Modules.Wallets.Core.Owners.Aggregates.Owner", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("FullName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Nationality")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime?>("VerifiedAt")
.HasColumnType("timestamp without time zone");
b.Property<int>("Version")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Owners");
});
modelBuilder.Entity("NPay.Modules.Wallets.Core.Wallets.Aggregates.Wallet", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("Currency")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("OwnerId")
.HasColumnType("uuid");
b.Property<int>("Version")
.IsConcurrencyToken()
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OwnerId");
b.ToTable("Wallets");
});
modelBuilder.Entity("NPay.Modules.Wallets.Core.Wallets.Entities.Transfer", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<decimal>("Amount")
.HasColumnType("numeric");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("Currency")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Direction")
.HasColumnType("integer");
b.Property<Guid?>("ReferenceId")
.HasColumnType("uuid");
b.Property<Guid>("WalletId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("WalletId");
b.ToTable("Transfers");
});
modelBuilder.Entity("NPay.Modules.Wallets.Core.Wallets.Aggregates.Wallet", b =>
{
b.HasOne("NPay.Modules.Wallets.Core.Owners.Aggregates.Owner", null)
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("NPay.Modules.Wallets.Core.Wallets.Entities.Transfer", b =>
{
b.HasOne("NPay.Modules.Wallets.Core.Wallets.Aggregates.Wallet", null)
.WithMany("Transfers")
.HasForeignKey("WalletId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("NPay.Modules.Wallets.Core.Wallets.Aggregates.Wallet", b =>
{
b.Navigation("Transfers");
});
#pragma warning restore 612, 618
}
}
}
| 35.654135 | 120 | 0.486293 | [
"MIT"
] | devmentors/NPay | src/Modules/Wallets/NPay.Modules.Wallets.Infrastructure/DAL/Migrations/WalletsDbContextModelSnapshot.cs | 4,744 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SteamSuite
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
SteamContext context = new SteamContext();
if ( !context.Initialize() )
{
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new MainForm( context ) );
}
}
}
| 21.9 | 68 | 0.517504 | [
"MIT"
] | Planimeter/hl2sb-src | src/open-steamworks/Projects/SteamSuite/SteamSuite/Program.cs | 659 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
namespace Google.Ads.GoogleAds.V9.Common
{
public partial class CallAsset
{
/// <summary>
/// <see cref="gagvr::ConversionActionName"/>-typed view over the <see cref="CallConversionAction"/> resource
/// name property.
/// </summary>
public gagvr::ConversionActionName CallConversionActionAsConversionActionName
{
get => string.IsNullOrEmpty(CallConversionAction) ? null : gagvr::ConversionActionName.Parse(CallConversionAction, allowUnparsed: true);
set => CallConversionAction = value?.ToString() ?? "";
}
}
}
| 37.529412 | 148 | 0.699843 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V9/Types/AssetTypesResourceNames.g.cs | 1,276 | C# |
using System;
using UnityEngine;
namespace E7.NotchSolution
{
[Serializable]
internal class PerEdgeValues<T>
{
[SerializeField] public T left;
[SerializeField] public T bottom;
[SerializeField] public T top;
[SerializeField] public T right;
}
} | 20.928571 | 41 | 0.65529 | [
"MIT"
] | studentutu/NotchSolution | Runtime/Base/PerEdgeValues.cs | 293 | C# |
using UnityEngine;
using System.Collections;
namespace UTJ {
[RequireComponent(typeof(MeshFilter),typeof(MeshRenderer))]
public class HahenRenderer : MonoBehaviour {
private MeshFilter mf_;
private MeshRenderer mr_;
void Start()
{
mf_ = GetComponent<MeshFilter>();
mr_ = GetComponent<MeshRenderer>();
mf_.sharedMesh = Hahen.Instance.getMesh();
mr_.sharedMaterial = Hahen.Instance.getMaterial();
}
}
} // namespace UTJ {
| 19.954545 | 59 | 0.742597 | [
"MIT"
] | Kotsuha/AnotherThread | Assets/Scripts/HahenRenderer.cs | 441 | C# |
using System.ComponentModel;
namespace Seemon.Vault.Core.Models.OpenPGP
{
public enum HashAlgorithm
{
[Description("MD5")]
MD5 = 1,
[Description("SHA-1")]
Sha1 = 2,
[Description("RIPEMD-160")]
RipeMD160 = 3,
[Description("DOUBLE-SHA")]
DoubleSha = 4,
[Description("MD2")]
MD2 = 5,
[Description("TIGER-192")]
Tiger192 = 6,
[Description("HAVAL-5-PASS-160")]
Haval5pass160 = 7,
[Description("SHA-256")]
Sha256 = 8,
[Description("SHA-384")]
Sha384 = 9,
[Description("SHA-512")]
Sha512 = 10,
[Description("SHA-224")]
Sha224 = 11
}
}
| 23.16129 | 42 | 0.508357 | [
"MIT"
] | mattseemon/Vault | src/Core/Models/OpenPGP/HashAlgorithm.cs | 720 | C# |
using System;
using System.Collections.Generic;
namespace SFA.DAS.AssessorService.Api.Types.CompaniesHouse
{
public class Officer
{
public string Id { get; set; }
public string Name { get; set; }
public string Role { get; set; }
public Address Address { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime AppointedOn { get; set; }
public DateTime? ResignedOn { get; set; }
public IEnumerable<Disqualification> Disqualifications { get; set; }
}
}
| 28.631579 | 76 | 0.639706 | [
"MIT"
] | SkillsFundingAgency/das-assessor-service | src/SFA.DAS.AssessorService.Api.Types/CompaniesHouse/Officer.cs | 546 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using UnityEngine;
namespace Cytus2.Models
{
public class Chart
{
public enum C1NoteType
{
Single,
Chain,
Hold
}
private readonly float baseSize;
private readonly float offset;
private readonly float verticalRatio;
private string checksumSource = string.Empty;
public int CurrentPageId;
private float horizontalRatio;
public float MusicOffset;
public ChartRoot Root;
public bool ScanlineSmoothing = false;
public Chart(string text, float horizontalRatio = 0.85f, float verticalRatio = 7.0f / 9.0f)
{
Root = new ChartRoot();
try
{
// C2/Cytoid format
Root = JsonConvert.DeserializeObject<ChartRoot>(text);
}
catch (JsonReaderException)
{
// C1 format
Root = FromCytus1Chart(text);
}
baseSize = Camera.main.orthographicSize;
offset = -Camera.main.orthographicSize * 0.04f;
this.horizontalRatio = horizontalRatio;
this.verticalRatio = verticalRatio;
var thisChecksumSource = string.Empty;
foreach (var tempo in Root.tempo_list)
thisChecksumSource += "tempo " + (int) tempo.tick + " " + tempo.value;
// Convert tick to absolute time
foreach (var eventOrder in Root.event_order_list) eventOrder.time = ConvertToTime(eventOrder.tick);
foreach (var anim in Root.animation_list) anim.time = ConvertToTime(anim.tick);
for (var index = 0; index < Root.page_list.Count; index++)
{
var page = Root.page_list[index];
page.start_time = ConvertToTime((float) page.start_tick);
page.end_time = ConvertToTime((float) page.end_tick);
thisChecksumSource += "page " + (int) page.start_tick + " " +
(int) page.end_tick;
if (index != 0)
{
page.actual_start_tick = (float) Root.page_list[index - 1].end_tick;
page.actual_start_time = Root.page_list[index - 1].end_time;
}
else
{
page.actual_start_tick = 0;
page.actual_start_time = 0;
}
if (Mod.FlipY.IsEnabled() || Mod.FlipAll.IsEnabled())
page.scan_line_direction = page.scan_line_direction == 1 ? -1 : 1;
}
for (var i = 0; i < Root.note_list.Count; i++)
{
var note = Root.note_list[i];
var page = Root.page_list[note.page_index];
note.direction = page.scan_line_direction;
note.speed = note.page_index == 0 ? 1.0f : CalculateNoteSpeed(note);
note.speed *= (float) note.approach_rate;
var modSpeed = 1f;
if (Mod.Fast.IsEnabled()) modSpeed = 1.5f;
if (Mod.Slow.IsEnabled()) modSpeed = 0.75f;
note.speed *= modSpeed;
note.start_time = ConvertToTime((float) note.tick);
note.end_time = ConvertToTime((float) (note.tick + note.hold_tick));
var flip = Mod.FlipX.IsEnabled() || Mod.FlipAll.IsEnabled() ? -1 : 1;
note.position = new Vector3(
((float) note.x * 2 * horizontalRatio - horizontalRatio) * baseSize * Screen.width /
Screen.height
* flip,
(float) (
verticalRatio * page.scan_line_direction *
(-baseSize + 2.0f *
baseSize *
(note.tick - page.start_tick) * 1.0f /
(page.end_tick - page.start_tick))
+ offset)
);
note.end_position = new Vector3(
((float) note.x * 2 * horizontalRatio - horizontalRatio) * baseSize * Screen.width /
Screen.height
* flip,
GetNotePosition((float) (note.tick + note.hold_tick))
);
note.holdlength = (float) (verticalRatio * 2.0f * baseSize *
note.hold_tick /
(page.end_tick -
page.start_tick));
if (note.type == 3 || note.type == 4)
note.intro_time = note.start_time - 1.175f / note.speed;
else
note.intro_time = note.start_time - 1.367f / note.speed;
var lx = note.x;
if (lx != 0f)
while (Mathf.Abs((float) lx) < 10000)
lx *= 10;
thisChecksumSource += "note " + note.id + " "
+ note.page_index + " "
+ note.type + " "
+ (int) note.tick + " "
+ (int) lx + " "
+ (int) note.hold_tick + " "
+ note.next_id + " "
+ (int) (note.approach_rate * 100);
}
foreach (var note in Root.note_list)
switch (note.type)
{
case 0:
note.tint = note.direction == 1 ? 0.94f : 1.06f;
break;
case 1:
note.tint = note.direction == 1 ? 0.94f : 1.06f;
break;
case 2:
note.tint = note.direction == 1 ? 0.94f : 1.06f;
break;
case 3:
note.tint = note.direction == 1 ? 0.94f : 1.06f;
if (note.next_id > 0)
{
note.nextdraglinestarttime = note.intro_time - 0.133f;
note.nextdraglinestoptime = Root.note_list[note.next_id].intro_time - 0.132f;
}
break;
case 4:
note.tint = note.direction == 1 ? 0.94f : 1.06f;
if (note.next_id > 0)
{
note.nextdraglinestarttime = note.intro_time - 0.133f;
note.nextdraglinestoptime = Root.note_list[note.next_id].intro_time - 0.132f;
}
break;
case 5:
note.tint = note.direction == 1 ? 1.00f : 1.30f;
break;
}
foreach (var note in Root.note_list)
{
if (note.next_id <= 0) continue;
var noteThis = note;
var noteNext = Root.note_list[note.next_id];
if (noteThis.position == noteNext.position)
noteThis.rotation = 0;
else if (Math.Abs(noteThis.position.y - noteNext.position.y) < 0.000001)
noteThis.rotation = noteThis.position.x > noteNext.position.x ? -90 : 90;
else if (Math.Abs(noteThis.position.x - noteNext.position.x) < 0.000001)
noteThis.rotation = noteThis.position.y > noteNext.position.y ? 180 : 0;
else
noteThis.rotation =
Mathf.Atan((noteNext.position.x - noteThis.position.x) /
(noteNext.position.y - noteThis.position.y)) / Mathf.PI * 180f +
(noteNext.position.y > noteThis.position.y ? 0 : 180);
}
MusicOffset = (float) Root.music_offset;
// Set checksum if not a converted chart
if (checksumSource == string.Empty) checksumSource = thisChecksumSource;
}
public string Checksum
{
get { return global::Checksum.From(checksumSource); }
}
private float ConvertToTime(float tick)
{
double result = 0;
var currentTick = 0f;
var currentTimeZone = 0;
for (var i = 1; i < Root.tempo_list.Count; i++)
{
if (Root.tempo_list[i].tick >= tick) break;
result += (Root.tempo_list[i].tick - currentTick) * 1e-6 * Root.tempo_list[i - 1].value /
(float) Root.time_base;
currentTick = (float) Root.tempo_list[i].tick;
currentTimeZone++;
}
result += (tick - currentTick) * 1e-6 * Root.tempo_list[currentTimeZone].value / (float) Root.time_base;
return (float) result;
}
private int ConvertToTick(float time)
{
var currentTime = 0.0;
var currentTick = 0.0;
int i;
for (i = 1; i < Root.tempo_list.Count; i++)
{
var delta = (Root.tempo_list[i].tick - Root.tempo_list[i - 1].tick) / Root.time_base *
Root.tempo_list[i - 1].value * 1e-6;
if (currentTime + delta < time)
{
currentTime += delta;
currentTick = Root.tempo_list[i].tick;
}
else
{
break;
}
}
return Mathf.RoundToInt((float) (currentTick +
(time - currentTime) / Root.tempo_list[i - 1].value * 1e6f *
Root.time_base));
}
public float CalculateNoteSpeed(ChartNote note)
{
var page = Root.page_list[note.page_index];
var previousPage = Root.page_list[note.page_index - 1];
var pageRatio = (float) (
1.0f * (note.tick - page.actual_start_tick) /
(page.end_tick -
page.actual_start_tick));
var tempo =
(page.end_time -
page.actual_start_time) * pageRatio +
(previousPage.end_time -
previousPage.actual_start_time) * (1.367f - pageRatio);
return tempo >= 1.367f ? 1.0f : 1.367f / tempo;
}
public float GetNotePosition(float tick)
{
var targetPageId = 0;
while (targetPageId < Root.page_list.Count && tick > Root.page_list[targetPageId].end_tick)
targetPageId++;
if (targetPageId == Root.page_list.Count)
return (float) (
-verticalRatio * Root.page_list[targetPageId - 1].scan_line_direction *
(-baseSize + 2.0f *
baseSize *
(tick - Root.page_list[targetPageId - 1].end_tick) *
1.0f / (Root.page_list[targetPageId - 1].end_tick -
Root.page_list[targetPageId - 1].start_tick))
+ offset);
return (float) (
verticalRatio * Root.page_list[targetPageId].scan_line_direction *
(-baseSize + 2.0f *
baseSize * (tick - Root.page_list[targetPageId].start_tick) *
1.0f / (Root.page_list[targetPageId].end_tick - Root.page_list[targetPageId].start_tick))
+ offset);
}
public float GetScanlinePosition(float time)
{
CurrentPageId = 0;
while (CurrentPageId < Root.page_list.Count && time > Root.page_list[CurrentPageId].end_time)
CurrentPageId++;
if (CurrentPageId == Root.page_list.Count)
{
if (ScanlineSmoothing)
return (float) (-verticalRatio * Root.page_list[CurrentPageId - 1].scan_line_direction *
(-baseSize + 2.0f *
baseSize *
(ConvertToTick(time) - Root.page_list[CurrentPageId - 1].end_tick) *
1.0f / (Root.page_list[CurrentPageId - 1].end_tick -
Root.page_list[CurrentPageId - 1].start_tick))
+ offset);
return -verticalRatio * Root.page_list[CurrentPageId - 1].scan_line_direction *
(-baseSize + 2.0f *
baseSize *
(time - Root.page_list[CurrentPageId - 1].end_time) *
1.0f / (Root.page_list[CurrentPageId - 1].end_time -
Root.page_list[CurrentPageId - 1].start_time))
+ offset;
}
if (ScanlineSmoothing)
return (float) (verticalRatio * Root.page_list[CurrentPageId].scan_line_direction *
(-baseSize + 2.0f *
baseSize *
(ConvertToTick(time) - Root.page_list[CurrentPageId].start_tick) *
1.0f / (Root.page_list[CurrentPageId].end_tick -
Root.page_list[CurrentPageId].start_tick))
+ offset);
return verticalRatio * Root.page_list[CurrentPageId].scan_line_direction *
(-baseSize + 2.0f *
baseSize *
(time - Root.page_list[CurrentPageId].start_time) *
1.0f / (Root.page_list[CurrentPageId].end_time - Root.page_list[CurrentPageId].start_time))
+ offset;
}
public float GetScanlinePosition01(float percentage)
{
return verticalRatio *
(-baseSize + 2.0f * baseSize * percentage)
+ offset;
}
public float GetEdgePosition(bool bottom)
{
return verticalRatio * (bottom ? 1 : -1) *
-baseSize
+ offset;
}
public ChartRoot FromCytus1Chart(string text)
{
// Parse
var pageDuration = 0f;
var pageShift = 0f;
var tmpNotes = new Dictionary<int, C1Note>();
foreach (var line in text.Split('\n'))
{
var data = line.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);
if (data.Length == 0) continue;
var type = data[0];
switch (type)
{
case "PAGE_SIZE":
pageDuration = float.Parse(data[1]);
checksumSource += data[1];
break;
case "PAGE_SHIFT":
pageShift = float.Parse(data[1]);
checksumSource += data[1];
break;
case "NOTE":
checksumSource += data[1] + data[2] + data[3] + data[4];
var note = new C1Note(int.Parse(data[1]), float.Parse(data[2]), float.Parse(data[3]),
float.Parse(data[4]), false);
tmpNotes.Add(int.Parse(data[1]), note);
if (note.Duration > 0) note.Type = C1NoteType.Hold;
break;
case "LINK":
var notesInChain = new List<C1Note>();
for (var i = 1; i < data.Length; i++)
{
if (data[i] != "LINK") checksumSource += data[i];
int id;
if (!int.TryParse(data[i], out id)) continue;
note = tmpNotes[id];
note.Type = C1NoteType.Chain;
if (!notesInChain.Contains(note)) notesInChain.Add(note);
}
for (var i = 0; i < notesInChain.Count - 1; i++)
notesInChain[i].ConnectedNote = notesInChain[i + 1];
notesInChain[0].IsChainHead = true;
break;
}
}
pageShift += pageDuration;
// Calculate chronological note ids
var sortedNotes = tmpNotes.Values.ToList();
sortedNotes.Sort((a, b) => a.Time.CompareTo(b.Time));
var chronologicalIds = sortedNotes.Select(note => note.OriginalId).ToList();
var notes = new Dictionary<int, C1Note>();
// Recalculate note ids from original ids
var newId = 0;
foreach (var noteId in chronologicalIds)
{
tmpNotes[noteId].Id = newId;
notes[newId] = tmpNotes[noteId];
newId++;
}
// Reset chronological ids
chronologicalIds.Clear();
for (var i = 0; i < tmpNotes.Count; i++) chronologicalIds.Add(i);
// Convert
const int timeBase = 480;
var root = new ChartRoot();
root.format_version = 0;
root.time_base = 480;
root.start_offset_time = 0;
var tempo = new ChartTempo();
tempo.tick = 0;
var tempoValue = (long) (pageDuration * 1000000f);
tempo.value = tempoValue;
root.tempo_list = new List<ChartTempo> {tempo};
if (pageShift < 0) pageShift = pageShift + 2 * pageDuration;
var pageShiftTickOffset = pageShift / pageDuration * timeBase;
var noteList = new List<ChartNote>();
var page = 0;
foreach (var note in notes.Values)
{
var obj = new ChartNote();
obj.id = note.Id;
switch (note.Type)
{
case C1NoteType.Single:
obj.type = NoteType.Click;
break;
case C1NoteType.Chain:
obj.type = note.IsChainHead ? NoteType.DragHead : NoteType.DragChild;
break;
case C1NoteType.Hold:
obj.type = NoteType.Hold;
break;
}
obj.x = note.X;
var ti = note.Time * timeBase * 1000000 / tempoValue + pageShiftTickOffset;
obj.tick = ti;
obj.hold_tick = note.Duration * timeBase * 1000000 / tempoValue;
page = Mathf.FloorToInt(ti / timeBase);
obj.page_index = page;
if (note.Type == C1NoteType.Chain)
obj.next_id = note.ConnectedNote != null ? note.ConnectedNote.Id : -1;
else
obj.next_id = 0;
if (obj.ring_color != null) obj.ParsedRingColor = Convert.HexToColor(obj.ring_color);
if (obj.fill_color != null) obj.ParsedFillColor = Convert.HexToColor(obj.fill_color);
noteList.Add(obj);
}
root.note_list = noteList;
var pageList = new List<ChartPage>();
var direction = false;
var t = 0;
for (var i = 0; i <= page; i++)
{
var obj = new ChartPage();
obj.scan_line_direction = direction ? 1 : -1;
direction = !direction;
obj.start_tick = t;
t += timeBase;
obj.end_tick = t;
pageList.Add(obj);
}
root.page_list = pageList;
root.music_offset = pageShiftTickOffset / timeBase / 1000000 * tempoValue;
return root;
}
[Serializable]
public class C1Note
{
[NonSerialized] public C1Note ConnectedNote;
public float Duration;
public int Id;
public bool IsChainHead;
public int OriginalId;
public float Time;
public C1NoteType Type = C1NoteType.Single;
public float X;
public C1Note(int originalId, float time, float x, float duration, bool isChainHead)
{
OriginalId = originalId;
Time = time;
X = x;
Duration = duration;
IsChainHead = isChainHead;
}
}
}
} | 39.773333 | 116 | 0.459844 | [
"MIT"
] | imgradeone/Cytoid | Assets/Scripts/Cytus2/Models/Chart.cs | 20,883 | C# |
using System;
using System.Collections.Generic;
using VPX.Enums;
namespace VPX.ApiModels
{
public class KnowledgeQuestionModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public ControlType ControlType { get; set; }
public Guid? AnswerId { get; set; }
public List<KnowledgeAnswerModel> Answers { get; set; }
}
}
| 24.125 | 63 | 0.642487 | [
"MIT"
] | VadimProkopchuk/JML | src/VPX.ApiModels/KnowledgeQuestionModel.cs | 388 | C# |
using JetBrains.Annotations;
using JsonApiDotNetCore.Resources.Annotations;
namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceInheritance;
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
public sealed class FamilyHealthInsurance : HealthInsurance
{
[Attr]
public int PermittedFamilySize { get; set; }
}
| 26.833333 | 70 | 0.829193 | [
"MIT"
] | damien-rousseau/JsonApiDotNetCore_Polymorphism | test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/FamilyHealthInsurance.cs | 322 | C# |
namespace LMAOSoft.Inc.Forms.Tools.Game_Info
{
partial class frm_game_info_multiple
{
/// <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();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.pb_package = new System.Windows.Forms.PictureBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.pb_content = new System.Windows.Forms.PictureBox();
this.tb_fullDirectory = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.lbl_rootFolder = new System.Windows.Forms.Label();
this.tb_deviceID = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.tb_titleName = new System.Windows.Forms.TextBox();
this.lbl_subFolder = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.lbl_titleFolder = new System.Windows.Forms.Label();
this.tb_consoleID = new System.Windows.Forms.TextBox();
this.tb_profileID = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.tb_display = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.tb_titleID = new System.Windows.Forms.TextBox();
this.lv_main = new System.Windows.Forms.ListView();
this.ch_title = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.ch_title_name = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.ch_status = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.cms_game_info = new System.Windows.Forms.ContextMenuStrip(this.components);
this.tsmi_select_all = new System.Windows.Forms.ToolStripMenuItem();
this.tsmi_send = new System.Windows.Forms.ToolStripMenuItem();
this.tsmi_send_selected = new System.Windows.Forms.ToolStripMenuItem();
this.tsmi_send_all = new System.Windows.Forms.ToolStripMenuItem();
this.tsmi_remove = new System.Windows.Forms.ToolStripMenuItem();
this.tsmi_remove_all = new System.Windows.Forms.ToolStripMenuItem();
this.ch_hash = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.ch_revision = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.tsmi_remove_duplicates = new System.Windows.Forms.ToolStripMenuItem();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pb_package)).BeginInit();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pb_content)).BeginInit();
this.cms_game_info.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Controls.Add(this.groupBox3);
this.groupBox1.Controls.Add(this.tb_fullDirectory);
this.groupBox1.Controls.Add(this.label8);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.lbl_rootFolder);
this.groupBox1.Controls.Add(this.tb_deviceID);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.tb_titleName);
this.groupBox1.Controls.Add(this.lbl_subFolder);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.label10);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.lbl_titleFolder);
this.groupBox1.Controls.Add(this.tb_consoleID);
this.groupBox1.Controls.Add(this.tb_profileID);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.tb_display);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.tb_titleID);
this.groupBox1.Location = new System.Drawing.Point(12, 290);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(484, 272);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Information";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.pb_package);
this.groupBox2.Location = new System.Drawing.Point(367, 146);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(102, 109);
this.groupBox2.TabIndex = 67;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Package Picture";
//
// pb_package
//
this.pb_package.Image = global::LMAOSoft.Properties.Resources.empty;
this.pb_package.Location = new System.Drawing.Point(11, 19);
this.pb_package.Name = "pb_package";
this.pb_package.Size = new System.Drawing.Size(80, 80);
this.pb_package.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pb_package.TabIndex = 43;
this.pb_package.TabStop = false;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.pb_content);
this.groupBox3.Location = new System.Drawing.Point(367, 31);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(102, 109);
this.groupBox3.TabIndex = 66;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Content Picture";
//
// pb_content
//
this.pb_content.Image = global::LMAOSoft.Properties.Resources.empty;
this.pb_content.Location = new System.Drawing.Point(11, 19);
this.pb_content.Name = "pb_content";
this.pb_content.Size = new System.Drawing.Size(80, 80);
this.pb_content.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pb_content.TabIndex = 42;
this.pb_content.TabStop = false;
//
// tb_fullDirectory
//
this.tb_fullDirectory.BackColor = System.Drawing.SystemColors.Control;
this.tb_fullDirectory.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.tb_fullDirectory.Location = new System.Drawing.Point(85, 247);
this.tb_fullDirectory.Name = "tb_fullDirectory";
this.tb_fullDirectory.ReadOnly = true;
this.tb_fullDirectory.Size = new System.Drawing.Size(272, 13);
this.tb_fullDirectory.TabIndex = 65;
this.tb_fullDirectory.Text = "N/A";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(14, 247);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(71, 13);
this.label8.TabIndex = 64;
this.label8.Text = "Full Directory:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(10, 25);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(75, 13);
this.label1.TabIndex = 46;
this.label1.Text = "Display Name:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(27, 77);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(58, 13);
this.label4.TabIndex = 52;
this.label4.Text = "Device ID:";
//
// lbl_rootFolder
//
this.lbl_rootFolder.AutoSize = true;
this.lbl_rootFolder.Location = new System.Drawing.Point(82, 181);
this.lbl_rootFolder.Name = "lbl_rootFolder";
this.lbl_rootFolder.Size = new System.Drawing.Size(27, 13);
this.lbl_rootFolder.TabIndex = 63;
this.lbl_rootFolder.Text = "N/A";
//
// tb_deviceID
//
this.tb_deviceID.Enabled = false;
this.tb_deviceID.Location = new System.Drawing.Point(91, 74);
this.tb_deviceID.MaxLength = 40;
this.tb_deviceID.Name = "tb_deviceID";
this.tb_deviceID.ReadOnly = true;
this.tb_deviceID.Size = new System.Drawing.Size(266, 20);
this.tb_deviceID.TabIndex = 53;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(20, 181);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(65, 13);
this.label9.TabIndex = 62;
this.label9.Text = "Root Folder:";
//
// tb_titleName
//
this.tb_titleName.Enabled = false;
this.tb_titleName.Location = new System.Drawing.Point(91, 48);
this.tb_titleName.Name = "tb_titleName";
this.tb_titleName.ReadOnly = true;
this.tb_titleName.Size = new System.Drawing.Size(266, 20);
this.tb_titleName.TabIndex = 51;
//
// lbl_subFolder
//
this.lbl_subFolder.AutoSize = true;
this.lbl_subFolder.Location = new System.Drawing.Point(82, 225);
this.lbl_subFolder.Name = "lbl_subFolder";
this.lbl_subFolder.Size = new System.Drawing.Size(27, 13);
this.lbl_subFolder.TabIndex = 61;
this.lbl_subFolder.Text = "N/A";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(23, 129);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(62, 13);
this.label5.TabIndex = 54;
this.label5.Text = "Console ID:";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(24, 225);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(61, 13);
this.label10.TabIndex = 60;
this.label10.Text = "Sub Folder:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(24, 51);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(61, 13);
this.label3.TabIndex = 50;
this.label3.Text = "Title Name:";
//
// lbl_titleFolder
//
this.lbl_titleFolder.AutoSize = true;
this.lbl_titleFolder.Location = new System.Drawing.Point(82, 203);
this.lbl_titleFolder.Name = "lbl_titleFolder";
this.lbl_titleFolder.Size = new System.Drawing.Size(27, 13);
this.lbl_titleFolder.TabIndex = 59;
this.lbl_titleFolder.Text = "N/A";
//
// tb_consoleID
//
this.tb_consoleID.Enabled = false;
this.tb_consoleID.Location = new System.Drawing.Point(91, 126);
this.tb_consoleID.MaxLength = 8;
this.tb_consoleID.Name = "tb_consoleID";
this.tb_consoleID.ReadOnly = true;
this.tb_consoleID.Size = new System.Drawing.Size(266, 20);
this.tb_consoleID.TabIndex = 55;
//
// tb_profileID
//
this.tb_profileID.Enabled = false;
this.tb_profileID.Location = new System.Drawing.Point(91, 100);
this.tb_profileID.MaxLength = 14;
this.tb_profileID.Name = "tb_profileID";
this.tb_profileID.ReadOnly = true;
this.tb_profileID.Size = new System.Drawing.Size(266, 20);
this.tb_profileID.TabIndex = 49;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(23, 203);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(62, 13);
this.label7.TabIndex = 58;
this.label7.Text = "Title Folder:";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(41, 155);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(44, 13);
this.label6.TabIndex = 56;
this.label6.Text = "Title ID:";
//
// tb_display
//
this.tb_display.Enabled = false;
this.tb_display.Location = new System.Drawing.Point(91, 22);
this.tb_display.Name = "tb_display";
this.tb_display.ReadOnly = true;
this.tb_display.Size = new System.Drawing.Size(266, 20);
this.tb_display.TabIndex = 47;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(32, 103);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 13);
this.label2.TabIndex = 48;
this.label2.Text = "Profile ID:";
//
// tb_titleID
//
this.tb_titleID.Enabled = false;
this.tb_titleID.Location = new System.Drawing.Point(91, 152);
this.tb_titleID.MaxLength = 8;
this.tb_titleID.Name = "tb_titleID";
this.tb_titleID.ReadOnly = true;
this.tb_titleID.Size = new System.Drawing.Size(266, 20);
this.tb_titleID.TabIndex = 57;
//
// lv_main
//
this.lv_main.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lv_main.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.ch_title,
this.ch_title_name,
this.ch_status,
this.ch_hash,
this.ch_revision});
this.lv_main.FullRowSelect = true;
this.lv_main.GridLines = true;
this.lv_main.Location = new System.Drawing.Point(12, 12);
this.lv_main.Name = "lv_main";
this.lv_main.Size = new System.Drawing.Size(484, 272);
this.lv_main.TabIndex = 1;
this.lv_main.UseCompatibleStateImageBehavior = false;
this.lv_main.View = System.Windows.Forms.View.Details;
this.lv_main.DoubleClick += new System.EventHandler(this.lv_main_DoubleClick);
this.lv_main.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lv_main_MouseDown);
//
// ch_title
//
this.ch_title.Text = "Title";
this.ch_title.Width = 59;
//
// ch_title_name
//
this.ch_title_name.Text = "Title Name";
this.ch_title_name.Width = 104;
//
// ch_status
//
this.ch_status.Text = "Status";
this.ch_status.Width = 88;
//
// cms_game_info
//
this.cms_game_info.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmi_select_all,
this.tsmi_send,
this.tsmi_remove,
this.tsmi_remove_all,
this.tsmi_remove_duplicates});
this.cms_game_info.Name = "cms_game_info";
this.cms_game_info.Size = new System.Drawing.Size(169, 136);
//
// tsmi_select_all
//
this.tsmi_select_all.Name = "tsmi_select_all";
this.tsmi_select_all.Size = new System.Drawing.Size(168, 22);
this.tsmi_select_all.Text = "Select All";
this.tsmi_select_all.Click += new System.EventHandler(this.tsmi_select_all_Click);
//
// tsmi_send
//
this.tsmi_send.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmi_send_selected,
this.tsmi_send_all});
this.tsmi_send.Name = "tsmi_send";
this.tsmi_send.Size = new System.Drawing.Size(168, 22);
this.tsmi_send.Text = "Send";
//
// tsmi_send_selected
//
this.tsmi_send_selected.Name = "tsmi_send_selected";
this.tsmi_send_selected.Size = new System.Drawing.Size(152, 22);
this.tsmi_send_selected.Text = "Selected";
this.tsmi_send_selected.Click += new System.EventHandler(this.tsmi_send_selected_Click);
//
// tsmi_send_all
//
this.tsmi_send_all.Name = "tsmi_send_all";
this.tsmi_send_all.Size = new System.Drawing.Size(152, 22);
this.tsmi_send_all.Text = "All";
//
// tsmi_remove
//
this.tsmi_remove.Name = "tsmi_remove";
this.tsmi_remove.Size = new System.Drawing.Size(168, 22);
this.tsmi_remove.Text = "Remove";
this.tsmi_remove.Click += new System.EventHandler(this.tsmi_remove_Click);
//
// tsmi_remove_all
//
this.tsmi_remove_all.Name = "tsmi_remove_all";
this.tsmi_remove_all.Size = new System.Drawing.Size(168, 22);
this.tsmi_remove_all.Text = "Remove All";
this.tsmi_remove_all.Click += new System.EventHandler(this.tsmi_remove_all_Click);
//
// ch_hash
//
this.ch_hash.Text = "Hash";
this.ch_hash.Width = 139;
//
// ch_revision
//
this.ch_revision.Text = "TU";
//
// tsmi_remove_duplicates
//
this.tsmi_remove_duplicates.Name = "tsmi_remove_duplicates";
this.tsmi_remove_duplicates.Size = new System.Drawing.Size(168, 22);
this.tsmi_remove_duplicates.Text = "Remove Dulicates";
this.tsmi_remove_duplicates.Click += new System.EventHandler(this.tsmi_remove_duplicates_Click);
//
// frm_game_info_multiple
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(509, 574);
this.Controls.Add(this.lv_main);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.MaximizeBox = false;
this.MinimumSize = new System.Drawing.Size(525, 613);
this.Name = "frm_game_info_multiple";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Game Info";
this.Load += new System.EventHandler(this.frm_game_info_multiple_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pb_package)).EndInit();
this.groupBox3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pb_content)).EndInit();
this.cms_game_info.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.PictureBox pb_package;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.PictureBox pb_content;
private System.Windows.Forms.TextBox tb_fullDirectory;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label lbl_rootFolder;
private System.Windows.Forms.TextBox tb_deviceID;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox tb_titleName;
private System.Windows.Forms.Label lbl_subFolder;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lbl_titleFolder;
private System.Windows.Forms.TextBox tb_consoleID;
private System.Windows.Forms.TextBox tb_profileID;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox tb_display;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox tb_titleID;
private System.Windows.Forms.ListView lv_main;
private System.Windows.Forms.ColumnHeader ch_title;
private System.Windows.Forms.ColumnHeader ch_title_name;
private System.Windows.Forms.ColumnHeader ch_status;
private System.Windows.Forms.ContextMenuStrip cms_game_info;
private System.Windows.Forms.ToolStripMenuItem tsmi_select_all;
private System.Windows.Forms.ToolStripMenuItem tsmi_send;
private System.Windows.Forms.ToolStripMenuItem tsmi_send_selected;
private System.Windows.Forms.ToolStripMenuItem tsmi_send_all;
private System.Windows.Forms.ToolStripMenuItem tsmi_remove;
private System.Windows.Forms.ToolStripMenuItem tsmi_remove_all;
private System.Windows.Forms.ColumnHeader ch_hash;
private System.Windows.Forms.ColumnHeader ch_revision;
private System.Windows.Forms.ToolStripMenuItem tsmi_remove_duplicates;
}
} | 47.305284 | 156 | 0.590163 | [
"MIT"
] | ImSeaWorld/LMAOSoft | LMAOSoft/Inc/Forms/Tools/Game Info/frm_game_info_multiple.Designer.cs | 24,175 | C# |
using System;
namespace uri2763 // Entrada e Saída CPF
{
internal static class Program
{
private static void Main()
{
string cpf = Console.ReadLine();
Console.WriteLine(cpf.Substring(0, 3));
Console.WriteLine(cpf.Substring(4, 3));
Console.WriteLine(cpf.Substring(8, 3));
Console.WriteLine(cpf.Substring(12, 2));
}
}
} | 25.9375 | 52 | 0.566265 | [
"MIT"
] | filimor/uri-online-judge-c-sharp | UriOnlineJudge/Iniciante/uri2763/Program.cs | 418 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Providers.SqlServer;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.MembershipService;
using Orleans.TestingHost.Utils;
using OrleansSQLUtils.Configuration;
using TestExtensions;
using UnitTests.General;
using Xunit;
namespace UnitTests.SqlStatisticsPublisherTests
{
/// <summary>
/// Tests for operation of Orleans Statistics Publisher using relational storage
/// </summary>
[Collection(TestEnvironmentFixture.DefaultCollection)]
public abstract class SqlStatisticsPublisherTestsBase: IClassFixture<ConnectionStringFixture>
{
private readonly TestEnvironmentFixture environment;
protected abstract string AdoInvariant { get; }
private readonly string ConnectionString;
private const string testDatabaseName = "OrleansStatisticsTest";
private readonly Logger logger;
private readonly ILoggerFactory loggerFactory;
private readonly SqlStatisticsPublisher StatisticsPublisher;
protected SqlStatisticsPublisherTestsBase(ConnectionStringFixture fixture, TestEnvironmentFixture environment)
{
this.environment = environment;
this.loggerFactory = TestingUtils.CreateDefaultLoggerFactory($"{this.GetType()}.log");
logger = new LoggerWrapper<SqlStatisticsPublisherTestsBase>(loggerFactory);
fixture.InitializeConnectionStringAccessor(GetConnectionString);
ConnectionString = fixture.ConnectionString;
StatisticsPublisher = new SqlStatisticsPublisher();
StatisticsPublisher.Init("Test", new StatisticsPublisherProviderRuntime(logger),
new StatisticsPublisherProviderConfig(AdoInvariant, ConnectionString)).Wait();
}
protected async Task<string> GetConnectionString()
{
var instance = await RelationalStorageForTesting.SetupInstance(this.AdoInvariant, testDatabaseName);
return instance.CurrentConnectionString;
}
protected async Task SqlStatisticsPublisher_ReportMetrics_Client()
{
StatisticsPublisher.AddConfiguration("statisticsDeployment", "statisticsHostName", "statisticsClient", IPAddress.Loopback);
await RunParallel(10, () => StatisticsPublisher.ReportMetrics((IClientPerformanceMetrics)new DummyPerformanceMetrics()));
}
protected async Task SqlStatisticsPublisher_ReportStats()
{
StatisticsPublisher.AddConfiguration("statisticsDeployment", "statisticsHostName", "statisticsClient", IPAddress.Loopback);
await RunParallel(10, () => StatisticsPublisher.ReportStats(new List<ICounter> { new DummyCounter(),new DummyCounter() }));
}
protected async Task SqlStatisticsPublisher_ReportMetrics_Silo()
{
var options = new SqlMembershipOptions()
{
AdoInvariant = AdoInvariant,
ConnectionString = ConnectionString
};
IMembershipTable mbr = new SqlMembershipTable(this.environment.Services.GetRequiredService<IGrainReferenceConverter>(),
this.environment.Services.GetRequiredService<GlobalConfiguration>(), Options.Create<SqlMembershipOptions>(options),
this.loggerFactory.CreateLogger<SqlMembershipTable>());
await mbr.InitializeMembershipTable(true).WithTimeout(TimeSpan.FromMinutes(1));
StatisticsPublisher.AddConfiguration("statisticsDeployment", true, "statisticsSiloId", SiloAddressUtils.NewLocalSiloAddress(0), new IPEndPoint(IPAddress.Loopback, 12345), "statisticsHostName");
await RunParallel(10, () => StatisticsPublisher.ReportMetrics((ISiloPerformanceMetrics)new DummyPerformanceMetrics()));
}
private Task RunParallel(int count, Func<Task> taskFactory)
{
return Task.WhenAll(Enumerable.Range(0, count).Select(x => taskFactory()));
}
}
} | 44.821053 | 205 | 0.725928 | [
"MIT"
] | seralexeev/orleans | test/TesterSQLUtils/SqlStatisticsPublisherTests/SqlStatisticsPublisherTestsBase.cs | 4,260 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JokeGenerator
{
class UserInputProcessor
{
public static int ProcessUserInput(string[] userAnswers, int userStep, string[] categoryOptions)
{
string randomName = "";
if (userAnswers[0].ToLower() == "c")
DisplayCategories(categoryOptions);
if (userStep == 4)
{
if (userAnswers[1].ToLower() == "y")
randomName = GenerateRandomName();
DisplayJokesToUser(userAnswers[3].ToString(), randomName, Int32.Parse(userAnswers[4]), 0);
}
return ControlUserStep(userAnswers, userStep);
}
private static void DisplayCategories(string[] categoryOptions)
{
for (int i = 0; i < categoryOptions.Length; i++)
{
Console.WriteLine(categoryOptions[i]);
}
}
public static int ControlUserStep(string[] userAnswers, int userStep)
{
if (userAnswers[0].ToLower() == "c")
userStep--;
if (userAnswers[2].ToLower() == "n" && userStep == 2)
userStep++;
userStep++;
if (userStep == 5)
userStep = 0;
return userStep;
}
public static string GenerateRandomName()
{
dynamic holdValue = RandomNameCall.GetRandomName();
return holdValue.name + " " + holdValue.surname;
}
public static void DisplayJokesToUser(string selectedCategory, string randomName, int selectedNumberOfJokes, int jokesDisplayedToUser)
{
string[] generatedJoke = RandomJokeCall.GetRandomJoke(selectedCategory);
if (!String.IsNullOrEmpty(randomName))
generatedJoke[0] = generatedJoke[0].Replace("Chuck Norris", randomName);
Console.WriteLine(generatedJoke[0]);
jokesDisplayedToUser++;
if (selectedNumberOfJokes != jokesDisplayedToUser)
DisplayJokesToUser(selectedCategory, randomName, selectedNumberOfJokes, jokesDisplayedToUser);
}
}
}
| 30.891892 | 142 | 0.572616 | [
"MIT"
] | Sceviour/JokeGenerator | ConsoleApp1/UserInputProcessor.cs | 2,288 | C# |
using System.Collections.Generic;
using NUnit.Framework;
namespace TddKitCsharp
{
[TestFixture]
public class FizzbuzzTest
{
private IList<string> _elements;
[SetUp]
public void SetUp()
{
_elements = new Fizzbuzz().Elements();
}
[Test]
public void should_return_100_elements()
{
Assert.That(_elements.Count, Is.EqualTo(100));
}
[Test]
public void should_return_1_for_1()
{
Assert.That(FizzBuzzOf(1), Is.EqualTo("1"));
}
[Test]
public void should_return_fizz_for_3()
{
Assert.That(FizzBuzzOf(3), Is.EqualTo("fizz"));
}
[Test]
public void should_return_buzz_for_5()
{
Assert.That(FizzBuzzOf(5), Is.EqualTo("buzz"));
}
[Test]
public void should_return_fizzbuzz_for_15()
{
Assert.That(FizzBuzzOf(15), Is.EqualTo("fizzbuzz"));
}
private string FizzBuzzOf(int number)
{
return _elements[number - 1];
}
}
} | 21.75 | 64 | 0.530504 | [
"MIT"
] | arpinum/formation-tdd-dec2015 | tdd-kit/tdd-kit-csharp/TddKitCsharp/FizzbuzzTest.cs | 1,133 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using OrchardCore.Contents.AuditTrail.Models;
namespace DFC.ServiceTaxonomy.VersionComparison.Services
{
public interface IAuditTrailQueryService
{
Task<List<AuditTrailContentEvent>> GetVersions(string contentItemId);
}
}
| 25.666667 | 77 | 0.792208 | [
"MIT"
] | SkillsFundingAgency/dfc-servicetaxonomy-editor | DFC.ServiceTaxonomy.VersionComparison/Services/IAuditTrailQueryService.cs | 310 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.